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,485,798
[ 1, 146, 230, 146, 232, 146, 230, 145, 117, 146, 235, 145, 113, 146, 229, 146, 239, 146, 228, 146, 242, 225, 145, 126, 145, 113, 225, 145, 126, 145, 118, 146, 228, 145, 123, 145, 127, 145, 124, 146, 239, 145, 123, 145, 127, 225, 145, 128, 146, 227, 145, 127, 146, 233, 145, 118, 145, 126, 146, 229, 145, 127, 145, 115, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 436, 407, 67, 502, 2038, 30, 146, 230, 146, 232, 146, 230, 145, 117, 146, 235, 145, 113, 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 ]
./partial_match/421613/0xE6Db969E4d0615F1A6071e8F806055662676cEF6/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
* @dev Gets the configuration paramters of the reserve from a memory object @param self The reserve configuration @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals/
function getParamsMemory( DataTypes.ReserveConfigurationMap memory self ) internal pure returns (uint256, uint256, uint256, uint256, uint256, uint256) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION, (self.data & ~CREDIT_RESERVE_FACTOR_MASK) >> CREDIT_RESERVE_FACTOR_START_BIT_POSITION ); }
16,825,003
[ 1, 3002, 326, 1664, 579, 5432, 434, 326, 20501, 628, 279, 3778, 733, 225, 365, 1021, 20501, 1664, 327, 1021, 919, 859, 5123, 13489, 90, 16, 4501, 26595, 367, 5573, 16, 4501, 26595, 367, 324, 22889, 16, 326, 20501, 15105, 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, 13281, 6031, 12, 203, 565, 1910, 2016, 18, 607, 6527, 1750, 863, 3778, 365, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 288, 203, 565, 327, 261, 203, 1377, 365, 18, 892, 473, 4871, 12050, 58, 67, 11704, 16, 203, 1377, 261, 2890, 18, 892, 473, 4871, 2053, 53, 3060, 2689, 67, 23840, 67, 11704, 13, 1671, 8961, 53, 3060, 2689, 67, 23840, 67, 7570, 67, 15650, 67, 15258, 16, 203, 1377, 261, 2890, 18, 892, 473, 4871, 2053, 53, 3060, 2689, 67, 38, 673, 3378, 67, 11704, 13, 1671, 8961, 53, 3060, 2689, 67, 38, 673, 3378, 67, 7570, 67, 15650, 67, 15258, 16, 203, 1377, 261, 2890, 18, 892, 473, 4871, 23816, 55, 67, 11704, 13, 1671, 2438, 2123, 3412, 67, 23816, 55, 67, 7570, 67, 15650, 67, 15258, 16, 203, 1377, 261, 2890, 18, 892, 473, 4871, 862, 2123, 3412, 67, 26835, 67, 11704, 13, 1671, 2438, 2123, 3412, 67, 26835, 67, 7570, 67, 15650, 67, 15258, 16, 203, 1377, 261, 2890, 18, 892, 473, 4871, 5458, 40, 1285, 67, 862, 2123, 3412, 67, 26835, 67, 11704, 13, 1671, 385, 5879, 1285, 67, 862, 2123, 3412, 67, 26835, 67, 7570, 67, 15650, 67, 15258, 203, 565, 11272, 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 ]
./full_match/1/0x8A9896b8d61cA66A231E9CF224DD4d80643e3CA1/sources/contracts/JBProjects.sol
/ Increment the count, which will be used as the ID. Mint the project. Set the metadata if one was provided.
function createFor( address _owner, JBProjectMetadata calldata _metadata ) external override returns (uint256 projectId) { projectId = ++count; _safeMint(_owner, projectId); if (bytes(_metadata.content).length > 0) metadataContentOf[projectId][_metadata.domain] = _metadata.content; emit Create(projectId, _owner, _metadata, msg.sender); } Allows a project owner to set the project's metadata content for a particular domain namespace. @dev Only a project's owner or operator can set its metadata. @dev Applications can use the domain namespace as they wish. @param _projectId The ID of the project who's metadata is being changed. @param _metadata A struct containing metadata content, and domain within which the metadata applies.
2,938,970
[ 1, 19, 17883, 326, 1056, 16, 1492, 903, 506, 1399, 487, 326, 1599, 18, 490, 474, 326, 1984, 18, 1000, 326, 1982, 309, 1245, 1703, 2112, 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 ]
[ 1, 1, 1, 1, 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, 752, 1290, 12, 203, 565, 1758, 389, 8443, 16, 203, 565, 804, 38, 4109, 2277, 745, 892, 389, 4165, 203, 225, 262, 3903, 3849, 1135, 261, 11890, 5034, 9882, 13, 288, 203, 565, 9882, 273, 965, 1883, 31, 203, 203, 565, 389, 4626, 49, 474, 24899, 8443, 16, 9882, 1769, 203, 203, 565, 309, 261, 3890, 24899, 4165, 18, 1745, 2934, 2469, 405, 374, 13, 203, 1377, 1982, 1350, 951, 63, 4406, 548, 6362, 67, 4165, 18, 4308, 65, 273, 389, 4165, 18, 1745, 31, 203, 203, 565, 3626, 1788, 12, 4406, 548, 16, 389, 8443, 16, 389, 4165, 16, 1234, 18, 15330, 1769, 203, 225, 289, 203, 203, 565, 25619, 279, 1984, 3410, 358, 444, 326, 1984, 1807, 1982, 913, 364, 279, 6826, 2461, 1981, 18, 7010, 203, 565, 632, 5206, 7010, 565, 5098, 279, 1984, 1807, 3410, 578, 3726, 848, 444, 2097, 1982, 18, 203, 203, 565, 632, 5206, 7010, 565, 4257, 87, 848, 999, 326, 2461, 1981, 487, 2898, 14302, 18, 203, 203, 565, 632, 891, 389, 4406, 548, 1021, 1599, 434, 326, 1984, 10354, 1807, 1982, 353, 3832, 3550, 18, 203, 565, 632, 891, 389, 4165, 432, 1958, 4191, 1982, 913, 16, 471, 2461, 3470, 1492, 326, 1982, 10294, 18, 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 ]
import "../../interfaces/IWETH.sol"; import "../../interfaces/IDeltaToken.sol"; import "../../interfaces/IRebasingLiquidityToken.sol"; import '../uniswapv2/libraries/UniswapV2Library.sol'; import '../Upgradability/token/ERC20/ERC20Upgradeable.sol'; interface IRESERVE_VAULT { function flashBorrowEverything() external; } interface IDELTA_LSW { function totalWETHEarmarkedForReferrers() external view returns (uint256); } contract DELTA_Rebasing_Liquidity_Token is IRebasingLiquidityToken, ERC20Upgradeable { using SafeMathUpgradeable for uint256; struct AddressCache { address deltaxWethPairAddress; IDeltaToken deltaToken; IUniswapV2Pair deltaxWethPair; } uint256 public override rlpPerLP; uint256 public _dailyVolumeTargetETH; uint256 private lastTargetUpdate; uint256 public ethVolumeRemaining; //immutables and contstancts IUniswapV2Pair public immutable DELTA_WETH_PAIR; IDeltaToken public immutable DELTA; address constant internal DEAD_BEEF = 0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF; address public constant LSW = 0xdaFCE5670d3F67da9A3A44FE6bc36992e5E2beaB; address public immutable RESERVE_VAULT; IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 constant public _DAILY_PERCENTAGE_COST_INCREASE_TO_MINT_LP = 10; function initialize() public virtual initializer { __ERC20_init("Rebasing Liquidity Token - DELTA.financial", "DELTA rLP"); // Name, symbol // Initially set it to 1LP = 1RLP rlpPerLP = 1 ether; } // Rebasing LP is created before DELTA TOKEN is. constructor (address delta, address _reserveVault ) { //LSW call points RESERVE_VAULT = _reserveVault; DELTA = IDeltaToken(delta); DELTA_WETH_PAIR = IUniswapV2Pair(address(uint(keccak256(abi.encodePacked( hex'ff', 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, // Mainnet uniswap factory keccak256(abi.encodePacked(delta, address(WETH))), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); } function onlyLSW() public view { require(msg.sender == LSW, "!LSW GO AWAY"); } // Do not remove this as this is called from the LSW function setBaseLPToken(address) public { onlyLSW(); this; // sincence warnings } // @notice wraps all LP tokens of the caller, requires allowance // @dev intent of this function is to get the balance of the caller, and wrap his entire balance, update the basetoken supply, and issue the caller amount of tokens that we transfered from him function wrap() public override { _performWrap(); // This doesn't return because LSW doesn't expect a return value and we can't adjust it now. } function wrapWithReturn() external override returns (uint256) { return _performWrap(); } function _performWrap() internal returns (uint256) { uint256 balanceCaller = DELTA_WETH_PAIR.balanceOf(msg.sender); require(balanceCaller > 0, "No tokens to wrap"); // @dev from caller , to here , amount total of caller bool success = DELTA_WETH_PAIR.transferFrom(msg.sender, address(this), balanceCaller); require(success, "Transfer Failure"); uint256 garnishedBalance = balanceCaller.mul(rlpPerLP).div(1e18); _mint(msg.sender, garnishedBalance); return garnishedBalance; } function rebase() public { require(msg.sender == tx.origin, "Smart wallets cannot call this function"); uint256 deltaBalance = DELTA.balanceOf(address(this)); if(deltaBalance > 0) { // remove if we have DELTA in here for some reason DELTA.transfer(RESERVE_VAULT, deltaBalance); } // Collect pre-rebasing stats (uint256 preVolumeDELTAReserve, uint256 preVolumeWETHReserve,) = DELTA_WETH_PAIR.getReserves(); uint256 preVolumeLPSupply = DELTA_WETH_PAIR.totalSupply(); uint256 preVolumeLPBalance = DELTA_WETH_PAIR.balanceOf(address(this)); // Have the delta token allow for burning of LP, temporarily. // This will call tokenCaller and them proceed to call reserveCaller and to numberLoops of max transfers // And re-add LP tokens payback loan... hence we wrap this in few safety checks DELTA.performLiquidityRebasing(); // calls >tokenCaller >reserveCaller on this contract in order // Collect post-rebasing stats (uint256 postVolumeDELTAReserve, uint256 postVolumeWETHReserve,) = DELTA_WETH_PAIR.getReserves(); uint256 postVolumeLPSupply = DELTA_WETH_PAIR.totalSupply(); uint256 postVolumeLPBalance = DELTA_WETH_PAIR.balanceOf(address(this)); // All my homies hate division // WHERE IS MY FUCKING MONEY? require(postVolumeDELTAReserve == preVolumeDELTAReserve, "Delta reserve has changed"); require(preVolumeWETHReserve + 10 > postVolumeWETHReserve && postVolumeWETHReserve >= preVolumeWETHReserve , "WETH reserve out of bounds"); require(preVolumeLPBalance + 1e4 >= postVolumeLPBalance && postVolumeLPBalance + 1e5 > preVolumeLPBalance , "LP balance change not within bounds"); require(preVolumeLPSupply + 1e4 >= postVolumeLPSupply && postVolumeLPSupply + 1e5 > preVolumeLPSupply, "LP Supply change not within bounds"); } // Delta token calls this after performLiquidityRebasing is in the middle of execution on the token contract function tokenCaller() override public { require(msg.sender == address(DELTA)); IRESERVE_VAULT(RESERVE_VAULT).flashBorrowEverything(); } function volumeGeneratingTrades( IDeltaToken _delta, IUniswapV2Pair _pair, uint256 ethTradeVolumeNeededToHitTarget) internal returns (uint256 newVolumeETHRemaining) { uint256 balanceWETH = WETH.balanceOf(address(this)); (uint256 unsiwapReserveDelta, uint256 uniswapReserveWETH, ) = _pair.getReserves(); uint256 amount0In = unsiwapReserveDelta.mul(1e12).div(uniswapReserveWETH).mul(balanceWETH).div(1e12); // Amount DELTA to send every transfer to get balanceWETH if there was no fee uint256 amount0Out = amount0In * 10000/10161; // 0.6% slippage + ineffciencies; address addressPair = address(_pair); uint256 loops; while(loops < 50) { WETH.transfer(addressPair, balanceWETH); _delta.adjustBalanceOfNoVestingAccount(addressPair, amount0In, true); // Add the amountIn back uniswap treats it like a transfer and we dont have to guarantee that we have that delta // DELTA + WETH for DELTA * 0.994 + WETH // Quadruple WETH in volume _pair.swap(amount0Out, balanceWETH, address(this), ""); _delta.adjustBalanceOfNoVestingAccount(addressPair, unsiwapReserveDelta, false); // Adjust back to reserves ( would have higher else and print dragonflies) _pair.sync(); // Force reserves to show that // Note that WETH balance will not change if(balanceWETH > ethTradeVolumeNeededToHitTarget) { return 0; } else { ethTradeVolumeNeededToHitTarget -= balanceWETH; loops++; } } // This can be non 0 if we are over 50 loops which is straining this algorithm newVolumeETHRemaining = ethTradeVolumeNeededToHitTarget; } function setUpDailyVolumeTarget(uint256 ethWholeUnits, bool hourlyRebaseRightAway) public { onlyMultisig(); _dailyVolumeTargetETH = ethWholeUnits * 1 ether; lastTargetUpdate = hourlyRebaseRightAway ? block.timestamp - 1 hours : block.timestamp; // can rebase right away rebase } function getRemainingETHInVolumeTarget() public view returns (uint256 remainingVolumeInETH, uint256 secondsSinceLastUpdate) { secondsSinceLastUpdate = (block.timestamp - lastTargetUpdate); uint256 hoursSinceLastUpdate = secondsSinceLastUpdate / 1 hours; remainingVolumeInETH = (_dailyVolumeTargetETH / 24).mul(hoursSinceLastUpdate).add(ethVolumeRemaining); // We dont allow partial hours to not have too much volume from calls } function updateRemainingETH() private returns (uint256) { (uint256 remainingVolumeInETH, uint256 secondsSinceLastUpdate) = getRemainingETHInVolumeTarget(); lastTargetUpdate = block.timestamp - (secondsSinceLastUpdate % 1 hours); // we carry over the rest of 1hour return remainingVolumeInETH; } function reduceLpRatio(uint256 percentReductionE12) private { uint256 ratio = rlpPerLP; rlpPerLP = ratio.sub( ratio.mul(percentReductionE12).div(1e14) ); } // The delta reserve calls this during execution in order to complete flash borrowing function reserveCaller(uint256 borrowedDELTA, uint256 borrowedWETH) public override { // Reserve vault calls this contract with the amount of DELTA and WETH it borrowed to us. // 1) We find a optimal DELTA to add with all the WETH to get LP tokens // 2) We burn half of all LP tokens we have ( the newly minted + ones in this contract) // Only half can be traded at a time because of uniswap reserve requirements // 3) We do loop of DELTA and WETH trades for DELTA and WETH. With every time removing 0.6% of delta we expect to pay the fee (0.3*2) // 4) We sell DELTA to get WETH // 5) We keep changing the uniswap balance and adding more and more liquidity in a loop until we have enough to cover what we had before // trading loses us lp tokens, because the ones remaining in the pool concentrate fees // 6) We adjust the uniswap balance to thee previos state in order to avoid price changing // 7) We repay the loan // 8) We adjust the uniswap DELTA reciever ratio, in order to make LP tokens more to mint // We have to take into account the totalSupply change in LP tokens require(msg.sender == RESERVE_VAULT); // We update the target timestamp and consume all remaining ETH that was unspent. uint256 ethTradeVolumeNeededToHitTarget = updateRemainingETH(); require(ethTradeVolumeNeededToHitTarget > 0, "Can't generate volume, wait until a full hour still last targetUpdate is up"); uint256 balanceLPBeforeMintingAndRebasing = DELTA_WETH_PAIR.balanceOf(address(this)); // We got a loan from reserve vault // We have to figure out how to utilize it (uint256 unsiwapReserveDelta, uint256 uniswapReserveWETH,) = DELTA_WETH_PAIR.getReserves(); // If we borrowed WETH, we mint if(borrowedWETH > 0) { uint256 balanceWETHWithLoan = WETH.balanceOf(address(this)); uint256 optimalDELTAToMatchAllWETH = UniswapV2Library.quote(balanceWETHWithLoan, uniswapReserveWETH, unsiwapReserveDelta); // Send everything to add liquidity DELTA.adjustBalanceOfNoVestingAccount(address(DELTA_WETH_PAIR), optimalDELTAToMatchAllWETH, true); WETH.transfer(address(DELTA_WETH_PAIR), balanceWETHWithLoan); DELTA_WETH_PAIR.mint(address(this)); } // We remove half of the liquidity // Note that half is the max because you cant get out more than reserves // Half is when we have all teh lp tokens DELTA_WETH_PAIR.transfer(address(DELTA_WETH_PAIR), DELTA_WETH_PAIR.balanceOf(address(this)) / 2); DELTA_WETH_PAIR.burn(address(this)); // Perform volume trades, and reduce LP ratio based on the volume that gets filled successfully { // scope for unfilledEthVolumeRemaining, newRatio uint256 unfilledEthVolumeRemaining = volumeGeneratingTrades(DELTA, DELTA_WETH_PAIR, ethTradeVolumeNeededToHitTarget); uint256 volumeFulfilled = ethTradeVolumeNeededToHitTarget.sub(unfilledEthVolumeRemaining); uint256 lpRatioPercentReductionE12 = volumeFulfilled.mul(1e12).div(_dailyVolumeTargetETH).mul(_DAILY_PERCENTAGE_COST_INCREASE_TO_MINT_LP); // Adjust the ratio by the remianing eth to trade // If its 10% a day this should return 10/24 for every hour of volume = 0.41 * 1e12 = 410000000000; reduceLpRatio(lpRatioPercentReductionE12); ethVolumeRemaining = unfilledEthVolumeRemaining; } // At this point we have either too much or too little LP tokens // Since we borrowed we might have too much // Or we might have too little depending on when borrowed is less adding it than we already have // We branch the logic dependent on it uint256 balanceLPNow = DELTA_WETH_PAIR.balanceOf(address(this)); if(balanceLPNow > balanceLPBeforeMintingAndRebasing) { // We have more or exactly the balance we had before // We burn the difference uint256 difference = balanceLPNow - balanceLPBeforeMintingAndRebasing; DELTA_WETH_PAIR.transfer(address(DELTA_WETH_PAIR), difference); DELTA_WETH_PAIR.burn(address(this)); DELTA.adjustBalanceOfNoVestingAccount(address(DELTA_WETH_PAIR), unsiwapReserveDelta, false); } else { // Since we dont let accumulation to happen in the tokens vy adjusting balances directly // we can safely assume we just need to give back the WETH and DELTA back to previous levels to get LP tokens we need // This assumpion is changed in a function wrapping this one (, uint256 currentUniswapReserveWETH,) = DELTA_WETH_PAIR.getReserves(); // Reserve has too little WETH // We need to send the difference // Note this is also the case when we have less LP tokens than we should // Fees have not accumulated in the remaining supply of tokens as the reserves did not change uint256 ethNeeded = uniswapReserveWETH.sub(currentUniswapReserveWETH); if(ethNeeded > 0) { WETH.transfer(address(DELTA_WETH_PAIR), ethNeeded); DELTA.adjustBalanceOfNoVestingAccount(address(DELTA_WETH_PAIR), unsiwapReserveDelta, false); DELTA_WETH_PAIR.mint(address(this)); } // Reserves now have as much DELTA and WETH as they should. } if(borrowedWETH > 0) { // repay weth loan // note that reserves match up with weth it coudnt have gone anywhere but to us, but this convinently tests that too WETH.transfer(RESERVE_VAULT, WETH.balanceOf(address(this))); // -1 inefficiencies DELTA.adjustBalanceOfNoVestingAccount(RESERVE_VAULT, borrowedDELTA, true); } DELTA_WETH_PAIR.sync(); // We directly set the balance of this address to 0 DELTA.adjustBalanceOfNoVestingAccount(address(this), 0, false); } /// @notice opens the first rebasing function openRebasing() public { onlyLSW(); require(rlpPerLP == 1e18, "Contract not initialized"); // we check how much LP we have // This call only happens once so we can assume a lot here uint256 totalETHInLSW = (1500 ether + WETH.balanceOf(RESERVE_VAULT) + IDELTA_LSW(LSW).totalWETHEarmarkedForReferrers()) * 2; uint256 totalInPairRatioE12 = uint256(1500 ether).mul(1e12).div(totalETHInLSW); rlpPerLP = totalInPairRatioE12.mul(1e6); // 18 - 12 //One LP equal RLP 86606638913000000 (0.0866066389130000) } function onlyMultisig() private view { require(msg.sender == DELTA.governance(), "!governance"); } } pragma solidity >=0.6.0 <0.8.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; function balanceOf(address) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma experimental ABIEncoderV2; pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../common/OVLTokenTypes.sol"; interface IDeltaToken is IERC20 { function vestingTransactions(address, uint256) external view returns (VestingTransaction memory); function getUserInfo(address) external view returns (UserInformationLite memory); function getMatureBalance(address, uint256) external view returns (uint256); function liquidityRebasingPermitted() external view returns (bool); function lpTokensInPair() external view returns (uint256); function governance() external view returns (address); function performLiquidityRebasing() external; function distributor() external view returns (address); function totalsForWallet(address ) external view returns (WalletTotals memory totals); function adjustBalanceOfNoVestingAccount(address, uint256,bool) external; function userInformation(address user) external view returns (UserInformation memory); } pragma experimental ABIEncoderV2; pragma solidity ^0.7.6; import "./IERC20Upgradeable.sol"; interface IRebasingLiquidityToken is IERC20Upgradeable { function tokenCaller() external; function reserveCaller(uint256,uint256) external; function wrapWithReturn() external returns (uint256); function wrap() external; function rlpPerLP() external view returns (uint256); } pragma solidity ^0.7.6; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import "./SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap for uint; // 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, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(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(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../utils/ContextUpgradeable.sol"; import "../../../../interfaces/IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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: * * - `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 virtual { _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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: UNLICENSED // DELTA-BUG-BOUNTY pragma solidity ^0.7.6; struct VestingTransaction { uint256 amount; uint256 fullVestingTimestamp; } struct WalletTotals { uint256 mature; uint256 immature; uint256 total; } struct UserInformation { // This is going to be read from only [0] uint256 mostMatureTxIndex; uint256 lastInTxIndex; uint256 maturedBalance; uint256 maxBalance; bool fullSenderWhitelisted; // Note that recieving immature balances doesnt mean they recieve them fully vested just that senders can do it bool immatureReceiverWhitelisted; bool noVestingWhitelisted; } struct UserInformationLite { uint256 maturedBalance; uint256 maxBalance; uint256 mostMatureTxIndex; uint256 lastInTxIndex; } struct VestingTransactionDetailed { uint256 amount; uint256 fullVestingTimestamp; // uint256 percentVestedE4; uint256 mature; uint256 immature; } uint256 constant QTY_EPOCHS = 7; uint256 constant SECONDS_PER_EPOCH = 172800; // About 2days uint256 constant FULL_EPOCH_TIME = SECONDS_PER_EPOCH * QTY_EPOCHS; // Precision Multiplier -- this many zeros (23) seems to get all the precision needed for all 18 decimals to be only off by a max of 1 unit uint256 constant PM = 1e23; // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } 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; } pragma solidity >=0.5.0; 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; } pragma solidity ^0.7.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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. */ 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 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; } // 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 SafeMathUpgradeable { /** * @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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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); } } } }
remove if we have DELTA in here for some reason
if(deltaBalance > 0) {
11,806,296
[ 1, 4479, 309, 732, 1240, 2030, 48, 9833, 316, 2674, 364, 2690, 3971, 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, 3639, 309, 12, 9878, 13937, 405, 374, 13, 288, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../libs/SafeMath.sol"; import "../libs/SwapUtilities.sol"; import "./BEP20WithFee.sol"; contract FarmVault { constructor() public { } } abstract contract BEP20WithFarmRouter is BEP20WithFee { using SafeMath for uint256; // --==[ Strategies ]==-- uint256 private constant FARM_STRATEGY_SELL_DIRECTLY = 1; uint256 private constant FARM_STRATEGY_SELL_VIA_CONTRACT = 2; uint256 private farm_strategy; // --==[ FEES ]==-- // Fees numbers are multiplied by 100 uint256 public farmRewardDistribution = 5000; // 50% // --==[ WALLETS ]==-- address public farmSink; address public farmVault; // --==[ Events ]==-- event FarmRewarded(uint256 amount, uint256 strategy); bool public isFarmSinkActive = true; bool public isFarmRewardingActive = true; uint256 public farmNumberOfTokensToSell = 8888e18; constructor(string memory name, string memory symbol) BEP20WithFee(name, symbol) internal { farm_strategy = FARM_STRATEGY_SELL_DIRECTLY; farmSink = _msgSender(); farmVault = address(new FarmVault()); } function setFarmRewardDistribution(uint256 distribution) onlyOwner external { require(distribution <= 10000, "BEP20WithFarmRouter: distribution should be less than 100%"); farmRewardDistribution = distribution; } function setFarmSink(address destination) onlyOwner external { require(destination != address(0), "BEP20WithFarmRouter: farm sink can't be zero address"); farmSink = destination; } function setFarmStrategy(uint256 strategy) onlyOwner external { farm_strategy = strategy; } function setFarmSinkActive(bool isActive) onlyOwner external { isFarmSinkActive = isActive; } function setFarmRewardingActive(bool isActive) onlyOwner external { isFarmRewardingActive = isActive; } function setFarmNumberOfTokensToSell(uint256 numberOfTokens) onlyOwner external { farmNumberOfTokensToSell = numberOfTokens; } // --==[ Overridden methods ]==-- function _transfer(address from, address to, uint256 amount) override internal virtual { bool overMinTokenBalance = BEP20.balanceOf(farmVault) >= farmNumberOfTokensToSell; bool internalSwap = (from == address(this) && isPair(to)); // don't trigger infinite loop if ( isFarmRewardingActive && !internalSwap && !isPair(from) && overMinTokenBalance && !isLocked() ) { forwardRewardsToSink(farmNumberOfTokensToSell); } super._transfer(from, to, amount); } function addRewards(address from, uint256 amount) override internal { uint256 rewardAmount = amount; if (isFarmSinkActive) { uint256 farmAmount = amount.mul(farmRewardDistribution).div(10000); BEP20._transfer(from, farmVault, farmAmount); rewardAmount = amount.sub(farmAmount); } // transfer rewards from payer to contract address super.addRewards(from, rewardAmount); } // for testing purposes function triggerForwardRewardsToSink(uint256 amount) external onlyOwner { require(BEP20.balanceOf(farmVault) >= amount, "BEP20WithFarmRouter: insufficient vault balance"); forwardRewardsToSink(amount); } function forwardRewardsToSink(uint256 amount) private lock { if (amount == 0 || farmSink == address(0) || swapRouter == address(0)) return; if (farm_strategy == FARM_STRATEGY_SELL_DIRECTLY) { farmRouterTransfer1(amount); } else if (farm_strategy == FARM_STRATEGY_SELL_VIA_CONTRACT) { farmRouterTransfer2(amount); } } function farmRouterTransfer1(uint256 amount) private { BEP20._transfer(farmVault, address(this), amount); _approve(address(this), swapRouter, amount); SwapUtilities.swapTokensForETH(swapRouter, address(this), farmSink, amount, swapRouterSellTimeout); emit FarmRewarded(amount, FARM_STRATEGY_SELL_DIRECTLY); } function farmRouterTransfer2(uint256 amount) private { BEP20._transfer(farmVault, address(this), amount); _approve(address(this), swapRouter, amount); uint256 balanceBeforeSwap = address(this).balance; SwapUtilities.swapTokensForETH(swapRouter, address(this), address(this), amount, swapRouterSellTimeout); uint256 rewardAmount = address(this).balance.sub(balanceBeforeSwap); payable(farmSink).transfer(rewardAmount); emit FarmRewarded(amount, FARM_STRATEGY_SELL_VIA_CONTRACT); } }
--==[ Overridden methods ]==--
function _transfer(address from, address to, uint256 amount) override internal virtual { bool overMinTokenBalance = BEP20.balanceOf(farmVault) >= farmNumberOfTokensToSell; if ( isFarmRewardingActive && !internalSwap && !isPair(from) && overMinTokenBalance && !isLocked() ) { forwardRewardsToSink(farmNumberOfTokensToSell); } super._transfer(from, to, amount); }
13,030,380
[ 1, 413, 631, 63, 531, 1107, 2794, 2590, 308, 631, 413, 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, 389, 13866, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 3849, 2713, 5024, 288, 203, 3639, 1426, 1879, 2930, 1345, 13937, 273, 9722, 52, 3462, 18, 12296, 951, 12, 74, 4610, 12003, 13, 1545, 284, 4610, 9226, 5157, 774, 55, 1165, 31, 203, 203, 3639, 309, 261, 203, 5411, 17646, 4610, 17631, 1060, 310, 3896, 597, 203, 5411, 401, 7236, 12521, 597, 203, 5411, 401, 291, 4154, 12, 2080, 13, 597, 203, 5411, 1879, 2930, 1345, 13937, 597, 203, 5411, 401, 291, 8966, 1435, 203, 3639, 262, 288, 203, 5411, 5104, 17631, 1060, 11634, 11326, 12, 74, 4610, 9226, 5157, 774, 55, 1165, 1769, 203, 3639, 289, 203, 3639, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 3844, 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 ]
// File contracts/library/SeedRand.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.1; library SeedRand { function rand( uint256 _seed, uint256 _index ) internal pure returns (uint256 val) { unchecked { val = uint256(keccak256(abi.encodePacked( _seed, _index ))); } } function randUint256( uint256 _seed, uint256 _index, uint256 n ) internal pure returns (uint256) { require(n > 0, "SeedRand#randUint256: n must be positive"); uint256 val; uint256 div = type(uint256).max / n; do { val = rand(_seed, _index); } while (val >= div * n); return val % n; } function range( uint256 _seed, uint256 _index, uint256 min, uint256 max ) internal pure returns (uint256) { return min + randUint256(_seed, _index, max - min); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.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); } // File contracts/interface/IShogunate.sol interface IShogunate is IERC721, IERC721Metadata { /** * Method to return the soul of a Shogunate NFT. The soul contains all of the * attributes of the Shogunate NFT. * @param _tokenId - The ID of the token to return the soul of. */ function soulOf(uint256 _tokenId) external view returns (bytes32); /** * Method to return the clan of a Shogunate NFT. * @param _tokenId - The ID of the token to return the clan of. */ function clanOf(uint256 _tokenId) external view returns (uint8); /** * Method to return the token ID of the shogun of a clan. * @param _clanId - The ID of the clan to return the shogun of. */ function shogunOf(uint8 _clanId) external view returns (uint256); /** * Method to check if a token is a shogun or not * @param _tokenId = The ID of the token to test */ function isShogun(uint256 _tokenId) external view returns (bool); /** * Method to check if tokenId exists */ function exists(uint256 _tokenId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 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); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/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 @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @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/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.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 { _setApprovalForAll(_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); _afterTokenTransfer(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); _afterTokenTransfer(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 from incorrect owner"); 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); _afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).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(base, _tokenURI)); } return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File @openzeppelin/contracts/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.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 = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 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)); } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.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); } } // File @openzeppelin/contracts/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/Pausable.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 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] // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.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 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 making 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 contracts/interface/IERC721Subscriber.sol interface IERC721Subscriber { /** * Method called when a token is transferred * @param from - The address the token is being transferred from * @param to - The address the token is being transferrd to * @param tokenId - The token ID being transferred */ function onERC721Transferred( address from, address to, uint256 tokenId ) external; } // File contracts/ERC721Transmitter.sol abstract contract ERC721Transmitter is ERC721 { // Subscriber to transmit data to IERC721Subscriber public subscriber; // Contract-wide transmission toggle bool public contractDataTransmissionPaused = false; // Token specific transmission opt-out choices mapping(uint256 => bool) public dataTransmissionPaused; /** * @dev Internal method to pause a token data transmission * @param tokenId - The token ID to pause the data transmission of * @param paused - True to pause, false to unpause */ function _pauseTokenDataTransmission(uint256 tokenId, bool paused) internal { dataTransmissionPaused[tokenId] = paused; } /** * @dev Internal method to pause data transmission for the whole contract. * @param paused - True to pause, false to unpause */ function _pauseContractDataTransmission(bool paused) internal { contractDataTransmissionPaused = paused; } function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._afterTokenTransfer(from, to, tokenId); if ( !contractDataTransmissionPaused && !dataTransmissionPaused[tokenId] && address(subscriber) != address(0) ) { subscriber.onERC721Transferred(from, to, tokenId); } } } // File contracts/AbstractShogunate.sol abstract contract AbstractShogunate is IShogunate, ERC721, ERC721URIStorage, ERC721Transmitter, Ownable, ReentrancyGuard { using ECDSA for bytes32; using Address for address; using Strings for uint256; // Max commits per transaction uint256 constant public MAX_COMMIT_PER_TX = 10; // Max reveals per transaction uint256 constant public MAX_REVEAL_PER_TX = 10; // Next ID to generate uint256 public nextId = 1; // Total Shogunate supply, including both Samurai and Shoguns uint256 public totalSupply = 0; // Mapping from tokenId to soul mapping(uint256 => bytes32) souls; // Mapping from clan to shogun tokenId mapping(uint8 => uint256) internal shogunIds; // Open time of the reveal phase uint256 public revealOpen; // Max supply uint256 immutable public maxTokens; /** * Event emitted when a tokenId is comitted in exchange for a mint pass * @param account - Account that comitted the token * @param tokenId - The ID of the comitted token */ event Commited(address indexed account, uint256 tokenId); /** * Event emitted when a tokenId is revealed. * Can be called by anyone, but token always goes to the user who committed * it. * @param tokenId - The revealed token ID * @param soul - The soul of the revealed token */ event NewSoul(uint256 indexed tokenId, bytes32 soul); // Address that can allow metadata migrations address public migrator; // Default base URI for all Samurai and Shoguns string public defaultURI; // keccak256 hash of the probability tables to use. bytes32 public tablesHash; /** * Represents a commit. */ struct RevealCommit { // User that committed the token, and will receive it once revealed. address receiver; // Block number that the commit has been done at. uint256 blockNumber; } // Mapping from tokenId to commit data mapping(uint256 => RevealCommit) public revealCommits; // Mapping from block number to block hash mapping(uint256 => bytes32) public blockhashesStore; // Last block that a commit was done at uint256 public lastCommitBlock; constructor( string memory _defaultURI, uint256 _revealOpen, uint256 _maxTokens, address _migrator, bytes32 _tablesHash ) { defaultURI = _defaultURI; revealOpen = _revealOpen; maxTokens = _maxTokens; migrator = _migrator; tablesHash = _tablesHash; } /** * Method to update the transfer subscriber. * The transfer subscriber receives data on transfers in the contract. * Owner only. * @param _newSubscriber - The new subscriber to send data to */ function updateTransferSubscriber( IERC721Subscriber _newSubscriber ) external onlyOwner { subscriber = _newSubscriber; } /** * Method to update the migrator. * The migrator is the account able to sign authorization for owners to * migrate individual token metadata. * Owner only. * @param _newMigrator - New migrator to validate authorizations. */ function updateMigrator(address _newMigrator) external onlyOwner { migrator = _newMigrator; } /** * Method to update the beginning of the reveal phase. * Owner only. * @param _newRevealOpen - New open time */ function updateRevealOpen(uint256 _newRevealOpen) external onlyOwner { require( block.timestamp < revealOpen, "Shogunate: Cannot change reveal open time when reveal is open." ); require( _newRevealOpen > block.timestamp, "Shogunate: Reveal open time cannot be set in the past." ); revealOpen = _newRevealOpen; } /** * @dev Internal method to generate a soul * @param _soulEssence - Soul seed * @param pTable - Probability table - Used in generation * @param aTable - Alias table - Used in generation */ function _generateSoul( uint256 _soulEssence, bytes32[] calldata pTable, bytes32[] calldata aTable ) virtual internal returns(bytes32); /** * @dev Internal method to authorize minting a new Samurai. * Does all logic and actions necessary to authorize a mint. * @param _amount - The amount of mints to authorize */ function _authorizeMint(uint256 _amount) virtual internal; /** * @dev Internal method to hash the probability and alias tables. * This hash can then be compared to 'tablesHash' to validate the tables. * @param pTable - The probability table * @param aTable - The alias table */ function _hashTables( bytes32[] calldata pTable, bytes32[] calldata aTable ) pure internal returns (bytes32) { return keccak256(abi.encodePacked(pTable, aTable)); } /** * Method to store the lastest needed block hash. * That method can be called by anyone, and will store the blockhash of the * latest block a commit was done at, therefore freezing its randomness and * bypassing the 256 block limit to fetch a previous block hash. * * It is called: * - Everytime a commit, reveal, or recommit is done. * - By external Shogunate systems to enforce the randomness and fairness of * the generation process. * It can be called by anyone who wishes to enforce it :) * * Never reverts, simply does nothing if there is nothing to store. */ function storeLatestNeededBlockHash() public { if ( lastCommitBlock > 0 && lastCommitBlock < block.number && blockhashesStore[lastCommitBlock] == 0x0 ) { bytes32 lastCommitBlockHash = blockhash(lastCommitBlock); if (lastCommitBlockHash != 0x0) { blockhashesStore[lastCommitBlock] = lastCommitBlockHash; } } } /** * Method to commit a mint pass to the generation of a specific token ID, * using the blockhash of the current block as a source of randomness for a * future reveal. * User calling it will be authorized through the authorizeMint method. * @param _amount - The amount to commit - Must be less than MAX_COMMIT_PER_TX */ function commit( uint256 _amount ) external nonReentrant { require( _amount <= MAX_COMMIT_PER_TX, "Shogunate#commit: Too many commits at once." ); // Freeze the randomness of previous commits if necessary storeLatestNeededBlockHash(); uint256 _nextId = nextId; require( !msg.sender.isContract(), "Shogunate#commit: Caller cannot be a contract." ); require( block.timestamp >= revealOpen, "Shogunate#commit: Reveal is not open." ); require( _nextId - 1 + _amount <= maxTokens, "Shogunate#commit: Not enough tokens available." ); _authorizeMint(_amount); for (uint256 i = 0; i < _amount; i++) { revealCommits[_nextId + i] = RevealCommit( msg.sender, block.number ); emit Commited(msg.sender, _nextId + i); } lastCommitBlock = block.number; nextId += _amount; } /** * Method to reset a previous commit with the current block number. * Can only be called when the block linked to the commit has an unreachable * block. * This method is intended as an emergency measure in case Shogunate external * systems go down. * Can be called by anyone. * @param tokenId - The token ID to recommi */ function recommit( uint256 tokenId ) external nonReentrant { // Freeze the randomness of previous commits if necessary storeLatestNeededBlockHash(); RevealCommit storage revealCommit = revealCommits[tokenId]; require( revealCommit.receiver != address(0) && revealCommit.blockNumber < block.number, "Shogunate#recommit: tokenId not ready to be revealed." ); bytes32 commitBlockHash = blockhashesStore[revealCommit.blockNumber]; require( commitBlockHash == 0x0, "Shogunate#recommit: Commit block hash is reachable." ); revealCommit.blockNumber = block.number; lastCommitBlock = block.number; } /** * Method to reveal a maximum of MAX_REVEAL_PER_TX tokens. * Can be called by anyone for any ready-to-reveal token, but minted token * will obviously always go to the committer. * * Provided tables are hashed and matched with the contract's tablesHash * @param tokenIds - Array of token IDs to reveal * @param pTable - Probability table to reveal with * @param aTable - Alias table to reveal with */ function reveal( uint256[] calldata tokenIds, bytes32[] calldata pTable, bytes32[] calldata aTable ) external nonReentrant { require( tokenIds.length <= MAX_REVEAL_PER_TX, "Shogunate#reveal: Too many reveals at once." ); // Freeze the randomness of previous commits if necessary storeLatestNeededBlockHash(); require( _hashTables(pTable, aTable) == tablesHash, "Shogunate#reveal: Invalid tables." ); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; RevealCommit memory revealCommit = revealCommits[tokenId]; require( revealCommit.receiver != address(0), "Shogunate#reveal: tokenId not ready to be revealed" ); bytes32 commitBlockHash = blockhashesStore[revealCommit.blockNumber]; require( commitBlockHash != 0x0, "Shogunate#reveal: Commit block hash is unreachable." ); uint256 soulEssence = uint256(keccak256(abi.encodePacked( revealCommit.receiver, commitBlockHash, tokenId ))); bytes32 soul = _generateSoul(soulEssence, pTable, aTable); souls[tokenId] = soul; _mint(revealCommit.receiver, tokenId); emit NewSoul(tokenId, soul); } } /** * Method to get the soul of the given token ID. * Reverts ig token does not exist. * @param _tokenId - The token ID to get the soul of */ function soulOf(uint256 _tokenId) external view returns (bytes32) { require( _exists(_tokenId), "Shogunate#soulOf: tokenId does not exist." ); return souls[_tokenId]; } /** * Method to check if a token exists. * @param _tokenId - The token ID to check */ function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /** * Method to get the URI of the given token ID. * Returns the default URI concatenated with the token ID or a URI specific * to the given tokenId if present. */ function tokenURI( uint256 tokenId ) public view virtual override(ERC721, IERC721Metadata, ERC721URIStorage) returns (string memory) { require(_exists(tokenId), "Shogunate#tokenURI: URI query for nonexistent token"); string memory tmpURI = super.tokenURI(tokenId); if (bytes(tmpURI).length == 0) { return string(abi.encodePacked(defaultURI, tokenId.toString())); } return tmpURI; } /** * Method to update default URI. * Owner only. * @param _defaultURI - NEw default URI */ function updateDefaultURI(string calldata _defaultURI) external onlyOwner { defaultURI = _defaultURI; } /** * Method to migrate token URI. * Must be called by token owner and contain a valid signature signed by * migrator. * @param _tokenId - Token ID to migrate * @param _validUntil - Signature expiration * @param _tokenURI - New token specific URI * @param _signature- Signature */ function migrateTokenURI( uint256 _tokenId, uint256 _validUntil, string calldata _tokenURI, bytes calldata _signature ) external nonReentrant { require( _exists(_tokenId), "Shogunate#migrateTokenURI: Token does not exist." ); require( ownerOf(_tokenId) == _msgSender(), "Shogunate#migrateTokenURI: Sender does not own token." ); require( _validUntil >= block.timestamp, "Shogunate#migrateTokenURI: Signature is expired." ); require( _isValidSignature( keccak256(abi.encodePacked(_tokenId, _msgSender(), _validUntil, _tokenURI)), _signature ), "Shogunate#migrateTokenURI: Invalid signature." ); _setTokenURI(_tokenId, _tokenURI); } /** * @dev Internal method to test the validity of a signature */ function _isValidSignature(bytes32 _hash, bytes memory _signature) internal view returns (bool) { bytes32 signedHash = _hash.toEthSignedMessageHash(); return signedHash.recover(_signature) == migrator; } function supportsInterface( bytes4 interfaceId ) public view virtual override(IERC165, ERC721) returns (bool) { return super.supportsInterface(interfaceId); } function _burn( uint256 tokenId ) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Transmitter) { super._afterTokenTransfer(from, to, tokenId); if (from == address(0)) { totalSupply += 1; } if (to == address(0)) { totalSupply -= 1; } } /** * Method to pause data transmission of a specific token. * Intended as a way for owners to opt out of synchronization with L2. * @param tokenId - Token ID to stop the transmission of. * @param paused - True to pause, false to unpause */ function pauseTokenDataTransmission( uint256 tokenId, bool paused ) external nonReentrant { require( ownerOf(tokenId) == _msgSender(), "Shogunate#pauseTokenDataTransmission: Caller does not own token." ); _pauseTokenDataTransmission(tokenId, paused); } /** * Method to pause data transmission of the whole contract. * Owner only. * @param paused - True to pause, false to unpause */ function pauseContractDataTransmission(bool paused) external onlyOwner { _pauseContractDataTransmission(paused); } } // File @openzeppelin/contracts/token/ERC1155/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.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; } // File contracts/interface/IMintPass.sol interface IMintPass is IERC1155 { /** * Method to redeem (burn) mint passes. * Can only be calledby the redeemer. * @param id - The ID of the mint pass to redeem * @param account - The account to redeem from * @param amount - The amount to redeem */ function redeem(uint256 id, address account, uint256 amount) external; /** * Method to mint new mint passes. * Can only be called by the minter. * @param id - The ID of the mint pass to mint * @param account - The account to mint to * @param amount - The amount of mint passes to mint */ function mint(uint256 id, address account, uint256 amount) external; } // File contracts/Shogunate.sol contract Shogunate is AbstractShogunate { // Mint pass contract IMintPass public mintPass; // Mint pass ID uint256 public mintPassId; // Clans amount (attribute 1) uint256 constant CLANS = 5; // Max probability value (200 means steps in .5%) uint256 constant PMAX = 200; // Structure to hold generation data to pass around struct GenerationData { bytes32[] pTable; bytes32[] aTable; uint256 soulEssence; } constructor( IMintPass _mintPass, uint256 _mintPassId, string memory _defaultURI, uint256 _revealOpen, uint256 _maxTokens, address _migrator, bytes32 _tablesHash ) AbstractShogunate( _defaultURI, _revealOpen, _maxTokens, _migrator, _tablesHash ) ERC721("Shogunate", "SGN") { mintPass = _mintPass; mintPassId = _mintPassId; } /** * @dev Internal method to authorize a mint. * Redeems mint passes. * @param _amount - Amount of mints to authorize */ function _authorizeMint(uint256 _amount) internal override { mintPass.redeem(mintPassId, msg.sender, _amount); } /** * @dev Internal method to generate an attribute with an identical * probability to select each variation */ function _generateUniformAttribute( GenerationData memory _gd, uint256 _attributeIndex, uint256 _variationsCount ) internal pure returns (bytes1) { uint256 soulShard = uint256(keccak256( abi.encodePacked(_gd.soulEssence, _attributeIndex) )); return bytes1(uint8(SeedRand.randUint256( soulShard, 0, _variationsCount ))); } /** * @dev Internal method to generate an attribute according to a probability * table. */ function _generateAttribute( GenerationData memory _gd, uint256 _attributeIndex, uint256 _tablesIndex ) internal pure returns (bytes1) { uint256 soulShard = uint256(keccak256( abi.encodePacked(_gd.soulEssence, _attributeIndex) )); uint256 pIndex = SeedRand.randUint256( soulShard, 0, uint8(_gd.pTable[_tablesIndex][0]) ); uint256 biasedCoinFlip = SeedRand.randUint256( soulShard, 1, PMAX ); if (biasedCoinFlip < uint8(_gd.pTable[_tablesIndex][pIndex + 1])) { return bytes1(uint8(pIndex)); } return bytes1(_gd.aTable[_tablesIndex][pIndex + 1]); } /** * @dev Generates a master samurai */ function _generateMasterSamuraiSoul( GenerationData memory _gd, bytes memory _soul ) internal pure { _soul[2] = _generateAttribute(_gd, 2, 21); // Head _soul[4] = _generateAttribute(_gd, 4, 22); // Outfit _soul[5] = _generateAttribute(_gd, 5, 23); // Armor Color _soul[6] = _generateAttribute(_gd, 6, 24); // Weapon _soul[7] = _generateAttribute(_gd, 7, 25); // Eyes _soul[14] = _generateAttribute(_gd, 14, 26); // Datemono _soul[15] = _generateAttribute(_gd, 15, 27); // Mask _soul[16] = _generateAttribute(_gd, 16, 28); // Mustache } /** * @dev Generates a female apprentice */ function _generateFemaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { _soul[2] = _generateAttribute(_gd, 2, 11); // Head _soul[3] = _generateAttribute(_gd, 3, 12); // Outfit Type if (_soul[3] == 0) { // Outfit Type is Armor _soul[4] = _generateAttribute(_gd, 4, 13); // Armor _soul[5] = _generateAttribute(_gd, 5, 15); // Armor Color } else { // Outfit Type is Kimono _soul[4] = _generateAttribute(_gd, 4, 14); // Kimono } _soul[6] = _generateAttribute(_gd, 6, 16); // Weapon _soul[7] = _generateAttribute(_gd, 7, 17); // Eyes _soul[8] = _generateAttribute(_gd, 8, 18); // Necklace _soul[9] = _generateAttribute(_gd, 9, 19); // Eyebrows _soul[10] = _generateUniformAttribute(_gd, 10, 4); // Nose _soul[11] = _generateUniformAttribute(_gd, 11, 3); // Mouth _soul[12] = _generateAttribute(_gd, 12, 20); // Face Paint } /** * @dev Generates a male apprentice */ function _generateMaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { _soul[2] = _generateAttribute(_gd, 2, 1); // Head _soul[3] = _generateAttribute(_gd, 3, 2); // Outfit Type if (_soul[3] == 0) { // Outfit Type is Armor _soul[4] = _generateAttribute(_gd, 4, 3); // Armor _soul[5] = _generateAttribute(_gd, 5, 5); // Armor Color } else { // Outfit Type is Kimono _soul[4] = _generateAttribute(_gd, 4, 4); // Kimono } _soul[6] = _generateAttribute(_gd, 6, 6); // Weapon _soul[7] = _generateAttribute(_gd, 7, 7); // Eyes _soul[8] = _generateAttribute(_gd, 8, 8); // Necklace _soul[9] = _generateAttribute(_gd, 9, 9); // Eyebrows _soul[10] = _generateUniformAttribute(_gd, 10, 4); // Nose _soul[11] = _generateUniformAttribute(_gd, 11, 3); // Mouth _soul[13] = _generateAttribute(_gd, 13, 10); // Beard } /** * @dev Internal method to generate a new soul */ function _generateSoul( uint256 _soulEssence, bytes32[] calldata pTable, bytes32[] calldata aTable ) internal pure override returns(bytes32) { GenerationData memory gd = GenerationData(pTable, aTable, _soulEssence); bytes memory soul = new bytes(17); soul[0] = _generateAttribute(gd, 0, 0); // Base soul[1] = _generateUniformAttribute(gd, 1, 5); // Clan if (soul[0] == 0) { _generateMasterSamuraiSoul(gd, soul); } else if (uint8(soul[0]) == 0x1) { _generateFemaleApprentice(gd, soul); } else { _generateMaleApprentice(gd, soul); } return bytes32(soul); } /** * Method to get the clan of a given tokenId. * @param _tokenId - Token ID to check the clan of */ function clanOf(uint256 _tokenId) external view returns(uint8) { require( _exists(_tokenId), "Shogunate#soulOf: tokenId does not exist." ); return uint8(souls[_tokenId][1]); } /** * Method to get the shogun of a specific clan. * @param _clanId - Clan ID to get the shogun of */ function shogunOf(uint8 _clanId) public view returns(uint256) { require(_clanId < CLANS, "Shogunate#shogunOf: Clan does not exist."); return shogunIds[_clanId]; } /** * Method to check is a tokenId is a shogun @param _tokenId - Token ID to check */ function isShogun(uint256 _tokenId) external view returns(bool) { require( _exists(_tokenId), "Shogunate#isShogun: tokenId does not exist." ); return souls[_tokenId][0] == 0xFF; } /** * Method to generate a Shogun. * Owner only. * Once a shogun has been minted for a specific clan, it cannot be minted * again. * A shogun token cannot collide with a potential Samurai ID * @param _tokenId - The token to give the shogun * @param _clanId - The clan this shogun will lead */ function mintShogun(uint256 _tokenId, uint8 _clanId) external onlyOwner { require(_tokenId > maxTokens, "Shogunate#mintShogun: Token is reserved."); require( shogunOf(_clanId) == 0, "Shogunate#mintShogun: Clan already has a shogun." ); bytes32 soul = bytes32(abi.encodePacked( uint8(0xFF), _clanId )); souls[_tokenId] = soul; shogunIds[_clanId] = _tokenId; _mint(msg.sender, _tokenId); emit NewSoul(_tokenId, soul); } }
Mint pass contract Mint pass ID Clans amount (attribute 1) Max probability value (200 means steps in .5%) Structure to hold generation data to pass around
contract Shogunate is AbstractShogunate { IMintPass public mintPass; uint256 public mintPassId; uint256 constant CLANS = 5; uint256 constant PMAX = 200; } struct GenerationData { bytes32[] pTable; bytes32[] aTable; uint256 soulEssence; } constructor( IMintPass _mintPass, uint256 _mintPassId, string memory _defaultURI, uint256 _revealOpen, uint256 _maxTokens, address _migrator, bytes32 _tablesHash ) AbstractShogunate( _defaultURI, _revealOpen, _maxTokens, _migrator, _tablesHash ) ERC721("Shogunate", "SGN") { mintPass = _mintPass; mintPassId = _mintPassId; } function _authorizeMint(uint256 _amount) internal override { mintPass.redeem(mintPassId, msg.sender, _amount); } function _generateUniformAttribute( GenerationData memory _gd, uint256 _attributeIndex, uint256 _variationsCount ) internal pure returns (bytes1) { uint256 soulShard = uint256(keccak256( abi.encodePacked(_gd.soulEssence, _attributeIndex) )); return bytes1(uint8(SeedRand.randUint256( soulShard, 0, _variationsCount ))); } function _generateAttribute( GenerationData memory _gd, uint256 _attributeIndex, uint256 _tablesIndex ) internal pure returns (bytes1) { uint256 soulShard = uint256(keccak256( abi.encodePacked(_gd.soulEssence, _attributeIndex) )); uint256 pIndex = SeedRand.randUint256( soulShard, 0, uint8(_gd.pTable[_tablesIndex][0]) ); uint256 biasedCoinFlip = SeedRand.randUint256( soulShard, 1, PMAX ); if (biasedCoinFlip < uint8(_gd.pTable[_tablesIndex][pIndex + 1])) { return bytes1(uint8(pIndex)); } return bytes1(_gd.aTable[_tablesIndex][pIndex + 1]); } function _generateAttribute( GenerationData memory _gd, uint256 _attributeIndex, uint256 _tablesIndex ) internal pure returns (bytes1) { uint256 soulShard = uint256(keccak256( abi.encodePacked(_gd.soulEssence, _attributeIndex) )); uint256 pIndex = SeedRand.randUint256( soulShard, 0, uint8(_gd.pTable[_tablesIndex][0]) ); uint256 biasedCoinFlip = SeedRand.randUint256( soulShard, 1, PMAX ); if (biasedCoinFlip < uint8(_gd.pTable[_tablesIndex][pIndex + 1])) { return bytes1(uint8(pIndex)); } return bytes1(_gd.aTable[_tablesIndex][pIndex + 1]); } function _generateMasterSamuraiSoul( GenerationData memory _gd, bytes memory _soul ) internal pure { } function _generateFemaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { if (_soul[3] == 0) { } } function _generateFemaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { if (_soul[3] == 0) { } } } else { function _generateMaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { if (_soul[3] == 0) { } } function _generateMaleApprentice( GenerationData memory _gd, bytes memory _soul ) internal pure { if (_soul[3] == 0) { } } } else { function _generateSoul( uint256 _soulEssence, bytes32[] calldata pTable, bytes32[] calldata aTable ) internal pure override returns(bytes32) { GenerationData memory gd = GenerationData(pTable, aTable, _soulEssence); bytes memory soul = new bytes(17); if (soul[0] == 0) { _generateMasterSamuraiSoul(gd, soul); _generateFemaleApprentice(gd, soul); _generateMaleApprentice(gd, soul); } return bytes32(soul); } function _generateSoul( uint256 _soulEssence, bytes32[] calldata pTable, bytes32[] calldata aTable ) internal pure override returns(bytes32) { GenerationData memory gd = GenerationData(pTable, aTable, _soulEssence); bytes memory soul = new bytes(17); if (soul[0] == 0) { _generateMasterSamuraiSoul(gd, soul); _generateFemaleApprentice(gd, soul); _generateMaleApprentice(gd, soul); } return bytes32(soul); } } else if (uint8(soul[0]) == 0x1) { } else { function clanOf(uint256 _tokenId) external view returns(uint8) { require( _exists(_tokenId), "Shogunate#soulOf: tokenId does not exist." ); return uint8(souls[_tokenId][1]); } function shogunOf(uint8 _clanId) public view returns(uint256) { require(_clanId < CLANS, "Shogunate#shogunOf: Clan does not exist."); return shogunIds[_clanId]; } @param _tokenId - Token ID to check function isShogun(uint256 _tokenId) external view returns(bool) { require( _exists(_tokenId), "Shogunate#isShogun: tokenId does not exist." ); return souls[_tokenId][0] == 0xFF; } function mintShogun(uint256 _tokenId, uint8 _clanId) external onlyOwner { require(_tokenId > maxTokens, "Shogunate#mintShogun: Token is reserved."); require( shogunOf(_clanId) == 0, "Shogunate#mintShogun: Clan already has a shogun." ); bytes32 soul = bytes32(abi.encodePacked( uint8(0xFF), _clanId )); souls[_tokenId] = soul; shogunIds[_clanId] = _tokenId; _mint(msg.sender, _tokenId); emit NewSoul(_tokenId, soul); } }
12,082,344
[ 1, 49, 474, 1342, 6835, 490, 474, 1342, 1599, 3905, 634, 3844, 261, 4589, 404, 13, 4238, 11331, 460, 261, 6976, 4696, 6075, 316, 263, 25, 9, 13, 13348, 358, 6887, 9377, 501, 358, 1342, 6740, 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, 16351, 2638, 717, 318, 340, 353, 4115, 1555, 717, 318, 340, 288, 203, 225, 6246, 474, 6433, 1071, 312, 474, 6433, 31, 203, 225, 2254, 5034, 1071, 312, 474, 6433, 548, 31, 203, 203, 225, 2254, 5034, 5381, 385, 11074, 55, 273, 1381, 31, 203, 203, 225, 2254, 5034, 5381, 453, 6694, 273, 4044, 31, 203, 203, 97, 203, 203, 225, 1958, 23234, 751, 288, 203, 565, 1731, 1578, 8526, 293, 1388, 31, 203, 565, 1731, 1578, 8526, 279, 1388, 31, 203, 565, 2254, 5034, 272, 1003, 41, 1049, 802, 31, 203, 225, 289, 203, 203, 225, 3885, 12, 203, 565, 6246, 474, 6433, 389, 81, 474, 6433, 16, 203, 565, 2254, 5034, 389, 81, 474, 6433, 548, 16, 203, 565, 533, 3778, 389, 1886, 3098, 16, 203, 565, 2254, 5034, 389, 266, 24293, 3678, 16, 203, 565, 2254, 5034, 389, 1896, 5157, 16, 203, 565, 1758, 389, 81, 2757, 639, 16, 203, 565, 1731, 1578, 389, 9373, 2310, 203, 225, 262, 4115, 1555, 717, 318, 340, 12, 203, 565, 389, 1886, 3098, 16, 203, 565, 389, 266, 24293, 3678, 16, 203, 565, 389, 1896, 5157, 16, 203, 565, 389, 81, 2757, 639, 16, 203, 565, 389, 9373, 2310, 203, 225, 262, 4232, 39, 27, 5340, 2932, 1555, 717, 318, 340, 3113, 315, 55, 8318, 7923, 288, 203, 565, 312, 474, 6433, 273, 389, 81, 474, 6433, 31, 203, 565, 312, 474, 6433, 548, 273, 389, 81, 474, 6433, 548, 31, 203, 225, 289, 203, 203, 225, 445, 389, 22488, 49, 474, 12, 11890, 2 ]
pragma solidity ^ 0.4.24; // 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; } } /** * @title BaseAccessControl * @dev Basic control permissions are setting here */ contract BaseAccessControl { address public ceo; address public coo; address public cfo; constructor() public { ceo = msg.sender; coo = msg.sender; cfo = msg.sender; } /** roles modifer */ modifier onlyCEO() { require(msg.sender == ceo, "CEO Only"); _; } modifier onlyCOO() { require(msg.sender == coo, "COO Only"); _; } modifier onlyCFO() { require(msg.sender == cfo, "CFO Only"); _; } modifier onlyCLevel() { require(msg.sender == ceo || msg.sender == coo || msg.sender == cfo, "CLevel Only"); _; } /** end modifier */ /** util modifer */ modifier required(address addr) { require(addr != address(0), "Address is required."); _; } modifier onlyHuman(address addr) { uint256 codeLength; assembly { codeLength: = extcodesize(addr) } require(codeLength == 0, "Humans only"); _; } modifier onlyContract(address addr) { uint256 codeLength; assembly { codeLength: = extcodesize(addr) } require(codeLength > 0, "Contracts only"); _; } /** end util modifier */ /** setter */ function setCEO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { ceo = addr; } function setCOO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { coo = addr; } function setCFO(address addr) external onlyCEO() required(addr) onlyHuman(addr) { cfo = addr; } /** end setter */ } /** * @title MinerAccessControl * @dev Expanding the access control module for miner contract, especially for B1MP contract here */ contract MinerAccessControl is BaseAccessControl { address public companyWallet; bool public paused = false; /** modifer */ modifier whenNotPaused() { require(!paused, "Paused"); _; } modifier whenPaused() { require(paused, "Running"); _; } /** end modifier */ /** setter */ function setCompanyWallet(address newCompanyWallet) external onlyCEO() required(newCompanyWallet) { companyWallet = newCompanyWallet; } function paused() public onlyCLevel() whenNotPaused() { paused = true; } function unpaused() external onlyCEO() whenPaused() { paused = false; } /** end setter */ } /** * @title B1MPToken * @dev This contract is One-Minute Profit Option Contract. * And all users can get their one-minute profit option as a ERC721 token through this contract. * Even more, all users can exchange their one-minute profit option in the future. */ interface B1MPToken { function mintByTokenId(address to, uint256 tokenId) external returns(bool); } /** * @title B1MP * @dev This is the old B1MP contract. * Because of some problem, we have decided to migrate all data and use a new one contract. */ interface B1MP { function _global() external view returns(uint256 revenue, uint256 g_positionAmount, uint256 earlierPayoffPerPosition, uint256 totalRevenue); function _userAddrBook(uint256 index) external view returns(address addr); function _users(address addr) external view returns(uint256 id, uint256 positionAmount, uint256 earlierPayoffMask, uint256 lastRefId); function _invitations(address addr) external view returns(uint256 invitationAmount, uint256 invitationPayoff); function _positionBook(uint256 index1, uint256 index2) external view returns(uint256 minute); function _positionOnwers(uint256 minute) external view returns(address addr); function totalUsers() external view returns(uint256); function getUserPositionIds(address addr) external view returns(uint256[]); } /** * @title NewB1MP * @dev Because the old one has some problem, we re-devise the whole contract. * All actions, such as buying, withdrawing, and etc., are responding and recording by this contract. */ contract NewB1MP is MinerAccessControl { using SafeMath for * ; // the activity configurations struct Config { uint256 start; // the activity's start-time uint256 end; // the activity's end-time uint256 price; // the price of any one-minute profit option uint256 withdrawFee; // the basic fee for withdrawal request uint8 earlierPayoffRate; // the proportion of dividends to early buyers uint8 invitationPayoffRate; // the proportion of dividends to inviters uint256 finalPrizeThreshold; // the threshold for opening the final prize uint8[10] finalPrizeRates; // a group proportions for the final prize, the final selected proportion will be decided by some parameters } struct Global { uint256 revenue; // reserved revenue of the project holder uint256 positionAmount; // the total amount of minutes been sold uint256 earlierPayoffPerPosition; // the average dividends for every minute been sold before uint256 totalRevenue; // total amount of revenue } struct User { uint256 id; // user's id, equal to user's index + 1, increment uint256 positionAmount; // the total amount of minutes bought by this user uint256 earlierPayoffMask; // the pre-purchaser dividend that the user should not receive uint256 lastRefId; // the inviter's user-id uint256[] positionIds; // all position ids hold by this user } struct Invitation { uint256 amount; // how many people invited uint256 payoff; // how much payoff through invitation } B1MP public oldB1MPContract; // the old B1MP contract, just for data migration B1MPToken public tokenContract; // the one-minute profit option contract Config public _config; // configurations Global public _global; // globa info address[] public _userAddrBook; // users' addresses list, for registration mapping(address => User) public _users; // all users' detail info mapping(address => Invitation) public _invitations; // the invitations info uint256[2][] public _positionBook; // all positions list mapping(uint256 => address) public _positionOwners; // positionId (index + 1) => owner mapping(uint256 => address) public _positionMiners; // position minute => miner uint256 public _prizePool; // the pool of final prize uint256 public _prizePoolWithdrawn; // how much money been withdrawn through final prize pool bool public _isPrizeActivated; // whether the final prize is activated address[] public _winnerPurchaseListForAddr; // final prize winners list uint256[] public _winnerPurchaseListForPositionAmount; // the purchase history of final prize winners mapping(address => uint256) public _winnerPositionAmounts; // the total position amount of any final prize winner uint256 public _currentWinnerIndex; // the index of current winner, using for a looping array of all winners uint256 private _winnerCounter; // the total amount of final prize winners uint256 public _winnerTotalPositionAmount; // the total amount of positons bought by all final prize winners bool private _isReady; // whether the data migration has been completed uint256 private _userMigrationCounter; // how many users have been migrated /** modifer */ modifier paymentLimit(uint256 ethVal) { require(ethVal > 0, "Too poor."); require(ethVal <= 100000 ether, "Too rich."); _; } modifier buyLimit(uint256 ethVal) { require(ethVal >= _config.price, 'Not enough.'); _; } modifier withdrawLimit(uint256 ethVal) { require(ethVal == _config.withdrawFee, 'Not enough.'); _; } modifier whenNotEnded() { require(_config.end == 0 || now < _config.end, 'Ended.'); _; } modifier whenEnded() { require(_config.end != 0 && now >= _config.end, 'Not ended.'); _; } modifier whenPrepare() { require(_config.end == 0, 'Started.'); require(_isReady == false, 'Ready.'); _; } modifier whenReady() { require(_isReady == true, 'Not ready.'); _; } /** end modifier */ // initialize constructor(address tokenAddr, address oldB1MPContractAddr) onlyContract(tokenAddr) onlyContract(oldB1MPContractAddr) public { // ready for migration oldB1MPContract = B1MP(oldB1MPContractAddr); _isReady = false; _userMigrationCounter = 0; // initialize base info tokenContract = B1MPToken(tokenAddr); _config = Config(1541993890, 0, 90 finney, 5 finney, 10, 20, 20000 ether, [ 5, 6, 7, 8, 10, 13, 15, 17, 20, 25 ]); _global = Global(0, 0, 0, 0); // ready for final prize _currentWinnerIndex = 0; _isPrizeActivated = false; } function migrateUserData(uint256 n) whenPrepare() onlyCEO() public { // intialize _userAddrBook & _users uint256 userAmount = oldB1MPContract.totalUsers(); _userAddrBook.length = userAmount; // migrate n users per time uint256 lastMigrationNumber = _userMigrationCounter; for (_userMigrationCounter; _userMigrationCounter < userAmount && _userMigrationCounter < lastMigrationNumber + n; _userMigrationCounter++) { // A. get user address address userAddr = oldB1MPContract._userAddrBook(_userMigrationCounter); /// save to _userAddrBook _userAddrBook[_userMigrationCounter] = userAddr; // B. get user info (uint256 id, uint256 positionAmount, uint256 earlierPayoffMask, uint256 lastRefId) = oldB1MPContract._users(userAddr); uint256[] memory positionIds = oldB1MPContract.getUserPositionIds(userAddr); /// save to _users _users[userAddr] = User(id, positionAmount, earlierPayoffMask, lastRefId, positionIds); // C. get invitation info (uint256 invitationAmount, uint256 invitationPayoff) = oldB1MPContract._invitations(userAddr); /// save to _invitations _invitations[userAddr] = Invitation(invitationAmount, invitationPayoff); // D. get & save position info for (uint256 i = 0; i < positionIds.length; i++) { uint256 pid = positionIds[i]; if (pid > 0) { if (pid > _positionBook.length) { _positionBook.length = pid; } uint256 pIndex = pid.sub(1); _positionBook[pIndex] = [oldB1MPContract._positionBook(pIndex, 0), oldB1MPContract._positionBook(pIndex, 1)]; _positionOwners[pIndex] = userAddr; } } } } function migrateGlobalData() whenPrepare() onlyCEO() public { // intialize _global (uint256 revenue, uint256 g_positionAmount, uint256 earlierPayoffPerPosition, uint256 totalRevenue) = oldB1MPContract._global(); _global = Global(revenue, g_positionAmount, earlierPayoffPerPosition, totalRevenue); } function depositeForMigration() whenPrepare() onlyCEO() public payable { require(_userMigrationCounter == oldB1MPContract.totalUsers(), 'Continue to migrate.'); require(msg.value >= address(oldB1MPContract).balance, 'Not enough.'); // update revenue, but don't update totalRevenue // because it's the dust of deposit, but not the revenue of sales // it will be not used for final prize _global.revenue = _global.revenue.add(msg.value.sub(address(oldB1MPContract).balance)); _isReady = true; } function () whenReady() whenNotEnded() whenNotPaused() onlyHuman(msg.sender) paymentLimit(msg.value) buyLimit(msg.value) public payable { buyCore(msg.sender, msg.value, 0); } function buy(uint256 refId) whenReady() whenNotEnded() whenNotPaused() onlyHuman(msg.sender) paymentLimit(msg.value) buyLimit(msg.value) public payable { buyCore(msg.sender, msg.value, refId); } function buyCore(address addr_, uint256 revenue_, uint256 refId_) private { // 1. prepare some data uint256 _positionAmount_ = (revenue_).div(_config.price); // actual amount uint256 _realCost_ = _positionAmount_.mul(_config.price); uint256 _invitationPayoffPart_ = _realCost_.mul(_config.invitationPayoffRate).div(100); uint256 _earlierPayoffPart_ = _realCost_.mul(_config.earlierPayoffRate).div(100); revenue_ = revenue_.sub(_invitationPayoffPart_).sub(_earlierPayoffPart_); uint256 _earlierPayoffMask_ = 0; // 2. register a new user if (_users[addr_].id == 0) { _userAddrBook.push(addr_); // add to user address list _users[addr_].id = _userAddrBook.length; // assign the user id, especially id = userAddrBook.index + 1 } // 3. update global info if (_global.positionAmount > 0) { uint256 eppp = _earlierPayoffPart_.div(_global.positionAmount); _global.earlierPayoffPerPosition = eppp.add(_global.earlierPayoffPerPosition); // update global earlier payoff for per position revenue_ = revenue_.add(_earlierPayoffPart_.sub(eppp.mul(_global.positionAmount))); // the dust for this dividend } else { revenue_ = revenue_.add(_earlierPayoffPart_); // no need to dividend, especially for first one } // update the total position amount _global.positionAmount = _positionAmount_.add(_global.positionAmount); // calculate the current user's earlier payoff mask for this tx _earlierPayoffMask_ = _positionAmount_.mul(_global.earlierPayoffPerPosition); // 4. update referral data if (refId_ <= 0 || refId_ > _userAddrBook.length || refId_ == _users[addr_].id) { // the referrer doesn't exist, or is clien self refId_ = _users[addr_].lastRefId; } else if (refId_ != _users[addr_].lastRefId) { _users[addr_].lastRefId = refId_; } // update referrer's invitation info if he exists if (refId_ != 0) { address refAddr = _userAddrBook[refId_.sub(1)]; // modify old one or create a new on if it doesn't exist _invitations[refAddr].amount = (1).add(_invitations[refAddr].amount); // update invitation amount _invitations[refAddr].payoff = _invitationPayoffPart_.add(_invitations[refAddr].payoff); // update invitation payoff } else { revenue_ = revenue_.add(_invitationPayoffPart_); // no referrer } // 5. update user info _users[addr_].positionAmount = _positionAmount_.add(_users[addr_].positionAmount); _users[addr_].earlierPayoffMask = _earlierPayoffMask_.add(_users[addr_].earlierPayoffMask); // update user's positions details, and record the position _positionBook.push([_global.positionAmount.sub(_positionAmount_).add(1), _global.positionAmount]); _positionOwners[_positionBook.length] = addr_; _users[addr_].positionIds.push(_positionBook.length); // 6. archive revenue _global.revenue = revenue_.add(_global.revenue); _global.totalRevenue = revenue_.add(_global.totalRevenue); // 7. select 1% user for final prize when the revenue is more than final prize threshold if (_global.totalRevenue > _config.finalPrizeThreshold) { uint256 maxWinnerAmount = countWinners(); // the max amount of winners, 1% of total users // activate final prize module at least there are more than 100 users if (maxWinnerAmount > 0) { if (maxWinnerAmount > _winnerPurchaseListForAddr.length) { _winnerPurchaseListForAddr.length = maxWinnerAmount; _winnerPurchaseListForPositionAmount.length = maxWinnerAmount; } // get the last winner's address address lwAddr = _winnerPurchaseListForAddr[_currentWinnerIndex]; if (lwAddr != address(0)) { // deal the last winner's info // deduct this purchase record's positions amount from total amount _winnerTotalPositionAmount = _winnerTotalPositionAmount.sub(_winnerPurchaseListForPositionAmount[_currentWinnerIndex]); // deduct the winner's position amount from this winner's amount _winnerPositionAmounts[lwAddr] = _winnerPositionAmounts[lwAddr].sub(_winnerPurchaseListForPositionAmount[_currentWinnerIndex]); // this is the winner's last record if (_winnerPositionAmounts[lwAddr] == 0) { // delete the winner's info _winnerCounter = _winnerCounter.sub(1); delete _winnerPositionAmounts[lwAddr]; } } // set the new winner's info, or update old winner's info // register a new winner if (_winnerPositionAmounts[msg.sender] == 0) { // add a new winner _winnerCounter = _winnerCounter.add(1); } // update total amount of winner's positions bought finally _winnerTotalPositionAmount = _positionAmount_.add(_winnerTotalPositionAmount); // update winner's position amount _winnerPositionAmounts[msg.sender] = _positionAmount_.add(_winnerPositionAmounts[msg.sender]); // directly reset the winner list _winnerPurchaseListForAddr[_currentWinnerIndex] = msg.sender; _winnerPurchaseListForPositionAmount[_currentWinnerIndex] = _positionAmount_; // move the index to next _currentWinnerIndex = _currentWinnerIndex.add(1); if (_currentWinnerIndex >= maxWinnerAmount) { // the max index = total amount - 1 _currentWinnerIndex = 0; // start a new loop when the number of winners exceed over the max amount allowed } } } // 8. update end time _config.end = (now).add(2 days); // expand the end time for every tx } function redeemOptionContract(uint256 positionId, uint256 minute) whenReady() whenNotPaused() onlyHuman(msg.sender) public { require(_users[msg.sender].id != 0, 'Unauthorized.'); require(positionId <= _positionBook.length && positionId > 0, 'Position Id error.'); require(_positionOwners[positionId] == msg.sender, 'No permission.'); require(minute >= _positionBook[positionId - 1][0] && minute <= _positionBook[positionId - 1][1], 'Wrong interval.'); require(_positionMiners[minute] == address(0), 'Minted.'); // record the miner _positionMiners[minute] = msg.sender; // mint this minute's token require(tokenContract.mintByTokenId(msg.sender, minute), "Mining Error."); } function activateFinalPrize() whenReady() whenEnded() whenNotPaused() onlyCOO() public { require(_isPrizeActivated == false, 'Activated.'); // total revenue should be more than final prize threshold if (_global.totalRevenue > _config.finalPrizeThreshold) { // calculate the prize pool uint256 selectedfinalPrizeRatesIndex = _winnerCounter.mul(_winnerTotalPositionAmount).mul(_currentWinnerIndex).mod(_config.finalPrizeRates.length); _prizePool = _global.totalRevenue.mul(_config.finalPrizeRates[selectedfinalPrizeRatesIndex]).div(100); // deduct the final prize pool from the reserved revenue _global.revenue = _global.revenue.sub(_prizePool); } // maybe not enough to final prize _isPrizeActivated = true; } function withdraw() whenReady() whenNotPaused() onlyHuman(msg.sender) withdrawLimit(msg.value) public payable { _global.revenue = _global.revenue.add(msg.value); // archive withdrawal fee to revenue, but not total revenue which is for final prize // 1. deduct invitation payoff uint256 amount = _invitations[msg.sender].payoff; _invitations[msg.sender].payoff = 0; // clear the user's invitation payoff // 2. deduct earlier payoff uint256 ep = (_global.earlierPayoffPerPosition).mul(_users[msg.sender].positionAmount); amount = amount.add(ep.sub(_users[msg.sender].earlierPayoffMask)); _users[msg.sender].earlierPayoffMask = ep; // reset the user's earlier payoff mask which include this withdrawal part // 3. get the user's final prize, and deduct it if (_isPrizeActivated == true && _winnerPositionAmounts[msg.sender] > 0 && _winnerTotalPositionAmount > 0 && _winnerCounter > 0 && _prizePool > _prizePoolWithdrawn) { // calculate the user's prize amount uint256 prizeAmount = prize(msg.sender); // set the user withdrawal amount amount = amount.add(prizeAmount); // refresh withdrawal amount of prize pool _prizePoolWithdrawn = _prizePoolWithdrawn.add(prizeAmount); // clear the user's finally bought position amount, so clear the user's final prize clearPrize(msg.sender); _winnerCounter = _winnerCounter.sub(1); } // 4. send eth (msg.sender).transfer(amount); } function withdrawByCFO(uint256 amount) whenReady() whenNotPaused() onlyCFO() required(companyWallet) public { require(amount > 0, 'Payoff too samll.'); uint256 max = _global.revenue; if (_isPrizeActivated == false) { // when haven't sent final prize // deduct the max final prize pool max = max.sub(_global.totalRevenue.mul(_config.finalPrizeRates[_config.finalPrizeRates.length.sub(1)]).div(100)); } require(amount <= max, 'Payoff too big.'); // deduct the withdrawal amount _global.revenue = _global.revenue.sub(amount); // send eth companyWallet.transfer(amount); } function withdrawByCFO(address addr) whenReady() whenNotPaused() onlyCFO() onlyContract(addr) required(companyWallet) public { // send all erc20 require(IERC20(addr).transfer(companyWallet, IERC20(addr).balanceOf(this))); } function collectPrizePoolDust() whenReady() whenNotPaused() onlyCOO() public { // when final prize has been sent, and all winners have received prizes require(_isPrizeActivated == true, 'Not activited.'); // collect the prize pool dust if (_winnerCounter == 0 || now > _config.end.add(180 days)) { _global.revenue = _global.revenue.add(_prizePool.sub(_prizePoolWithdrawn)); _prizePoolWithdrawn = _prizePool; } } function totalUsers() public view returns(uint256) { return _userAddrBook.length; } function getUserAddress(uint256 id) public view returns(address userAddrRet) { if (id <= _userAddrBook.length && id > 0) { userAddrRet = _userAddrBook[id.sub(1)]; } } function getUserPositionIds(address addr) public view returns(uint256[]) { return _users[addr].positionIds; } function countPositions() public view returns(uint256) { return _positionBook.length; } function getPositions(uint256 id) public view returns(uint256[2] positionsRet) { if (id <= _positionBook.length && id > 0) { positionsRet = _positionBook[id.sub(1)]; } } function prize(address addr) public view returns(uint256) { if (_winnerTotalPositionAmount == 0 || _prizePool == 0) { return 0; } return _winnerPositionAmounts[addr].mul(_prizePool).div(_winnerTotalPositionAmount); } function clearPrize(address addr) private { delete _winnerPositionAmounts[addr]; } function countWinners() public view returns(uint256) { return _userAddrBook.length.div(100); } function allWinners() public view returns(address[]) { return _winnerPurchaseListForAddr; } } /** * @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 ); }
update the total position amount
_global.positionAmount = _positionAmount_.add(_global.positionAmount);
1,031,982
[ 1, 2725, 326, 2078, 1754, 3844, 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, 202, 202, 67, 6347, 18, 3276, 6275, 273, 389, 3276, 6275, 27799, 1289, 24899, 6347, 18, 3276, 6275, 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 ]
pragma solidity ^0.4.24; interface MilAuthInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); function checkGameRegiester(address _gameAddr) external view returns(bool); function checkGameClosed(address _gameAddr) external view returns(bool); } interface MillionaireInterface { function invest(address _addr, uint256 _affID, uint256 _mfCoin, uint256 _general) external payable; function updateGenVaultAndMask(address _addr, uint256 _affID) external payable; function clearGenVaultAndMask(address _addr, uint256 _affID, uint256 _eth, uint256 _milFee) external; function assign(address _addr) external payable; function splitPot() external payable; } interface MilFoldInterface { function addPot() external payable; function activate() external; } contract Milevents { // fired whenever a player registers event onNewPlayer ( address indexed playerAddress, uint256 playerID, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 rid, //current round id address indexed buyerAddress, //buyer address uint256 compressData, //action << 96 | time << 64 | drawCode << 32 | txAction << 8 | roundState uint256 eth, //buy amount uint256 totalPot, //current total pot uint256 tickets, //buy tickets uint256 timeStamp //buy time ); // fired at end of buy or reload event onGameClose ( address indexed gameAddr, //game address uint256 amount, //split eth amount uint256 timeStamp //close time ); // fired at time who satisfy the reward condition event onReward ( address indexed rewardAddr, //reward address Mildatasets.RewardType rewardType, //rewardType uint256 amount //reward amount ); // fired whenever theres a withdraw event onWithdraw ( address indexed playerAddress, uint256 ethOut, uint256 timeStamp ); event onAffiliatePayout ( address indexed affiliateAddress, address indexed buyerAddress, uint256 eth, uint256 timeStamp ); // fired at every ico event onICO ( address indexed buyerAddress, //user address who buy ico uint256 buyAmount, //buy ico amount uint256 buyMf, //eth exchange mfcoin amount uint256 totalIco, //now total ico amount bool ended //is ico ended ); // fired whenever an player win the playround event onPlayerWin( address indexed addr, uint256 roundID, uint256 winAmount, uint256 winNums ); event onClaimWinner( address indexed addr, uint256 winnerNum, uint256 totalNum ); event onBuyMFCoins( address indexed addr, uint256 ethAmount, uint256 mfAmount, uint256 timeStamp ); event onSellMFCoins( address indexed addr, uint256 ethAmount, uint256 mfAmount, uint256 timeStamp ); event onUpdateGenVault( address indexed addr, uint256 mfAmount, uint256 genAmount, uint256 ethAmount ); } contract MilFold is MilFoldInterface,Milevents { using SafeMath for *; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== uint256 constant private rndMax_ = 90000; // max length a round timer can be uint256 constant private claimMax_ = 43200; // max limitation period to claim winned address constant private fundAddr_ = 0xB0c7Dc00E8A74c9dEc8688EFb98CcB2e24584E3B; // foundation address uint256 constant private MIN_ETH_BUYIN = 0.002 ether; // min buy amount uint256 constant private COMMON_REWARD_AMOUNT = 0.01 ether; // reward who end round or draw the game uint256 constant private CLAIM_WINNER_REWARD_AMOUNT = 1 ether; // reward who claim an winner uint256 constant private MAX_WIN_AMOUNT = 5000 ether; // max win amount every round; uint256 private rID_; // current round; uint256 private lID_; // last round; uint256 private lBlockNumber_; // last round end block number; bool private activated_; // mark contract is activated; MillionaireInterface constant private millionaire_ = MillionaireInterface(0x98BDbc858822415C626c13267594fbC205182A1F); MilAuthInterface constant private milAuth_ = MilAuthInterface(0xf856f6a413f7756FfaF423aa2101b37E2B3aFFD9); mapping (address => uint256) private playerTickets_; // (addr => tickets) returns player tickets mapping (uint256 => Mildatasets.Round) private round_; // (rID => data) returns round data mapping (uint256 => mapping(address => uint256[])) private playerTicketNumbers_; // (rID => address => data) returns round data mapping (address => uint256) private playerWinTotal_; // (addr => eth) returns total winning eth //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "it's not ready yet"); _; } /** * @dev prevents contracts from interacting with milfold,except constructor */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= MIN_ETH_BUYIN, "can't be less anymore"); _; } /** * @dev check sender must be devs */ modifier onlyDevs() { require(milAuth_.isDev(msg.sender) == true, "msg sender is not a dev"); _; } /** * @dev used to make sure the paid is sufficient to buy tickets. * @param _eth the eth you want pay for * @param _num the numbers you want to buy */ modifier inSufficient(uint256 _eth, uint256[] _num) { uint256 totalTickets = _num.length; require(_eth >= totalTickets.mul(500)/1 ether, "insufficient to buy the very tickets"); _; } /** * @dev used to make sure the paid is sufficient to buy tickets. * @param _eth the eth you want pay for * @param _startNums the start numbers you want to buy * @param _endNums the end numbers you want to to buy */ modifier inSufficient2(uint256 _eth, uint256[] _startNums, uint256[] _endNums) { uint256 totalTickets = calcSectionTickets(_startNums, _endNums); require(_eth >= totalTickets.mul(500)/1 ether, "insufficient to buy the very tickets"); _; } /** * @dev deposit to contract */ function() public isActivated() payable { addPot(); } /** * @dev buy tickets with pay eth * @param _affID the id of the player who gets the affiliate fee */ function buyTickets(uint256 _affID) public isActivated() isHuman() isWithinLimits(msg.value) payable { uint256 compressData = checkRoundAndDraw(msg.sender); buyCore(msg.sender, _affID, msg.value); emit onEndTx( rID_, msg.sender, compressData, msg.value, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev direct buy nums with pay eth in express way * @param _affID the id of the player who gets the affiliate fee * @param _nums which nums you buy, less than 10 */ function expressBuyNums(uint256 _affID, uint256[] _nums) public isActivated() isHuman() isWithinLimits(msg.value) inSufficient(msg.value, _nums) payable { uint256 compressData = checkRoundAndDraw(msg.sender); buyCore(msg.sender, _affID, msg.value); convertCore(msg.sender, _nums.length, TicketCompressor.encode(_nums)); emit onEndTx( rID_, msg.sender, compressData, msg.value, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev direct buy section nums with pay eth in express way * @param _affID the id of the player who gets the affiliate fee * @param _startNums section nums,start * @param _endNums section nums,end */ function expressBuyNumSec(uint256 _affID, uint256[] _startNums, uint256[] _endNums) public isActivated() isHuman() isWithinLimits(msg.value) inSufficient2(msg.value, _startNums, _endNums) payable { uint256 compressData = checkRoundAndDraw(msg.sender); buyCore(msg.sender, _affID, msg.value); convertCore( msg.sender, calcSectionTickets(_startNums, _endNums), TicketCompressor.encode(_startNums, _endNums) ); emit onEndTx( rID_, msg.sender, compressData, msg.value, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev buy tickets with use your vaults * @param _affID the id of the player who gets the affiliate fee * @param _eth the vaults you want pay for */ function reloadTickets(uint256 _affID, uint256 _eth) public isActivated() isHuman() isWithinLimits(_eth) { uint256 compressData = checkRoundAndDraw(msg.sender); reloadCore(msg.sender, _affID, _eth); emit onEndTx( rID_, msg.sender, compressData, _eth, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev direct buy nums with use your vaults in express way * @param _affID the id of the player who gets the affiliate fee * @param _eth the vaults you want pay for * @param _nums which nums you buy, no more than 10 */ function expressReloadNums(uint256 _affID, uint256 _eth, uint256[] _nums) public isActivated() isHuman() isWithinLimits(_eth) inSufficient(_eth, _nums) { uint256 compressData = checkRoundAndDraw(msg.sender); reloadCore(msg.sender, _affID, _eth); convertCore(msg.sender, _nums.length, TicketCompressor.encode(_nums)); emit onEndTx( rID_, msg.sender, compressData, _eth, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev direct buy section nums with use your vaults in express way * @param _affID the id of the player who gets the affiliate fee * @param _eth the vaults you want pay for * @param _startNums section nums, start * @param _endNums section nums, end */ function expressReloadNumSec(uint256 _affID, uint256 _eth, uint256[] _startNums, uint256[] _endNums) public isActivated() isHuman() isWithinLimits(_eth) inSufficient2(_eth, _startNums, _endNums) { uint256 compressData = checkRoundAndDraw(msg.sender); reloadCore(msg.sender, _affID, _eth); convertCore(msg.sender, calcSectionTickets(_startNums, _endNums), TicketCompressor.encode(_startNums, _endNums)); emit onEndTx( rID_, msg.sender, compressData, _eth, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev convert to nums with you consume tickets * @param nums which nums you buy, no more than 10 */ function convertNums(uint256[] nums) public { uint256 compressData = checkRoundAndDraw(msg.sender); convertCore(msg.sender, nums.length, TicketCompressor.encode(nums)); emit onEndTx( rID_, msg.sender, compressData, 0, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } /** * @dev convert to section nums with you consume tickets * @param startNums section nums, start * @param endNums section nums, end */ function convertNumSec(uint256[] startNums, uint256[] endNums) public { uint256 compressData = checkRoundAndDraw(msg.sender); convertCore(msg.sender, calcSectionTickets(startNums, endNums), TicketCompressor.encode(startNums, endNums)); emit onEndTx( rID_, msg.sender, compressData, 0, round_[rID_].pot, playerTickets_[msg.sender], block.timestamp ); } function buyCore(address _addr, uint256 _affID, uint256 _eth) private { /** * 2% transfer to foundation * 18% transfer to pot * 80% transfer to millionaire, 50% use to convert MFCoin and 30% use to genAndAff */ // 1 ticket = 0.002 eth, i.e., tickets = eth * 500 playerTickets_[_addr] = playerTickets_[_addr].add(_eth.mul(500)/1 ether); // transfer 2% to foundation uint256 foundFee = _eth.div(50); fundAddr_.transfer(foundFee); // transfer 80%(50% use to convert MFCoin and 30% use to genAndAff) amount to millionaire uint256 milFee = _eth.mul(80).div(100); millionaire_.updateGenVaultAndMask.value(milFee)(_addr, _affID); round_[rID_].pot = round_[rID_].pot.add(_eth.sub(milFee).sub(foundFee)); } function reloadCore(address _addr, uint256 _affID, uint256 _eth) private { /** * 2% transfer to foundation * 18% transfer to pot * 80% transfer to millionaire, 50% use to convert MFCoin and 30% use to genAndAff */ // transfer 80%(50% use to convert MFCoin and 30% use to genAndAff) amount to millionaire uint256 milFee = _eth.mul(80).div(100); millionaire_.clearGenVaultAndMask(_addr, _affID, _eth, milFee); // 1 ticket = 0.002 eth, i.e., tickets = eth * 500 playerTickets_[_addr] = playerTickets_[_addr].add(_eth.mul(500)/1 ether); // transfer 2% to foundation uint256 foundFee = _eth.div(50); fundAddr_.transfer(foundFee); //game pot will add in default function //round_[rID_].pot = round_[rID_].pot.add(_eth.sub(milFee).sub(foundFee)); } function convertCore(address _addr, uint256 length, uint256 compressNumber) private { playerTickets_[_addr] = playerTickets_[_addr].sub(length); uint256[] storage plyTicNums = playerTicketNumbers_[rID_][_addr]; plyTicNums.push(compressNumber); } // in order to draw the MilFold, we have to do all as following // 1. end current round // 2. calculate the draw-code // 3. claim winned // 4. assign to foundation, winners, and migrate the rest to the next round function checkRoundAndDraw(address _addr) private returns(uint256) { if (lID_ > 0 && round_[lID_].state == Mildatasets.RoundState.STOPPED && (block.number.sub(lBlockNumber_) >= 7)) { // calculate the draw-code round_[lID_].drawCode = calcDrawCode(); round_[lID_].claimDeadline = now + claimMax_; round_[lID_].state = Mildatasets.RoundState.DRAWN; round_[lID_].blockNumber = block.number; round_[rID_].roundDeadline = now + rndMax_; if (round_[rID_].pot > COMMON_REWARD_AMOUNT) { round_[rID_].pot = round_[rID_].pot.sub(COMMON_REWARD_AMOUNT); //reward who Draw Code 0.01 ether _addr.transfer(COMMON_REWARD_AMOUNT); emit onReward(_addr, Mildatasets.RewardType.DRAW, COMMON_REWARD_AMOUNT); } return lID_ << 96 | round_[lID_].claimDeadline << 64 | round_[lID_].drawCode << 32 | uint256(Mildatasets.TxAction.DRAW) << 8 | uint256(Mildatasets.RoundState.DRAWN); } else if (lID_ > 0 && round_[lID_].state == Mildatasets.RoundState.DRAWN && now > round_[lID_].claimDeadline) { // assign to foundation, winners, and migrate the rest to the next round if (round_[lID_].totalNum > 0) { assignCore(); } round_[lID_].state = Mildatasets.RoundState.ASSIGNED; if (round_[rID_].pot > COMMON_REWARD_AMOUNT) { round_[rID_].pot = round_[rID_].pot.sub(COMMON_REWARD_AMOUNT); //reward who Draw Code 0.01 ether _addr.transfer(COMMON_REWARD_AMOUNT); emit onReward(_addr, Mildatasets.RewardType.ASSIGN, COMMON_REWARD_AMOUNT); } return lID_ << 96 | uint256(Mildatasets.TxAction.ASSIGN) << 8 | uint256(Mildatasets.RoundState.ASSIGNED); } else if ((rID_ == 1 || round_[lID_].state == Mildatasets.RoundState.ASSIGNED) && now >= round_[rID_].roundDeadline) { // end current round lID_ = rID_; lBlockNumber_ = block.number; round_[lID_].state = Mildatasets.RoundState.STOPPED; rID_ = rID_ + 1; // migrate last round pot to this round util last round draw round_[rID_].state = Mildatasets.RoundState.STARTED; if (round_[lID_].pot > COMMON_REWARD_AMOUNT) { round_[rID_].pot = round_[lID_].pot.sub(COMMON_REWARD_AMOUNT); //reward who end round 0.01 ether _addr.transfer(COMMON_REWARD_AMOUNT); emit onReward(_addr, Mildatasets.RewardType.END, COMMON_REWARD_AMOUNT); } else { round_[rID_].pot = round_[lID_].pot; } return rID_ << 96 | uint256(Mildatasets.TxAction.ENDROUND) << 8 | uint256(Mildatasets.RoundState.STARTED); } return rID_ << 96 | uint256(Mildatasets.TxAction.BUY) << 8 | uint256(round_[rID_].state); } /** * @dev claim the winner identified by the given player's address * @param _addr player's address */ function claimWinner(address _addr) public isActivated() isHuman() { require(lID_ > 0 && round_[lID_].state == Mildatasets.RoundState.DRAWN && now <= round_[lID_].claimDeadline, "it's not time for claiming"); require(round_[lID_].winnerNum[_addr] == 0, "the winner have been claimed already"); uint winNum = 0; uint256[] storage ptns = playerTicketNumbers_[lID_][_addr]; for (uint256 j = 0; j < ptns.length; j ++) { (uint256 tType, uint256 tLength, uint256[] memory playCvtNums) = TicketCompressor.decode(ptns[j]); for (uint256 k = 0; k < tLength; k ++) { if ((tType == 1 && playCvtNums[k] == round_[lID_].drawCode) || (tType == 2 && round_[lID_].drawCode >= playCvtNums[2 * k] && round_[lID_].drawCode <= playCvtNums[2 * k + 1])) { winNum++; } } } if (winNum > 0) { if (round_[lID_].winnerNum[_addr] == 0) { round_[lID_].winners.push(_addr); } round_[lID_].totalNum = round_[lID_].totalNum.add(winNum); round_[lID_].winnerNum[_addr] = winNum; uint256 rewardAmount = CLAIM_WINNER_REWARD_AMOUNT.min(round_[lID_].pot.div(200)); //reward who claim winner ,min 1 ether,no more than 1% reward round_[rID_].pot = round_[rID_].pot.sub(rewardAmount); // reward who claim an winner msg.sender.transfer(rewardAmount); emit onReward(msg.sender, Mildatasets.RewardType.CLIAM, COMMON_REWARD_AMOUNT); emit onClaimWinner( _addr, winNum, round_[lID_].totalNum ); } } function assignCore() private { /** * 2% transfer to foundation * 48% transfer to next round * 50% all winner share 50% pot on condition singal share no more than MAX_WIN_AMOUNT */ uint256 lPot = round_[lID_].pot; uint256 totalWinNum = round_[lID_].totalNum; uint256 winShareAmount = (MAX_WIN_AMOUNT.mul(totalWinNum)).min(lPot.div(2)); uint256 foundFee = lPot.div(50); fundAddr_.transfer(foundFee); uint256 avgShare = winShareAmount / totalWinNum; for (uint256 idx = 0; idx < round_[lID_].winners.length; idx ++) { address addr = round_[lID_].winners[idx]; uint256 num = round_[lID_].winnerNum[round_[lID_].winners[idx]]; uint256 amount = round_[lID_].winnerNum[round_[lID_].winners[idx]].mul(avgShare); millionaire_.assign.value(amount)(addr); playerWinTotal_[addr] = playerWinTotal_[addr].add(amount); emit onPlayerWin(addr, lID_, amount, num); } round_[rID_].pot = round_[rID_].pot.sub(winShareAmount).sub(foundFee); } function calcSectionTickets(uint256[] startNums, uint256[] endNums) private pure returns(uint256) { require(startNums.length == endNums.length, "tickets length invalid"); uint256 totalTickets = 0; uint256 tickets = 0; for (uint256 i = 0; i < startNums.length; i ++) { tickets = endNums[i].sub(startNums[i]).add(1); totalTickets = totalTickets.add(tickets); } return totalTickets; } function calcDrawCode() private view returns(uint256) { return uint256(keccak256(abi.encodePacked( ((uint256(keccak256(abi.encodePacked(blockhash(block.number))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 2))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 3))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 4))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 5))))) / (block.timestamp)).add ((uint256(keccak256(abi.encodePacked(blockhash(block.number - 6))))) / (block.timestamp)) ))) % 10000000; } function activate() public { // only millionaire can activate require(msg.sender == address(millionaire_), "only contract millionaire can activate"); // can only be ran once require(activated_ == false, "MilFold already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].roundDeadline = now + rndMax_; round_[1].state = Mildatasets.RoundState.STARTED; // round_[0].pot refers to initial pot from ico phase round_[1].pot = round_[0].pot; } function addPot() public payable { require(milAuth_.checkGameClosed(address(this)) == false, "game already closed"); require(msg.value > 0, "add pot failed"); round_[rID_].pot = round_[rID_].pot.add(msg.value); } function close() public isActivated onlyDevs { require(milAuth_.checkGameClosed(address(this)), "game no closed"); activated_ = false; millionaire_.splitPot.value(address(this).balance)(); } /** * @dev return players's total winning eth * @param _addr player's address * @return player's total tickets * @return player's total winning eth */ function getPlayerAccount(address _addr) public view returns(uint256, uint256) { return (playerTickets_[_addr], playerWinTotal_[_addr]); } /** * @dev return numbers in the round * @param _rid round id * @param _addr player's address * @return player's numbers */ function getPlayerRoundNums(uint256 _rid, address _addr) public view returns(uint256[]) { return playerTicketNumbers_[_rid][_addr]; } /** * @dev return player's winning information in the round * @return winning numbers * @param _rid round id * @param _addr player's address */ function getPlayerRoundWinningInfo(uint256 _rid, address _addr) public view returns(uint256) { Mildatasets.RoundState state = round_[_rid].state; if (state >= Mildatasets.RoundState.UNKNOWN && state < Mildatasets.RoundState.DRAWN) { return 0; } else if (state == Mildatasets.RoundState.ASSIGNED) { return round_[_rid].winnerNum[_addr]; } else { // only drawn but not assigned, we need to query the player's winning numbers uint256[] storage ptns = playerTicketNumbers_[_rid][_addr]; uint256 nums = 0; for (uint256 j = 0; j < ptns.length; j ++) { (uint256 tType, uint256 tLength, uint256[] memory playCvtNums) = TicketCompressor.decode(ptns[j]); for (uint256 k = 0; k < tLength; k ++) { if ((tType == 1 && playCvtNums[k] == round_[_rid].drawCode) || (tType == 2 && round_[_rid].drawCode >= playCvtNums[2 * k] && round_[lID_].drawCode <= playCvtNums[2 * k + 1])) { nums ++; } } } return nums; } } /** * @dev check player is claim in round * @param _rid round id * @param _addr player address * @return true is claimed else false */ function checkPlayerClaimed(uint256 _rid, address _addr) public view returns(bool) { return round_[_rid].winnerNum[_addr] > 0; } /** * @dev return current round information * @return round id * @return last round state * 1. current round started * 2. current round stopped(wait for drawing code) * 3. drawn code(wait for claiming winners) * 4. assigned to foundation, winners, and migrate the rest to the next round) * @return round end time * @return last round claiming time * @return round pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256) { return ( rID_, uint256(round_[lID_].state), round_[rID_].roundDeadline, round_[lID_].claimDeadline, round_[rID_].pot ); } /** * @dev return history round information * @param _rid round id * @return items include as following * round state * 1. current round started * 2. current round stopped(wait for drawing code) * 3. drawn code(wait for claiming winners) * 4. assigned to foundation, winners, and migrate the rest to the next round) * round end time * winner claim end time * draw code * round pot * draw block number(last one) * @return winners' address * @return winning number */ function getHistoryRoundInfo(uint256 _rid) public view returns(uint256[], address[], uint256[]) { uint256 length = round_[_rid].winners.length; uint256[] memory numbers = new uint256[](length); if (round_[_rid].winners.length > 0) { for (uint256 idx = 0; idx < length; idx ++) { numbers[idx] = round_[_rid].winnerNum[round_[_rid].winners[idx]]; } } uint256[] memory items = new uint256[](6); items[0] = uint256(round_[_rid].state); items[1] = round_[_rid].roundDeadline; items[2] = round_[_rid].claimDeadline; items[3] = round_[_rid].drawCode; items[4] = round_[_rid].pot; items[5] = round_[_rid].blockNumber; return (items, round_[_rid].winners, numbers); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library Mildatasets { // between `DRAWN' and `ASSIGNED', someone need to claim winners. enum RoundState { UNKNOWN, // aim to differ from normal states STARTED, // start current round STOPPED, // stop current round DRAWN, // draw code ASSIGNED // assign to foundation, winners, and migrate the rest to the next round } // MilFold Transaction Action. enum TxAction { UNKNOWN, // default BUY, // buy or reload tickets and so on DRAW, // draw code of game ASSIGN, // assign to winners ENDROUND // end game and start new round } // RewardType enum RewardType { UNKNOWN, // default DRAW, // draw code ASSIGN, // assign winner END, // end game CLIAM // winner cliam } struct Player { uint256 playerID; // Player id(use to affiliate other player) uint256 eth; // player eth balance uint256 mask; // player mask uint256 genTotal; // general total vault uint256 affTotal; // affiliate total vault uint256 laff; // last affiliate id used } struct Round { uint256 roundDeadline; // deadline to end round uint256 claimDeadline; // deadline to claim winners uint256 pot; // pot uint256 blockNumber; // draw block number(last one) RoundState state; // round state uint256 drawCode; // draw code uint256 totalNum; // total number mapping (address => uint256) winnerNum; // winners' number address[] winners; // winners } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); 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 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } } library TicketCompressor { uint256 constant private mask = 16777215; //2 ** 24 - 1 function encode(uint256[] tickets) internal pure returns(uint256) { require((tickets.length > 0) && (tickets.length <= 10), "tickets must > 0 and <= 10"); uint256 value = tickets[0]; for (uint256 i = 1 ; i < tickets.length ; i++) { require(tickets[i] < 10000000, "ticket number must < 10000000"); value = value << 24 | tickets[i]; } return 1 << 248 | tickets.length << 240 | value; } function encode(uint256[] startTickets, uint256[] endTickets) internal pure returns(uint256) { require(startTickets.length > 0 && startTickets.length == endTickets.length && startTickets.length <= 5, "section tickets must > 0 and <= 5"); uint256 value = startTickets[0] << 24 | endTickets[0]; for (uint256 i = 1 ; i < startTickets.length ; i++) { require(startTickets[i] <= endTickets[i] && endTickets[i] < 10000000, "tickets number invalid"); value = value << 48 | startTickets[i] << 24 | endTickets[i]; } return 2 << 248 | startTickets.length << 240 | value; } function decode(uint256 _input) internal pure returns(uint256,uint256,uint256[]) { uint256 _type = _input >> 248; uint256 _length = _input >> 240 & 127; require(_type == 1 || _type == 2, "decode type is incorrect!"); if (_type == 1) { uint256[] memory results = new uint256[](_length); uint256 tempVal = _input; for (uint256 i=0 ; i < _length ; i++) { results[i] = tempVal & mask; tempVal = tempVal >> 24; } return (_type,_length,results); } else { uint256[] memory result2 = new uint256[](_length * 2); uint256 tempVal2 = _input; for (uint256 j=0 ; j < _length ; j++) { result2[2 * j + 1] = tempVal2 & mask; tempVal2 = tempVal2 >> 24; result2[2 * j] = tempVal2 & mask; tempVal2 = tempVal2 >> 24; } return (_type,_length,result2); } } }
* @dev return current round information @return round id @return last round state 1. current round started 2. current round stopped(wait for drawing code) 3. drawn code(wait for claiming winners) 4. assigned to foundation, winners, and migrate the rest to the next round) @return round end time @return last round claiming time @return round pot/
function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256) { return ( rID_, uint256(round_[lID_].state), round_[rID_].roundDeadline, round_[lID_].claimDeadline, round_[rID_].pot ); }
945,436
[ 1, 2463, 783, 3643, 1779, 327, 3643, 612, 327, 1142, 3643, 919, 1377, 404, 18, 783, 3643, 5746, 1377, 576, 18, 783, 3643, 9627, 12, 7048, 364, 16327, 981, 13, 1377, 890, 18, 19377, 981, 12, 7048, 364, 7516, 310, 5657, 9646, 13, 1377, 1059, 18, 6958, 358, 1392, 367, 16, 5657, 9646, 16, 471, 13187, 326, 3127, 358, 326, 1024, 3643, 13, 327, 3643, 679, 813, 327, 1142, 3643, 7516, 310, 813, 327, 3643, 5974, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 5175, 11066, 966, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 327, 261, 203, 5411, 436, 734, 67, 16, 203, 5411, 2254, 5034, 12, 2260, 67, 63, 80, 734, 67, 8009, 2019, 3631, 203, 5411, 3643, 67, 63, 86, 734, 67, 8009, 2260, 15839, 16, 203, 5411, 3643, 67, 63, 80, 734, 67, 8009, 14784, 15839, 16, 203, 5411, 3643, 67, 63, 86, 734, 67, 8009, 13130, 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 ]
// Sources flattened with hardhat v2.6.5 https://hardhat.org // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @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; } } } // File @openzeppelin/contracts-upgradeable/security/[email protected] /** * @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; } // File @openzeppelin/contracts-upgradeable/access/[email protected] /** * @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; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] /** * @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); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] /** * @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); } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] /** * @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; } // File contracts/bico-token/bico/BicoTokenImplementation.sol pragma solidity 0.8.4; /** * @dev Context variant with ERC2771 support. */ abstract contract ERC2771ContextUpgradeable is Initializable { /* * Forwarder singleton we accept calls from */ address public _trustedForwarder; function __ERC2771Context_init(address trustedForwarder) internal initializer { __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address trustedForwarder) internal initializer { _trustedForwarder = trustedForwarder; } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual 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(), 20))) } } else { return msg.sender; } } function _msgData() internal view virtual returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return msg.data; } } uint256[49] private __gap; } /** * @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 { /** * @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 { __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(), "BICO:: 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(), "BICO:: Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[49] private __gap; } /** * @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, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __ERC165_init(); __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, msg.sender); _; } /** * @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( "BICO:: 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 == msg.sender, "BICO:: 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, msg.sender); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } uint256[49] private __gap; } /** * @title Biconomy Protocol Governance contract * @dev All contracts that will be owned by a Governor entity should extend this contract. */ contract GovernedUpgradeable is Initializable { // -- State -- address public governor; address public pendingGovernor; // -- Events -- event NewPendingOwnership(address indexed from, address indexed to); event NewOwnership(address indexed from, address indexed to); /** * @dev Check if the caller is the governor. */ modifier onlyGovernor { require(msg.sender == governor, "BICO:: Only Governor can call"); _; } /** * @dev Initialize the governor to the contract caller. */ function __Governed_init(address _initGovernor) internal initializer { __Governed_init_unchained(_initGovernor); } function __Governed_init_unchained(address _initGovernor) internal initializer { governor = _initGovernor; } /** * @dev Admin function to begin change of governor. The `_newGovernor` must call * `acceptOwnership` to finalize the transfer. * @param _newGovernor Address of new `governor` */ function transferOwnership(address _newGovernor) external onlyGovernor { require(_newGovernor != address(0), "BICO:: Governor must be set"); address oldPendingGovernor = pendingGovernor; pendingGovernor = _newGovernor; emit NewPendingOwnership(oldPendingGovernor, pendingGovernor); } /** * @dev Admin function for pending governor to accept role and update governor. * This function must called by the pending governor. */ function acceptOwnership() external { require( pendingGovernor != address(0) && msg.sender == pendingGovernor, "Caller must be pending governor" ); address oldGovernor = governor; address oldPendingGovernor = pendingGovernor; governor = pendingGovernor; pendingGovernor = address(0); emit NewOwnership(oldGovernor, governor); emit NewPendingOwnership(oldPendingGovernor, pendingGovernor); } uint256[49] private __gap; } /** * @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("BICO:: 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. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "BICO:: ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "BICO:: 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), "BICO:: 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)); } } contract BicoTokenImplementation is Initializable, ERC2771ContextUpgradeable, PausableUpgradeable, AccessControlUpgradeable, GovernedUpgradeable, ReentrancyGuardUpgradeable { // -- State ERC20-- mapping(address => uint256) private _balances; uint8 internal _initializedVersion; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; // -- State Access Control custom roles-- bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice The timestamp after which minting may occur uint public mintingAllowedAfter; /// @notice Minimum time between mints uint32 public minimumTimeBetweenMints; /// @notice Cap on the percentage of totalSupply that can be minted at each mint uint8 public mintCap; // -- State Gas abstraction methods-- /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ); bytes32 public constant APPROVE_TYPEHASH = keccak256( "Approve(address owner,address spender,uint256 value,uint256 batchId,uint256 batchNonce,uint256 deadline)" ); bytes32 public constant TRANSFER_TYPEHASH = keccak256( "Transfer(address sender,address recipient,uint256 amount,uint256 batchId,uint256 batchNonce,uint256 deadline)" ); bytes32 private DOMAIN_SEPARATOR; /// @notice A record of states for signing / validating signatures mapping(address => mapping(uint256 => uint256)) public nonces; // -- Events-- /** * @dev Emitted when trusted forwarder is updated to * another (`trustedForwarder`). * * Note that `trustedForwarder` may be zero. `actor` is msg.sender for this action. */ event TrustedForwarderChanged(address indexed truestedForwarder, address indexed actor); /** * @dev Emitted when minting allowed after timestamp is changed through governance * * Note that `_mintingAllowedAfter` may be zero. `actor` is msg.sender for this action. */ event MintingAllowedAfterChanged(uint indexed _mintingAllowedAfter, address indexed actor); /** * @dev Emitted when minimum time between mints is changed through governance * * Note that `_minimumTimeBetweenMints` may be zero. `actor` is msg.sender for this action. */ event MinimumTimeBetweenMintsChanged(uint32 indexed _minimumTimeBetweenMints, address indexed actor); /** * @dev Emitted when mint cap is changed through governance * * Note that `_mintCap` may be zero. `actor` is msg.sender for this action. */ event MintCapChanged(uint8 indexed _mintCap, address indexed actor); /** * @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 Initializes the contract */ function initialize(address beneficiary, address trustedForwarder, address governor, address accessControlAdmin, address pauser, address minter) public initializer { __BicoTokenImplementation_init_unchained(accessControlAdmin,pauser,minter); _mint(beneficiary, 1000000000 * 10 ** decimals()); __ERC2771Context_init(trustedForwarder); __Pausable_init(); __AccessControl_init(); __Governed_init(governor); __ReentrancyGuard_init(); _initializedVersion = 0; mintingAllowedAfter = 0; minimumTimeBetweenMints = 1 days * 365; mintCap = 2; } function __BicoTokenImplementation_init_unchained(address accessControlAdmin, address pauser, address minter) internal initializer { _name = "Biconomy Token"; _symbol = "BICO"; _setupRole(DEFAULT_ADMIN_ROLE, accessControlAdmin); _setupRole(PAUSER_ROLE, pauser); _setupRole(MINTER_ROLE, minter); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, keccak256("Biconomy Token"), keccak256("1"), address(this), bytes32(getChainId()) ) ); } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual 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 nonReentrant whenNotPaused returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual 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 nonReentrant whenNotPaused 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 nonReentrant whenNotPaused returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "BICO:: ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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 virtual nonReentrant whenNotPaused 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 virtual nonReentrant whenNotPaused returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "BICO:: ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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), "BICO:: ERC20: transfer from the zero address"); require(recipient != address(0), "BICO:: ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "BICO:: ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - 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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "BICO:: ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } //there is no public burn() method in V0 /** * @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), "BICO:: ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "BICO:: ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= 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), "BICO:: ERC20: approve from the zero address"); require(spender != address(0), "BICO:: ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Increments the nonce of given user/batch pair * @dev Updates the highestBatchId of the given user if the request's batchId > current highest * @dev only intended to be called post call execution * @param _user : owner or sender address * @param _batchId : batch Id */ function _updateNonce(address _user, uint256 _batchId) internal { nonces[_user][_batchId]++; } /** * @dev Approve token allowance by validating a message signed by the holder. * @param _owner Address of the token holder * @param _spender Address of the approved spender * @param _value Amount of tokens to approve the spender * @param _batchId Batch Id. pass this 0 if batching is not needed. * @param _deadline Expiration time of the signed approval * @param _v Signature version * @param _r Signature r value * @param _s Signature s value */ function approveWithSig( uint8 _v, bytes32 _r, bytes32 _s, uint256 _deadline, address _owner, uint256 _batchId, address _spender, uint256 _value ) public virtual nonReentrant whenNotPaused { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( APPROVE_TYPEHASH, _owner, _spender, _value, _batchId, nonces[_owner][_batchId], _deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v)); require(recoveredAddress != address(0), "BICO:: invalid signature"); require(_owner == recoveredAddress, "BICO:: invalid approval:Unauthorized"); require(_deadline == 0 || block.timestamp <= _deadline, "BICO:: expired approval"); _updateNonce(_owner,_batchId); _approve(_owner, _spender, _value); } /** * @dev Transfer tokens by validating a message signed by the sender. * @param _sender Address of the token sender * @param _recipient Address of the token recipient * @param _amount Amount of tokens to transfer * @param _batchId Batch Id. pass this 0 if batching is not needed. * @param _deadline Expiration time of the signed approval * @param _v Signature version * @param _r Signature r value * @param _s Signature s value */ function transferWithSig( uint8 _v, bytes32 _r, bytes32 _s, uint256 _deadline, address _sender, uint256 _batchId, address _recipient, uint256 _amount ) public virtual nonReentrant whenNotPaused { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( TRANSFER_TYPEHASH, _sender, _recipient, _amount, _batchId, nonces[_sender][_batchId], _deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v)); require(recoveredAddress != address(0), "BICO:: invalid signature"); require(_sender == recoveredAddress, "BICO:: invalid transfer:Unauthorized"); require(_deadline == 0 || block.timestamp <= _deadline, "BICO:: expired transfer"); _updateNonce(_sender,_batchId); _transfer(_sender, _recipient, _amount); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function setTrustedForwarder(address payable _forwarder) external onlyGovernor { require(_forwarder != address(0), "BICO:: Invalid address for new trusted forwarder"); _trustedForwarder = _forwarder; emit TrustedForwarderChanged(_forwarder, msg.sender); } function setMintingAllowedAfter(uint _mintingAllowedAfter) external onlyGovernor { mintingAllowedAfter = _mintingAllowedAfter; emit MintingAllowedAfterChanged(_mintingAllowedAfter,msg.sender); } function setMinimumTimeBetweenMints(uint32 _minimumTimeBetweenMints) external onlyGovernor { minimumTimeBetweenMints = _minimumTimeBetweenMints; emit MinimumTimeBetweenMintsChanged(_minimumTimeBetweenMints,msg.sender); } function setMintCap(uint8 _mintCap) external onlyGovernor { mintCap = _mintCap; emit MintCapChanged(_mintCap, msg.sender); } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @dev Admin function to begin change of governor. The `_newGovernor` must call `acceptOwnership` to finalize the transfer. @param _newGovernor Address of new `governor`/
function transferOwnership(address _newGovernor) external onlyGovernor { require(_newGovernor != address(0), "BICO:: Governor must be set"); address oldPendingGovernor = pendingGovernor; pendingGovernor = _newGovernor; emit NewPendingOwnership(oldPendingGovernor, pendingGovernor); }
13,941,712
[ 1, 4446, 445, 358, 2376, 2549, 434, 314, 1643, 29561, 18, 1021, 1375, 67, 2704, 43, 1643, 29561, 68, 1297, 745, 1375, 9436, 5460, 12565, 68, 358, 12409, 326, 7412, 18, 225, 389, 2704, 43, 1643, 29561, 5267, 434, 394, 1375, 75, 1643, 29561, 68, 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, 7412, 5460, 12565, 12, 2867, 389, 2704, 43, 1643, 29561, 13, 3903, 1338, 43, 1643, 29561, 288, 203, 3639, 2583, 24899, 2704, 43, 1643, 29561, 480, 1758, 12, 20, 3631, 315, 38, 2871, 51, 2866, 611, 1643, 29561, 1297, 506, 444, 8863, 203, 203, 3639, 1758, 1592, 8579, 43, 1643, 29561, 273, 4634, 43, 1643, 29561, 31, 203, 3639, 4634, 43, 1643, 29561, 273, 389, 2704, 43, 1643, 29561, 31, 203, 203, 3639, 3626, 1166, 8579, 5460, 12565, 12, 1673, 8579, 43, 1643, 29561, 16, 4634, 43, 1643, 29561, 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 ]
./full_match/4/0x601B3155f6D95bd8cF572DAF9c21ddE0614bc9CF/sources/sport/sports.sol
@winTeam:胜利队伍 初始为0当比赛时由预言机导入比赛结果@dev: 结算/ require(block.timestamp>NumberStatus[number].endTime, "invalid time"); 我数量在同类型总量中的比例 如果有推荐人需分给推荐人
function settlement(uint number, uint winTeam) external{ uint buyTeam1count; uint buyTeam2count; uint buyTeam3count; uint allCount; uint winAmount; uint lostAmount; uint myRate; for(uint i; i<NumberStatus[number].userCount +1; i++) { bill memory billcount = NumberAccount[number][i]; allCount = allCount + billcount.amount; if (billcount.buyTeam == 1) { buyTeam1count = buyTeam1count + billcount.amount; } if (billcount.buyTeam == 2) { buyTeam2count = buyTeam2count + billcount.amount; } if (billcount.buyTeam == 3) { buyTeam3count = buyTeam3count + billcount.amount; } } if (winTeam == 1) { winAmount = buyTeam1count; lostAmount = buyTeam2count + buyTeam3count; } if (winTeam == 2) { winAmount = buyTeam2count; lostAmount = buyTeam1count + buyTeam3count; } if (winTeam == 3) { winAmount = buyTeam3count; lostAmount = buyTeam1count + buyTeam2count; } for(uint i;i<NumberStatus[number].userCount + 1; i++) { if (NumberAccount[number][i].buyTeam == winTeam) { bill memory winbill = NumberAccount[number][i]; myRate = (winbill.amount * 10000) / winAmount; uint allReturn = (allCount * myRate) / 10000; uint netRetrun = (allReturn * WinnerRate) / 10000; MyReturns[winbill.account] = MyReturns[winbill.account] + netRetrun; if(winbill.referrer != address(0)) { uint refRetrun = (allReturn * referrerRate) / 10000; fee = fee + (allReturn - netRetrun - refRetrun); MyReturns[winbill.referrer] = MyReturns[winbill.referrer] + refRetrun; fee = fee + (allReturn-netRetrun); } } } NumberStatus[number].winTeam = winTeam; NumberStatus[number].status = 3; }
12,312,385
[ 1, 36, 8082, 8689, 176, 125, 253, 169, 230, 255, 166, 235, 107, 170, 251, 258, 165, 125, 240, 225, 166, 235, 256, 166, 105, 238, 165, 121, 123, 20, 166, 126, 246, 167, 112, 247, 169, 118, 254, 167, 250, 119, 168, 247, 114, 170, 100, 231, 169, 106, 227, 167, 255, 123, 166, 112, 125, 166, 232, 103, 167, 112, 247, 169, 118, 254, 168, 124, 246, 167, 257, 255, 30, 225, 168, 124, 246, 168, 111, 250, 19, 2583, 12, 2629, 18, 5508, 34, 1854, 1482, 63, 2696, 8009, 409, 950, 16, 315, 5387, 813, 8863, 225, 167, 235, 244, 167, 248, 113, 170, 234, 242, 166, 255, 106, 166, 243, 239, 168, 114, 124, 166, 257, 238, 167, 227, 124, 170, 234, 242, 165, 121, 260, 168, 253, 231, 167, 112, 247, 165, 127, 238, 225, 166, 104, 229, 167, 257, 255, 167, 255, 236, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 26319, 806, 12, 11890, 1300, 16, 2254, 5657, 8689, 13, 3903, 95, 203, 203, 3639, 2254, 30143, 8689, 21, 1883, 31, 203, 3639, 2254, 30143, 8689, 22, 1883, 31, 203, 3639, 2254, 30143, 8689, 23, 1883, 31, 203, 3639, 2254, 777, 1380, 31, 203, 3639, 2254, 5657, 6275, 31, 203, 3639, 2254, 13557, 6275, 31, 203, 3639, 2254, 3399, 4727, 31, 203, 203, 3639, 364, 12, 11890, 277, 31, 277, 32, 1854, 1482, 63, 2696, 8009, 1355, 1380, 397, 21, 31, 277, 27245, 288, 203, 5411, 20714, 3778, 20714, 1883, 273, 3588, 3032, 63, 2696, 6362, 77, 15533, 203, 5411, 777, 1380, 273, 777, 1380, 397, 20714, 1883, 18, 8949, 31, 203, 5411, 309, 261, 17240, 1883, 18, 70, 9835, 8689, 422, 404, 13, 288, 203, 7734, 30143, 8689, 21, 1883, 273, 30143, 8689, 21, 1883, 397, 20714, 1883, 18, 8949, 31, 203, 5411, 289, 203, 5411, 309, 261, 17240, 1883, 18, 70, 9835, 8689, 422, 576, 13, 288, 203, 7734, 30143, 8689, 22, 1883, 273, 30143, 8689, 22, 1883, 397, 20714, 1883, 18, 8949, 31, 203, 5411, 289, 203, 5411, 309, 261, 17240, 1883, 18, 70, 9835, 8689, 422, 890, 13, 288, 203, 7734, 30143, 8689, 23, 1883, 273, 30143, 8689, 23, 1883, 397, 20714, 1883, 18, 8949, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 8082, 8689, 422, 404, 13, 288, 203, 5411, 5657, 6275, 273, 30143, 8689, 21, 1883, 31, 203, 5411, 13557, 6275, 273, 30143, 8689, 22, 1883, 397, 30143, 8689, 23, 1883, 31, 2 ]
// SPDX-License-Identifier: BSD-4-Clause pragma solidity 0.8.3; import "./IOddzSDK.sol"; import "./Libs/DateTimeLibrary.sol"; import "./Integrations/Gasless/BaseRelayRecipient.sol"; import "./Libs/IERC20Extented.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract OddzSDK is IOddzSDK, BaseRelayRecipient, AccessControl { using Address for address; using SafeERC20 for IERC20; bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE"); IOddzOption public optionManager; IERC20 public oddzToken; IERC20Extented public usdcToken; mapping(bytes32 => bool) public usersForTheMonth; // Month -> Amount mapping(uint256 => uint256) public totalPremiumCollected; mapping(uint256 => uint256) public totalOddzAllocated; // Address -> Month -> Amount mapping(address => mapping(uint256 => uint256)) public premiumCollected; /** * @dev minimum gasless premium */ uint256 public override minimumGaslessPremium; modifier onlyOwner(address _address) { require(hasRole(DEFAULT_ADMIN_ROLE, _address), "SDK: caller has no access to the method"); _; } modifier onlyTimeLocker(address _address) { require(hasRole(TIMELOCKER_ROLE, _address), "SDK: caller has no access to the method"); _; } constructor( IOddzOption _optionManager, address _trustedForwarder, IERC20 _oddzToken, IERC20Extented _usdcToken ) { oddzToken = _oddzToken; usdcToken = _usdcToken; optionManager = _optionManager; trustedForwarder = _trustedForwarder; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(TIMELOCKER_ROLE, msg.sender); _setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE); } function setTimeLocker(address _address) external { require(_address != address(0), "SDK: Invalid timelocker address"); grantRole(TIMELOCKER_ROLE, _address); } function removeTimeLocker(address _address) external { revokeRole(TIMELOCKER_ROLE, _address); } function setTrustedForwarder(address forwarderAddress) public onlyOwner(msg.sender) { require(forwarderAddress != address(0), "SDK: Forwarder Address cannot be 0"); trustedForwarder = forwarderAddress; } function versionRecipient() external view virtual override returns (string memory) { return "1"; } function msgSender() internal view virtual override returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return msg.sender; } } function buy( address _pair, bytes32 _optionModel, uint256 _premiumWithSlippage, uint256 _expiration, uint256 _amount, uint256 _strike, IOddzOption.OptionType _optionType, address _provider ) public override returns (uint256 optionId) { IOddzOption.OptionDetails memory option = IOddzOption.OptionDetails(_optionModel, _expiration, _pair, _amount, _strike, _optionType); return _buy(option, _premiumWithSlippage, _provider, msg.sender); } function buyWithGasless( address _pair, bytes32 _optionModel, uint256 _premiumWithSlippage, uint256 _expiration, uint256 _amount, uint256 _strike, IOddzOption.OptionType _optionType, address _provider ) public override returns (uint256 optionId) { IOddzOption.OptionDetails memory option = IOddzOption.OptionDetails(_optionModel, _expiration, _pair, _amount, _strike, _optionType); IOddzOption.PremiumResult memory premiumResult = optionManager.getPremium(option, msgSender()); require( premiumResult.optionPremium + premiumResult.txnFee > minimumGaslessPremium, "SDK: premium amount not elgible for gasless" ); return _buy(option, _premiumWithSlippage, _provider, msgSender()); } function _buy( IOddzOption.OptionDetails memory _option, uint256 _premiumWithSlippage, address _provider, address _buyer ) private returns (uint256 optionId) { require(_provider != address(0), "SDK: invalid provider address"); optionId = optionManager.buy(_option, _premiumWithSlippage, _buyer); (, , , , , uint256 premium, , , ) = optionManager.options(optionId); uint256 month = DateTimeLibrary.getMonth(block.timestamp); if (!usersForTheMonth[keccak256(abi.encode(_provider, month))]) { usersForTheMonth[keccak256(abi.encode(_provider, month))] = true; emit OptionProvider(month, _provider); } premiumCollected[_provider][month] += premium; totalPremiumCollected[month] += premium; } function getPremium( address _pair, bytes32 _optionModel, uint256 _expiration, uint256 _amount, uint256 _strike, IOddzOption.OptionType _optionType ) public view override returns ( uint256 optionPremium, uint256 txnFee, uint256 iv, uint8 ivDecimal ) { IOddzOption.OptionDetails memory option = IOddzOption.OptionDetails(_optionModel, _expiration, _pair, _amount, _strike, _optionType); IOddzOption.PremiumResult memory premiumResult = optionManager.getPremium(option, msg.sender); optionPremium = premiumResult.optionPremium; txnFee = premiumResult.txnFee; iv = premiumResult.iv; ivDecimal = premiumResult.ivDecimal; } function allocateOddzReward(uint256 _amount) public override { totalOddzAllocated[DateTimeLibrary.getMonth(block.timestamp)] += _amount; oddzToken.safeTransferFrom(msg.sender, address(this), _amount); } function distributeReward(address[] memory _providers, uint256 _month) public override { require(DateTimeLibrary.getMonth(block.timestamp) > _month, "SDK: Oddz rewards not enabled for the month"); for (uint256 i = 0; i < _providers.length; i++) { bytes32 providerMonth = keccak256(abi.encode(_providers[i], _month)); // skip reward for ineligible provider if (!usersForTheMonth[providerMonth]) continue; // set provider as ineligible delete usersForTheMonth[providerMonth]; uint256 amount = (totalOddzAllocated[_month] * premiumCollected[_providers[i]][_month]) / totalPremiumCollected[_month]; if (amount > 0) oddzToken.safeTransfer(_providers[i], amount); } } function setMinimumGaslessPremium(uint256 _amount) external onlyTimeLocker(msg.sender) { uint256 amount = _amount / 10**usdcToken.decimals(); require(amount >= 1 && amount < 500, "invalid minimum gasless premium"); minimumGaslessPremium = _amount; } }
At this point we know that the sender is a trusted forwarder, so we trust that the last bytes of msg.data are the verified sender address. extract sender address from the end of msg.data
function msgSender() internal view virtual override returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } }
13,076,883
[ 1, 861, 333, 1634, 732, 5055, 716, 326, 5793, 353, 279, 13179, 364, 20099, 16, 1427, 732, 10267, 716, 326, 1142, 1731, 434, 1234, 18, 892, 854, 326, 13808, 5793, 1758, 18, 2608, 5793, 1758, 628, 326, 679, 434, 1234, 18, 892, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1234, 12021, 1435, 2713, 1476, 5024, 3849, 1135, 261, 2867, 325, 13, 288, 203, 3639, 309, 261, 3576, 18, 892, 18, 2469, 1545, 4248, 597, 353, 16950, 30839, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 19931, 288, 203, 7734, 325, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 5411, 289, 203, 5411, 327, 1234, 18, 15330, 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 ]
pragma solidity >=0.8.9 <0.9.0; //SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; import "../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "./ISwapper.sol"; import "./XToken.sol"; /* Hello and welcome to the ShibaBurn burning portal. This is a contract that empowers developers to create incentive based deflation for all ERC20 tokens! ShibaBurn allows for an infinite number of burn pools to be created for any given token. By default, burn pools track the following data: - total tokens burnt by each user - total tokens burnt by all users ShibaBurn also allows for ETH to be "zapped" into burn pool ownershib by means of buying the specified token on ShibaSwap, and burning it in one transaction. This is only possible if eth-token liquidity is present on ShibaSwap.com If configured by the ShibaBurn owner wallet, burn pools can optionally: - Mint xTokens for users (e.g. burntSHIB in the case of burning SHIB to the default pool) - Keep track of the index at which any given address exceeds a burnt amount beyond an admin specified threshold _____ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \ /::\____\ /::\ \ /::\ \ /::\ \ /::::\ \ /:::/ / \:::\ \ /::::\ \ /::::\ \ /::::::\ \ /:::/ / \:::\ \ /::::::\ \ /::::::\ \ /:::/\:::\ \ /:::/ / \:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/__\:::\ \ /:::/____/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ \:::\ \:::\ \ /::::\ \ /::::\ \ /::::\ \:::\ \ /::::\ \:::\ \ ___\:::\ \:::\ \ /::::::\ \ _____ ____ /::::::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /\ \:::\ \:::\ \ /:::/\:::\ \ /\ \ /\ \ /:::/\:::\ \ /:::/\:::\ \:::\ ___\ /:::/\:::\ \:::\ \ /::\ \:::\ \:::\____\/:::/ \:::\ /::\____\/::\ \/:::/ \:::\____\/:::/__\:::\ \:::| |/:::/ \:::\ \:::\____\ \:::\ \:::\ \::/ /\::/ \:::\ /:::/ /\:::\ /:::/ \::/ /\:::\ \:::\ /:::|____|\::/ \:::\ /:::/ / \:::\ \:::\ \/____/ \/____/ \:::\/:::/ / \:::\/:::/ / \/____/ \:::\ \:::\/:::/ / \/____/ \:::\/:::/ / \:::\ \:::\ \ \::::::/ / \::::::/ / \:::\ \::::::/ / \::::::/ / \:::\ \:::\____\ \::::/ / \::::/____/ \:::\ \::::/ / \::::/ / \:::\ /:::/ / /:::/ / \:::\ \ \:::\ /:::/ / /:::/ / \:::\/:::/ / /:::/ / \:::\ \ \:::\/:::/ / /:::/ / \::::::/ / /:::/ / \:::\ \ \::::::/ / /:::/ / \::::/ / /:::/ / \:::\____\ \::::/ / /:::/ / \::/ / \::/ / \::/ / \::/____/ \::/ / \/____/ \/____/ \/____/ ~~ \/____/ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /::\ \ /::\____\ /::\ \ /::\____\ /::::\ \ /:::/ / /::::\ \ /::::| | /::::::\ \ /:::/ / /::::::\ \ /:::::| | /:::/\:::\ \ /:::/ / /:::/\:::\ \ /::::::| | /:::/__\:::\ \ /:::/ / /:::/__\:::\ \ /:::/|::| | /::::\ \:::\ \ /:::/ / /::::\ \:::\ \ /:::/ |::| | /::::::\ \:::\ \ /:::/ / _____ /::::::\ \:::\ \ /:::/ |::| | _____ /:::/\:::\ \:::\ ___\ /:::/____/ /\ \ /:::/\:::\ \:::\____\ /:::/ |::| |/\ \ /:::/__\:::\ \:::| ||:::| / /::\____\/:::/ \:::\ \:::| |/:: / |::| /::\____\ \:::\ \:::\ /:::|____||:::|____\ /:::/ /\::/ |::::\ /:::|____|\::/ /|::| /:::/ / \:::\ \:::\/:::/ / \:::\ \ /:::/ / \/____|:::::\/:::/ / \/____/ |::| /:::/ / \:::\ \::::::/ / \:::\ \ /:::/ / |:::::::::/ / |::|/:::/ / \:::\ \::::/ / \:::\ /:::/ / |::|\::::/ / |::::::/ / \:::\ /:::/ / \:::\__/:::/ / |::| \::/____/ |:::::/ / \:::\/:::/ / \::::::::/ / |::| ~| |::::/ / \::::::/ / \::::::/ / |::| | /:::/ / \::::/ / \::::/ / \::| | /:::/ / \::/____/ \::/____/ \:| | \::/ / ~~ ~~ \|___| \/____/ */ contract ShibaBurn is Ownable { // ShibaSwap router: ISwapper public router = ISwapper(0x03f7724180AA6b939894B5Ca4314783B0b36b329); // Ledgendary burn address that holds tokens burnt of the SHIB ecosystem: address public burnAddress = 0xdEAD000000000000000042069420694206942069; address public wethAddress; // Addresses of SHIB ecosystem tokens: address public shibAddress = 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE; address public boneAddress = 0x9813037ee2218799597d83D4a5B6F3b6778218d9; address public leashAddress = 0x27C70Cd1946795B66be9d954418546998b546634; address public ryoshiAddress = 0x777E2ae845272a2F540ebf6a3D03734A5a8f618e; event Burn(address sender, uint256 time, address tokenAddress, uint256 poolIndex, uint256 amount); bool locked; modifier noReentrancy() { require(!locked,"Reentrant call"); locked = true; _; locked = false; } ////////////// // BURN POOLS: ////////////// // // xTokens[tokenAddress][poolIndex] // => address of pool's xToken mapping(address => mapping(uint256 => address)) public xTokens; // totalBurnt[tokenAddress][poolIndex] // => total amount burnt for specified pool mapping(address => mapping(uint256 => uint256)) public totalBurnt; // totalTrackedBurners[tokenAddress][poolIndex] // => total number of burners that have exceeded the trackBurnerIndexThreshold mapping(address => mapping(uint256 => uint256)) public totalTrackedBurners; // trackBurnerIndexThreshold[tokenAddress][poolIndex] // => the burn threshold required to track user burn indexes of a specific pool mapping(address => mapping(uint256 => uint256)) public trackBurnerIndexThreshold; // burnerIndex[tokenAddress][poolIndex][userAddress] // => the index at which a user exceeded the trackBurnerIndexThreshold for a specific pool mapping(address => mapping(uint256 => mapping(address => uint256))) public burnerIndex; // burnerIndex[tokenAddress][poolIndex][burnerIndex] // => the address of the a specified tracked burner at a specified index mapping(address => mapping(uint256 => mapping(uint256 => address))) public burnersByIndex; // amountBurnt[tokenAddress][poolIndex][userAddress] // => amount burnt by a specific user for a specified pool mapping(address => mapping(uint256 => mapping(address => uint256))) public amountBurnt; constructor(address _wethAddress) Ownable() { wethAddress = _wethAddress; } /** * @notice Intended to be used for web3 interface, such that all data can be pulled at once * @param tokenAddress The address of the token for which the query will be made * @param currentUser The address used to query user-based pool info and ethereum balance * @return burnPool info for the default pool (0) of the specified token */ function getInfo(address currentUser, address tokenAddress) external view returns (uint256[] memory) { return getInfoForPool(0, currentUser, tokenAddress); } /** * @notice Intended to be used for web3 interface, such that all data can be pulled at once * @param poolIndex The index of which token-specific burn pool to be used * @param tokenAddress The address of the token for which the query will be made * @param currentUser The address used to query user-based pool info and ethereum balance * * @return burnPool info for the specified pool of the specified token as an array of 11 integers indicating the following: * (0) Number of decimals of the token associated with the tokenAddress * (1) Total amount burnt for the specified burn-pool * (2) Total amount burnt by the specified currentUser for the specified burn-pool * (3) The amount of specified tokens in possession by the specified currentUser * (4) The amount of eth in the wallet of the specified currentUser * (5) The amount of specified tokens allowed to be burnt by this contract * (6) The threshold of tokens needed to be burnt to track the index of a user for the specified pool (if zero, no indexes will be tracked) * (7) Burn index of the current user with regards to a specified pool (only tracked if admin configured, and burn meets threshold requirements) * (8) Total number of burners above the specified threshold for the specific pool * (9) Decimal integer representation of the address of the 'xToken' of the specified pool * (10) Total supply of the xToken associated with the specified pool * (11) Specified pool's xToken balance of currentUser */ function getInfoForPool(uint256 poolIndex, address currentUser, address tokenAddress) public view returns (uint256[] memory) { uint256[] memory info = new uint256[](12); IERC20Metadata token = IERC20Metadata(tokenAddress); info[0] = token.decimals(); info[1] = totalBurnt[tokenAddress][poolIndex]; info[2] = amountBurnt[tokenAddress][poolIndex][currentUser]; info[3] = token.balanceOf(currentUser); info[4] = currentUser.balance; info[5] = token.allowance(currentUser, address(this)); if (trackBurnerIndexThreshold[tokenAddress][poolIndex] != 0) { info[6] = trackBurnerIndexThreshold[tokenAddress][poolIndex]; info[7] = burnerIndex[tokenAddress][poolIndex][currentUser]; info[8] = totalTrackedBurners[tokenAddress][poolIndex]; } if (xTokens[tokenAddress][poolIndex] != address(0)) { IERC20Metadata xToken = IERC20Metadata(xTokens[tokenAddress][poolIndex]); info[9] = uint256(uint160(address(xToken))); info[10] = xToken.totalSupply(); info[11] = xToken.balanceOf(currentUser); } return info; } /** * @notice Intended to be used for web3 such that all necessary data can be requested at once * @param tokenAddress The address of the token to buy on shibaswap. * @return Name and Symbol metadata of specified ERC20 token. */ function getTokenInfo(address tokenAddress) external view returns (string[] memory) { string[] memory info = new string[](2); IERC20Metadata token = IERC20Metadata(tokenAddress); info[0] = token.name(); info[1] = token.symbol(); return info; } /** * @param tokenAddress The address of the token to buy on shibaswap. * @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks) * * @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx for the * "default" burn pool for the specified token. Based on the admin configuration of each pool, * xTokens may be issued, and/or the burner's index will be tracked. */ function buyAndBurn(address tokenAddress, uint256 minOut) external payable { buyAndBurnForPool(tokenAddress, minOut, 0); } /** * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param threshold the minimum amount of tokens required to be burnt for the burner's index to be tracked * * @dev This can only be set on pools with no burns * @notice Allows the admin address to mark a specific pool as tracking "indexes" of burns above a specific threshold. * This allows for projects to reward users based on how early they burned more than the specified amount. * Setting this threshold will cause each burn to require more gas. */ function trackIndexesForPool(address tokenAddress, uint256 poolIndex, uint256 threshold) public onlyOwner { require (totalBurnt[tokenAddress][poolIndex] == 0, "tracking indexes can only be turned on for pools with no burns"); trackBurnerIndexThreshold[tokenAddress][poolIndex] = threshold; } /** * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param xTokenAddress the address of the xToken that will be minted in exchange for burning * * @notice Allows the admin address to set an xToken address for a specific pool. * @dev It is required for this contract to have permission to mint the xToken */ function setXTokenForPool(address tokenAddress, uint256 poolIndex, address xTokenAddress) public onlyOwner { require (totalBurnt[tokenAddress][poolIndex] == 0, "xToken can only be set on pools with no burns"); xTokens[tokenAddress][poolIndex] = xTokenAddress; } /** * @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx. * Based on the admin configuration of each pool, xTokens may be issued, * and the burner's index will be tracked. * * @dev uses hard coded shibaswap router address * * @param tokenAddress The address of the token to buy on shibaswap. * @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks) * @param poolIndex the index of which token-specific burn pool to be used * */ function buyAndBurnForPool(address tokenAddress, uint256 minOut, uint256 poolIndex) public payable noReentrancy { address[] memory ethPath = new address[](2); ethPath[0] = wethAddress; // WETH ethPath[1] = tokenAddress; IERC20Metadata token = IERC20Metadata(tokenAddress); uint256 balanceWas = token.balanceOf(burnAddress); router.swapExactETHForTokens{ value: msg.value }(minOut, ethPath, burnAddress, block.timestamp + 1000); uint256 amount = token.balanceOf(burnAddress) - balanceWas; _increaseOwnership(tokenAddress, poolIndex, amount); } /** * @dev internal method * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param amount the amount of tokens intended to be burnt * * @return boolean value which indicates whether or not the burner's burn index should be tracked for the current transaction. */ function shouldTrackIndex(address tokenAddress, uint256 poolIndex, uint256 amount) internal returns (bool) { uint256 threshold = trackBurnerIndexThreshold[tokenAddress][poolIndex]; uint256 alreadyBurnt = amountBurnt[tokenAddress][poolIndex][msg.sender]; return threshold != 0 && alreadyBurnt < threshold && alreadyBurnt + amount >= threshold; } /** * @notice increases ownership of specified pool. * @dev tracks the user's burn Index if configured * @dev mints xTokens for the user if configured * @dev internal method * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param amount of tokens intended to be burnt * */ function _increaseOwnership(address tokenAddress, uint256 poolIndex, uint256 amount) internal { if (shouldTrackIndex(tokenAddress, poolIndex, amount)) { burnerIndex[tokenAddress][poolIndex][msg.sender] = totalTrackedBurners[tokenAddress][poolIndex]; burnersByIndex[tokenAddress][poolIndex][totalTrackedBurners[tokenAddress][poolIndex]] = msg.sender; totalTrackedBurners[tokenAddress][poolIndex] += 1; } if (xTokens[tokenAddress][poolIndex] != address(0)) XToken(xTokens[tokenAddress][poolIndex]).mint(msg.sender, amount); amountBurnt[tokenAddress][poolIndex][msg.sender] = amountBurnt[tokenAddress][poolIndex][msg.sender] + amount; totalBurnt[tokenAddress][poolIndex] += amount; emit Burn(msg.sender, block.timestamp, tokenAddress, poolIndex, amount); } /** * @notice Burns SHIB to the default SHIB pool * @param amount the amount of SHIB to be burnt */ function burnShib(uint256 amount) external { burnToken(shibAddress, amount); } /** * @notice Burns RYOSHI to the default RYOSHI pool * @param amount the amount of RYOSHI to be burnt */ function burnRyoshi(uint256 amount) external { burnToken(ryoshiAddress, amount); } /** * @notice Burns LEASH to the default LEASH pool * @param amount the amount of LEASH to be burnt * */ function burnLeash(uint256 amount) external { burnToken(leashAddress, amount); } /** * @notice Burns BONE to the default BONE pool * @param amount the amount of BONE to be burnt * */ function burnBone(uint256 amount) external { burnToken(boneAddress, amount); } /** * @notice Burns any token to the default (0) pool for that token * @param tokenAddress the address of the token intended to be burnt * @param amount the amount of tokens to be burnt * */ function burnToken(address tokenAddress, uint256 amount) public { burnTokenForPool(tokenAddress, 0, amount); } /** * @notice Burns any token to the specified pool for that token * @param tokenAddress the address of the token intended to be burnt * @param poolIndex the index of which token-specific burn pool to be used * @param amount the amount of tokens to be burnt * */ function burnTokenForPool(address tokenAddress, uint256 poolIndex, uint256 amount) public noReentrancy { IERC20Metadata token = IERC20Metadata(tokenAddress); require (token.balanceOf(msg.sender) >= amount, "insufficient token balance"); token.transferFrom(msg.sender, burnAddress, amount); _increaseOwnership(tokenAddress, poolIndex, amount); } }
amountBurnt[tokenAddress][poolIndex][userAddress] => amount burnt by a specific user for a specified pool
mapping(address => mapping(uint256 => mapping(address => uint256))) public amountBurnt;
12,569,944
[ 1, 8949, 38, 321, 88, 63, 2316, 1887, 6362, 6011, 1016, 6362, 1355, 1887, 65, 282, 516, 3844, 18305, 88, 635, 279, 2923, 729, 364, 279, 1269, 2845, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 20349, 1071, 3844, 38, 321, 88, 31, 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 ]
./full_match/4/0x3f3c3A2AF4d27Ee5cbF6c91ea734Fb5BDD571764/sources/test.sol
_mintBatch(msg.sender, [1,2,3,4],[1,1,1,1],"");
contract NFT is ERC1155 { using SafeMath for uint256; _mint(msg.sender, 1,1,""); _mint(msg.sender, 2,1,""); _mint(msg.sender, 3,1,""); _mint(msg.sender, 4,1,""); _mint(msg.sender, 5,1,""); _mint(msg.sender, 6,1,""); _mint(msg.sender, 7,1,""); _mint(msg.sender, 8,1,""); _mint(msg.sender, 9,1,""); _mint(msg.sender, 10,1,""); }
12,276,632
[ 1, 67, 81, 474, 4497, 12, 3576, 18, 15330, 16, 306, 21, 16, 22, 16, 23, 16, 24, 6487, 63, 21, 16, 21, 16, 21, 16, 21, 6487, 3660, 1769, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 6835, 423, 4464, 353, 4232, 39, 2499, 2539, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 7010, 377, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 576, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 890, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1059, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1381, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1666, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2371, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1725, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2468, 16, 21, 16, 3660, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 1728, 16, 21, 16, 3660, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.7.6; pragma abicoder v2; import "./interfaces/IMetadataPointer.sol"; /** * @notice The Gitcoin GrantRegistry contract keeps track of all grants that have been created. * It is designed to be a singleton, i.e. there is only one instance of a GrantRegistry which * tracks all grants. It behaves as follows: * - Anyone can create a grant by calling `createGrant` * - A grant's `owner` can edit their grant using the `updateGrant` family of method * - The `getAllGrants` and `getGrants` view methods are used to fetch grant data */ contract GrantRegistry { // --- Data --- /// @notice Number of grants stored in this registry uint96 public grantCount; /// @notice Grant object struct Grant { // Slot 1 (within this struct) // Using a uint96 for the grant ID means a max of 2^96-1 = 7.9e28 grants uint96 id; // grant ID, as address owner; // grant owner (has permissions to modify grant information) // Slot 2 // Using uint48 for timestamps means a maximum timestamp of 2^48-1 = 281474976710655 = year 8.9 million uint48 createdAt; // timestamp the grant was created, uint48 uint48 lastUpdated; // timestamp the grant data was last updated in this registry address payee; // address that receives funds donated to this grant // Slots 3+ MetaPtr metaPtr; // metadata pointer } /// @notice Mapping from Grant ID to grant data mapping(uint96 => Grant) public grants; // --- Events --- /// @notice Emitted when a new grant is created event GrantCreated( uint96 indexed id, address indexed owner, address indexed payee, MetaPtr metaPtr, uint256 time ); /// @notice Emitted when a grant's owner is changed event GrantUpdated( uint96 indexed id, address indexed owner, address indexed payee, MetaPtr metaPtr, uint256 time ); // --- Core methods --- /** * @notice Create a new grant in the registry * @param _owner Grant owner (has permissions to modify grant information) * @param _payee Address that receives funds donated to this grant * @param _metaPtr metadata pointer */ function createGrant( address _owner, address _payee, MetaPtr calldata _metaPtr ) external { uint96 _id = grantCount; grants[_id] = Grant( _id, _owner, uint48(block.timestamp), uint48(block.timestamp), _payee, _metaPtr ); emit GrantCreated(_id, _owner, _payee, _metaPtr, block.timestamp); grantCount += 1; } /** * @notice Update the owner of a grant * @param _id ID of grant to update * @param _owner New owner address */ function updateGrantOwner(uint96 _id, address _owner) external { Grant storage grant = grants[_id]; require(msg.sender == grant.owner, "GrantRegistry: Not authorized"); grant.owner = _owner; grant.lastUpdated = uint48(block.timestamp); emit GrantUpdated( grant.id, grant.owner, grant.payee, grant.metaPtr, block.timestamp ); } /** * @notice Update the payee of a grant * @param _id ID of grant to update * @param _payee New payee address */ function updateGrantPayee(uint96 _id, address _payee) external { Grant storage grant = grants[_id]; require(msg.sender == grant.owner, "GrantRegistry: Not authorized"); grant.payee = _payee; grant.lastUpdated = uint48(block.timestamp); emit GrantUpdated( grant.id, grant.owner, grant.payee, grant.metaPtr, block.timestamp ); } /** * @notice Update the metadata pointer of a grant * @param _id ID of grant to update * @param _metaPtr New URL that points to grant metadata */ function updateGrantMetaPtr(uint96 _id, MetaPtr calldata _metaPtr) external { Grant storage grant = grants[_id]; require(msg.sender == grant.owner, "GrantRegistry: Not authorized"); grant.metaPtr = _metaPtr; grant.lastUpdated = uint48(block.timestamp); emit GrantUpdated( grant.id, grant.owner, grant.payee, grant.metaPtr, block.timestamp ); } /** * @notice Update multiple fields of a grant at once * @dev To leave a field unchanged, you must pass in the same value as the current value * @param _id ID of grant to update * @param _owner New owner address * @param _payee New payee address * @param _metaPtr New URL that points to grant metadata */ function updateGrant( uint96 _id, address _owner, address _payee, MetaPtr calldata _metaPtr ) external { Grant memory _grant = grants[_id]; require(msg.sender == _grant.owner, "GrantRegistry: Not authorized"); grants[_id] = Grant( _id, _owner, _grant.createdAt, uint48(block.timestamp), _payee, _metaPtr ); emit GrantUpdated(_id, _owner, _payee, _metaPtr, block.timestamp); } // --- View functions --- /** * @notice Returns an array of all grants and their on-chain data * @dev May run out of gas for large values `grantCount`, depending on the node's RpcGasLimit. In these cases, * `getGrants` can be used to fetch a subset of grants and aggregate the results of various calls off-chain */ function getAllGrants() external view returns (Grant[] memory) { return getGrants(0, grantCount); } /** * @notice Returns a range of grants and their on-chain data * @param _startId Grant ID of first grant to return, inclusive, i.e. this grant ID is included in return data * @param _endId Grant ID of last grant to return, exclusive, i.e. this grant ID is NOT included in return data */ function getGrants(uint96 _startId, uint96 _endId) public view returns (Grant[] memory) { require( _endId <= grantCount, "GrantRegistry: _endId must be <= grantCount" ); require(_startId <= _endId, "GrantRegistry: Invalid ID range"); Grant[] memory grantList = new Grant[](_endId - _startId); for (uint96 i = _startId; i < _endId; i++) { grantList[i - _startId] = grants[i]; // use index of `i - _startId` so index starts at zero } return grantList; } /** * @notice Returns the address that will be used to pay out donations for a given grant * @dev The payee may be set to null address * @param _id Grant ID used to retrieve the payee address in the registry */ function getGrantPayee(uint96 _id) public view returns (address) { require(_id < grantCount, "GrantRegistry: Grant does not exist"); return grants[_id].payee; } }
timestamp the grant data was last updated in this registry
uint48 lastUpdated;
5,461,786
[ 1, 5508, 326, 7936, 501, 1703, 1142, 3526, 316, 333, 4023, 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, 3639, 2254, 8875, 1142, 7381, 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 ]
pragma solidity ^0.6.0; /** * @title OrderedSet * @dev Data structure. It has the properties of a mapping for addresses, but members are ordered * and can be enumerated. Items can be inserted only at the head or the tail, but can be removed * from anywhere. Append, prepend, remove and contains are O(1). Length and enumerate O(N). InsertAfter * and insertBefore could be implemented at O(1). * @author Alberto Cuesta Cañada */ library OrderedSet { event ItemInserted(address prev, address inserted, address next); event ItemRemoved(address removed); struct Set { mapping (address => address) next; mapping (address => address) prev; } /** * @dev Insert an item as the new tail. */ function append(Set storage set, address item) internal { _insert( set, tail(set), item, address(0) ); } /** * @dev Insert an item as the new head. */ function prepend(Set storage set, address item) internal { _insert( set, address(0), item, head(set) ); } /** * @dev Remove an item. */ function remove(Set storage set, address item) internal { require( item != address(0), "OrderedSet: Cannot remove the empty address" ); require( contains(set, item) == true, "OrderedSet: Cannot remove a non existing item" ); set.next[set.prev[item]] = set.next[item]; set.prev[set.next[item]] = set.prev[item]; delete set.next[item]; delete set.prev[item]; emit ItemRemoved(item); } /** * @dev Returns the Head. */ function head(Set storage set) internal view returns (address) { return set.next[address(0)]; } /** * @dev Returns the Tail. */ function tail(Set storage set) internal view returns (address) { return set.prev[address(0)]; } /** * @dev Returns true if the item is in the set. */ function contains(Set storage set, address item) internal view returns (bool) { return head(set) == item || set.next[item] != address(0) || set.prev[item] != address(0); } /** * @dev Return the number of items in the set. */ function length(Set storage set) internal view returns (uint256) { uint256 count = 0; address item = head(set); while (item != address(0)) { count += 1; item = set.next[item]; } return count; } /** * @dev Return an array with all items in the set, from Head to Tail. */ function enumerate(Set storage set) internal view returns (address[] memory) { address[] memory items = new address[](length(set)); uint256 count = 0; address item = head(set); while (item != address(0)) { items[count] = item; count += 1; item = set.next[item]; } return items; } /** * @dev Insert an item between another two.. */ function _insert( Set storage set, address prev_, address item, address next_ ) private { require( item != address(0), "OrderedSet: Cannot insert the empty address" ); require( contains(set, item) == false, "OrderedSet: Cannot insert an existing item" ); set.next[prev_] = item; set.next[item] = next_; set.prev[next_] = item; set.prev[item] = prev_; emit ItemInserted(prev_, item, next_); } }
* @dev Insert an item as the new tail./
function append(Set storage set, address item) internal { _insert( set, tail(set), item, address(0) ); }
1,027,536
[ 1, 4600, 392, 761, 487, 326, 394, 5798, 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 ]
[ 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, 714, 12, 694, 2502, 444, 16, 1758, 761, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 389, 6387, 12, 203, 5411, 444, 16, 203, 5411, 5798, 12, 542, 3631, 203, 5411, 761, 16, 203, 5411, 1758, 12, 20, 13, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
@dev Reads the bytes7 at `rdPtr` in returndata.
function readBytes7( ReturndataPointer rdPtr ) internal pure returns (bytes7 value) { assembly ("memory-safe") { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
8,451,816
[ 1, 7483, 326, 1731, 27, 622, 1375, 13623, 5263, 68, 316, 327, 892, 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 ]
[ 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, 25825, 27, 12, 203, 3639, 2000, 892, 4926, 9437, 5263, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 27, 460, 13, 288, 203, 3639, 19931, 7566, 7858, 17, 4626, 7923, 288, 203, 5411, 327, 892, 3530, 12, 20, 16, 9437, 5263, 16, 389, 3335, 3944, 13, 203, 5411, 460, 519, 312, 945, 12, 20, 13, 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, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "../../liquidate/external/IUniswapV2Router02.sol"; import "../InvestmentVehicleSingleAssetBaseV1Upgradeable.sol"; import "./interface/IYearnVaultV2.sol"; /** YearnV2VaultV1Base is the IV implementation that targets Yearn V2 vaults. It takes the base asset and deposits into the external Yearn vaults */ contract YearnV2VaultV1Base is InvestmentVehicleSingleAssetBaseV1Upgradeable { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; address public yearnVault; uint256 YEARN_SHARE_UNIT; /// initialize the iv with yearn external yearn vault and its respective base asset /// @param _store the address of system storage /// @param _baseAsset the address of base asset /// @param _yVault the address of the external yearn vault function initialize( address _store, address _baseAsset, address _yVault ) public initializer { super.initialize(_store, _baseAsset); yearnVault = _yVault; YEARN_SHARE_UNIT = 10 ** (IYearnVaultV2(yearnVault).decimals()); } /// calculates the respective yearn vault shares from base asset /// @param baseAssetAmount the amount of base asset provided /// @return the amount of respective yearn vault shares function baseAssetToYVaultShares(uint256 baseAssetAmount) public view returns(uint256) { return baseAssetAmount .mul(YEARN_SHARE_UNIT) .div(IYearnVaultV2(yearnVault).pricePerShare()); } /// calculates the respective base asset amount from yearn vault shares /// @param shares the amount of yearn vault shares /// @return the amount of respective base asset function yVaultSharesToBaseAsset(uint256 shares) public view returns(uint256) { return shares .mul(IYearnVaultV2(yearnVault).pricePerShare()) .div(YEARN_SHARE_UNIT); } function _investAll() internal override { uint256 baseAssetAmountInVehicle = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if(baseAssetAmountInVehicle > 0){ // Approve yearn vault IERC20Upgradeable(baseAsset).safeApprove(yearnVault, 0); IERC20Upgradeable(baseAsset).safeApprove(yearnVault, baseAssetAmountInVehicle); // Deposit to yearn vault IYearnVaultV2(yearnVault).deposit(baseAssetAmountInVehicle); } } /** Interacting with underlying investment opportunities */ function _pullFundsFromInvestment(uint256 _baseAmount) internal override{ uint256 respectiveShare = baseAssetToYVaultShares(_baseAmount); uint256 ownedShare = IYearnVaultV2(yearnVault).balanceOf(address(this)); uint256 withdrawingShare = MathUpgradeable.min(ownedShare, respectiveShare); IYearnVaultV2(yearnVault).withdraw(withdrawingShare); } function _collectProfitAsBaseAsset() internal override returns (uint256) { return profitsPending(); } /** View functions */ /// exposes the amount of yearn vault shares owned by this IV /// @return totalShares the yearn vault shares that is owned by this IV function totalYearnVaultShares() public view returns (uint256 totalShares) { totalShares = IERC20Upgradeable(yearnVault).balanceOf(address(this)); } /// calculates the amount of base asset that is deposited into yearn vault /// @return amount of base asset in yearn vault function invested() public view override returns (uint256){ return yVaultSharesToBaseAsset(totalYearnVaultShares()); } /// calculates the amount of profit that has not been accounted in the system /// this is useful for the operators to determine whether it is time to call /// `collectProfitAndDistribute` or not. /// @return the amount of profit that has not been accounted yet function profitsPending() public view override returns (uint256) { uint256 ivBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); uint256 yvaultBalance = invested(); uint256 totalBalance = ivBalance.add(yvaultBalance); uint256 profit = totalBalance.sub(totalDebt()); return profit; } } // 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 pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.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 SafeMathUpgradeable for uint256; 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' // 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(IERC20Upgradeable 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(IERC20Upgradeable 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(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 // 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 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/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 { 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: MIT 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 SafeMathUpgradeable { /** * @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.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @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); } } pragma solidity 0.7.6; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); 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 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; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "../inheritance/StorageV1ConsumerUpgradeable.sol"; import "../interface/IDebtor.sol"; import "../interface/ICreditor.sol"; import "../interface/IInsuranceProvider.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; /** InvestmentVehicleSingleAssetBaseV1Upgradeable is the base contract for single asset IVs. It will receive only one kind of asset and invest into an investment opportunity. Every once in a while, operators should call the `collectProfitAndDistribute` to perform accounting for relevant parties. Apart from the usual governance and operators, there are two roles for an IV: * "creditors" who lend their asset * "beneficiaries" who provide other services. (e.g. insurance, operations, tranches, boosts) Interest are accrued to their contribution respectively. Creditors gets their interest with respect to their lending amount, whereas the governance will set the ratio that is distributed to beneficiaries. */ abstract contract InvestmentVehicleSingleAssetBaseV1Upgradeable is StorageV1ConsumerUpgradeable, IDebtor { using MathUpgradeable for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; uint256 public constant RATIO_DENOMINATOR = 10000; uint256 public constant ASSET_ID_BASE = 0; uint256 public constant SHARE_UNIT = 10 ** 18; // profit sharing roles (beneficiaries) uint256 constant ROLE_OPERATIONS = 0; uint256 constant ROLE_INSURER = 1; address public baseAsset; // shares uint256 public totalShares; uint256 public sharePrice; mapping(address => uint256) public shareBalance; struct ProfitShareInfo { uint256 ratio; // only used by PSCAT_PROTOCOL uint256 profit; // only used by PSCAT_PROTOCOL uint256 role; } event DividendClaimed(address _who, uint256 amount); event BeneficiaryAdded(address _target, uint256 _psRatio, uint256 _psRole); event BeneficiaryRemoved(address _target); event VaultRemoved(address _target); event CreditorWithdrawn(address _creditor, uint256 _baseAssetRequested, uint256 _baseAssetTransferred); event CreditorInvested(address _creditor, uint256 _baseAssetInvested, uint256 shareMinted); event OpsInvestmentPulled(uint256 _amount); event OpsInvestAll(); event OpsCollectProfit(uint256 baseAssetProfit); event InsuranceClaimFiled(uint256 filedAmount); mapping(address => ProfitShareInfo) public psInfo; EnumerableSetUpgradeable.AddressSet psList; /// Whitelist the vaults/ creditors for depositing funds into the IV. mapping(address => bool) public activeCreditor; address[] public profitAssets; mapping(address => uint256) public profitAssetHeld; modifier onlyBeneficiary() { require(isBeneficiary(msg.sender) ,"IVSABU: msg.sender is not a beneficiary"); _; } modifier onlyCreditor() { require(activeCreditor[msg.sender] || msg.sender == treasury() || msg.sender == governance() ,"IVSABU: msg.sender is not a creditor"); _; } function initialize(address _store, address _baseAsset) public virtual initializer { require(profitAssets.length == 0, "IVSABU: profitToken should be empty"); super.initialize(_store); baseAsset = _baseAsset; profitAssets.push(baseAsset); // when initializing the strategy, all profit is allocated to the creditors require(profitAssets[ASSET_ID_BASE] == baseAsset, "IVSABU: Base asset id should be predefined constant"); sharePrice = SHARE_UNIT; //set initial sharePrice } /// Check if a target is a beneficiary (profit share). /// @param _address target address /// @return Return true if the address is a beneficiary. function isBeneficiary( address _address ) public view returns (bool) { return psList.contains(_address); } /// Add a creditor (typically a vault) to whitelist. /// @param _target Address of the creditor. function addCreditor( address _target ) public adminPriviledged { activeCreditor[_target] = true; } /// Claim the dividend. function claimDividendAsBeneficiary() external returns(uint256) { return _claimDividendForBeneficiary(msg.sender); } /// Claim the dividend for a beneficiary. /// @param _who Address of the beneficiary. function claimDividendForBeneficiary(address _who) external opsPriviledged returns(uint256) { return _claimDividendForBeneficiary(_who); } function _claimDividendForBeneficiary(address _who) internal returns(uint256) { ProfitShareInfo storage info = psInfo[_who]; uint256 profit = info.profit; require(profit > 0, "Must have non-zero dividend."); uint256 inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (inVehicleBalance < profit) { _pullFundsFromInvestment(profit.sub(inVehicleBalance)); inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); profit = MathUpgradeable.min(profit, inVehicleBalance); } IERC20Upgradeable(baseAsset).safeTransfer(_who, profit); info.profit = (info.profit).sub(profit); emit DividendClaimed(_who, profit); return profit; } /// Remove the target address from the whitelist for further depositing funds into IV. /// The target address can still withdraw the deposited funds. /// @param _target Vault address. function removeVault( address _target ) public adminPriviledged { activeCreditor[_target] = false; emit VaultRemoved(_target); } /// Adds a beneficiary to the Investment Vehicle. /// A beneficiary is a party that benefits the Investment Vehicle, thus /// should gain something in return. /// @param _target Address of the new beneficiary /// @param _psRatio Profit sharing ratio designated to the beneficiary /// @param _psRole an identifier for different roles in the protocol function addBeneficiary( address _target, uint256 _psRatio, uint256 _psRole ) public adminPriviledged { require( !isBeneficiary(_target), "IVSABU: target already is a beneficiary" ); psInfo[_target] = ProfitShareInfo({ ratio: _psRatio, profit: 0, role: _psRole }); emit BeneficiaryAdded(_target, _psRatio, _psRole); psList.add(_target); } /// Remove the target address from the beneciary list. /// The target address will no longer receive dividend. /// However, the target address can still claim the existing dividend. /// @param _target Address of the beneficiary that is being removed. function removeBeneficiary( address _target ) public adminPriviledged { require( isBeneficiary(_target), "IVSABU: target is not a beneficiary" ); emit BeneficiaryRemoved(_target); psList.remove(_target); } /// Returns the length of the profit sharing list function psListLength() public view returns (uint256) { return psList.length(); } /** Interacting with creditors */ /// Creditor withdraws funds. /// If _baseAssetRequested is less than the asset that the vehicle can provide, /// it will withraw as much as possible. /// @param _baseAssetRequested the amount of base asset requested by the creditor /// @return The actual amount that the IV has sent back. function withdrawAsCreditor( uint256 _baseAssetRequested ) external override returns (uint256) { address _creditor = msg.sender; uint256 balance = baseAssetBalanceOf(_creditor); require( balance > 0, "IVSABU: Creditor has no balance." ); // check if the creditor has enough funds. require( _baseAssetRequested <= balance, "IVSABU: Cannot request more than debt." ); uint256 inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf(address(this)); if (inVehicleBalance < _baseAssetRequested) { _pullFundsFromInvestment(_baseAssetRequested.sub(inVehicleBalance)); } // _pullFundsFromInvestment is not guaranteed to pull the asked amount. // (See the function description for more details) // Therefore, we need to check the baseAsset balance again, /// and determine the amount to transfer. inVehicleBalance = IERC20Upgradeable(baseAsset).balanceOf( address(this) ); uint256 balanceToTransfer = MathUpgradeable.min(_baseAssetRequested, inVehicleBalance); uint256 burnMe = baseAssetAsShareBalance(balanceToTransfer); shareBalance[_creditor] = shareBalance[_creditor].sub(burnMe); totalShares = totalShares.sub(burnMe); IERC20Upgradeable(baseAsset).safeTransfer( _creditor, balanceToTransfer ); emit CreditorWithdrawn(_creditor, _baseAssetRequested, balanceToTransfer); return balanceToTransfer; } /// Creditor pushing more funds into vehicle /// returns how much funds was accepted by the vehicle. /// @param _amount the amount of base asset that the creditor wants to invest. /// @return The amount that was accepted by the IV. function askToInvestAsCreditor(uint256 _amount) external onlyCreditor override returns(uint256) { address _creditor = msg.sender; IERC20Upgradeable(baseAsset).safeTransferFrom(msg.sender, address(this), _amount); uint256 mintMe = baseAssetAsShareBalance(_amount); shareBalance[_creditor] = shareBalance[_creditor].add(mintMe); totalShares = totalShares.add(mintMe); emit CreditorInvested(_creditor, _amount, mintMe); return _amount; } /** Interacting with underlying investment opportunities */ /// Operator can use this to pull funds out from investment to ease the operation /// such as moving the funds to another iv, emergency exit, etc. /// @param _amount the amount of funds that we are removing from the investment opportunity function pullFundsFromInvestment(uint256 _amount) external opsPriviledged { _pullFundsFromInvestment(_amount); emit OpsInvestmentPulled(_amount); } /// Pull the funds from the underlying investment opportunities. /// This function will do best effor to pull the requested amount of funds. /// However, the exact amount of funds pulled is not guaranteed. function _pullFundsFromInvestment(uint256 _amount) internal virtual; function investAll() public opsPriviledged virtual { _investAll(); emit OpsInvestAll(); } function _investAll() internal virtual; /// Anyone can call the function when the IV has more debt /// than funds in the investment opportunity, /// this means that it has lost money and could file for insurance. /// The function would calculate the lost amount automatically, and call /// contracts that have provided insurance. /// If the loss is negligible, the function will not call the respective contracts. function fileInsuanceClaim() public { uint256 totalBalance = invested().add(IERC20Upgradeable(baseAsset).balanceOf(address(this))); uint256 totalDebtAmount = totalDebt(); uint256 claimAmount = 0; if(totalBalance < totalDebtAmount) { claimAmount = totalDebtAmount.sub(totalBalance); } if(claimAmount < (totalDebtAmount / 10000)){ claimAmount = 0; // Calling _fileInsuranceClaimAmount with zero // claim amount will unlock the previously locked insurance vault. } emit InsuranceClaimFiled(claimAmount); // If balance < debt, lock all the insurance vaults. // Otherwise, unlock all the insurance vaults. _fileInsuranceClaimAmount(claimAmount); } // The funds are locked on the insurance provider's side // This allows the liquidity that provides insurance to potentially // maximize its capital efficiency by insuring multiple independent investment vehicles function _fileInsuranceClaimAmount(uint256 _amount) internal { for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); if (psInfo[targetAddress].role == ROLE_INSURER){ IInsuranceProvider(targetAddress).fileClaim(_amount); } } } /** Collecting profits */ /// Operators can call this to account all the profit that has accumulated /// to all the creditors and beneficiaries of the IV. /// @param minBaseProfit the minimum profit that should be accounted. function collectProfitAndDistribute(uint256 minBaseProfit) external virtual opsPriviledged { // Withdraws native interests as baseAsset and collects FARM uint256 baseProfit = _collectProfitAsBaseAsset(); require(baseProfit >= minBaseProfit, "IVSABU: profit did not achieve minBaseProfit"); emit OpsCollectProfit(baseProfit); // profit accounting for baseAsset _accountProfit(baseProfit); // invest the baseAsset back _investAll(); } function _collectProfitAsBaseAsset() internal virtual returns (uint256 baseAssetProfit); function _accountProfit(uint256 baseAssetProfit) internal { uint256 remaining = baseAssetProfit; for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); ProfitShareInfo storage targetInfo = psInfo[targetAddress]; uint256 profitToTarget = baseAssetProfit.mul(targetInfo.ratio).div(RATIO_DENOMINATOR); targetInfo.profit = targetInfo.profit.add(profitToTarget); remaining = remaining.sub(profitToTarget); } sharePrice = sharePrice.add(remaining.mul(SHARE_UNIT).div(totalShares)); } /** View functions */ function invested() public view virtual returns (uint256); /// Returns the profit that has not been accounted. /// @return The pending profit in the investment opportunity yet to be accounted. function profitsPending() public view virtual returns (uint256); /// Converts IV share to amount in base asset /// @param _shareBalance the share amount /// @return the equivalent base asset amount function shareBalanceAsBaseAsset( uint256 _shareBalance ) public view returns (uint256) { return _shareBalance.mul(sharePrice).div(SHARE_UNIT); } /// Converts base asset amount to share amount /// @param _baseAssetAmount amount in base asset /// @return the equivalent share amount function baseAssetAsShareBalance( uint256 _baseAssetAmount ) public view returns (uint256) { return _baseAssetAmount.mul(SHARE_UNIT).div(sharePrice); } /// Returns base asset amount that an address holds /// @param _address the target address, could be a creditor or beneficiary. /// @return base asset amount of the target address function baseAssetBalanceOf( address _address ) public view override returns (uint256) { return shareBalanceAsBaseAsset(shareBalance[_address]); } /// Returns the total debt of the IV. /// @return the total debt of the IV. function totalDebt() public view returns (uint256) { uint256 debt = shareBalanceAsBaseAsset(totalShares); for(uint256 i = 0 ; i < psList.length(); i++) { address targetAddress = psList.at(i); ProfitShareInfo storage targetInfo = psInfo[targetAddress]; debt = debt.add(targetInfo.profit); } return debt; } } pragma solidity 0.7.6; interface IYearnVaultV2 { function decimals () external view returns ( uint256 ); function transfer ( address receiver, uint256 amount ) external returns ( bool ); function transferFrom ( address sender, address receiver, uint256 amount ) external returns ( bool ); function approve ( address spender, uint256 amount ) external returns ( bool ); function increaseAllowance ( address spender, uint256 amount ) external returns ( bool ); function decreaseAllowance ( address spender, uint256 amount ) external returns ( bool ); function totalAssets ( ) external view returns ( uint256 ); function deposit ( ) external returns ( uint256 ); function deposit ( uint256 _amount ) external returns ( uint256 ); function deposit ( uint256 _amount, address recipient ) external returns ( uint256 ); function maxAvailableShares ( ) external view returns ( uint256 ); function withdraw ( ) external returns ( uint256 ); function withdraw ( uint256 maxShares ) external returns ( uint256 ); function withdraw ( uint256 maxShares, address recipient ) external returns ( uint256 ); function withdraw ( uint256 maxShares, address recipient, uint256 maxLoss ) external returns ( uint256 ); function pricePerShare ( ) external view returns ( uint256 ); function addStrategy ( address strategy, uint256 _debtRatio, uint256 rateLimit, uint256 _performanceFee ) external; function updateStrategyDebtRatio ( address strategy, uint256 _debtRatio ) external; function updateStrategyRateLimit ( address strategy, uint256 rateLimit ) external; function updateStrategyPerformanceFee ( address strategy, uint256 _performanceFee ) external; function migrateStrategy ( address oldVersion, address newVersion ) external; function revokeStrategy ( ) external; function revokeStrategy ( address strategy ) external; function addStrategyToQueue ( address strategy ) external; function removeStrategyFromQueue ( address strategy ) external; function debtOutstanding ( ) external view returns ( uint256 ); function debtOutstanding ( address strategy ) external view returns ( uint256 ); function creditAvailable ( ) external view returns ( uint256 ); function creditAvailable ( address strategy ) external view returns ( uint256 ); function availableDepositLimit ( ) external view returns ( uint256 ); function expectedReturn ( ) external view returns ( uint256 ); function expectedReturn ( address strategy ) external view returns ( uint256 ); function report ( uint256 gain, uint256 loss, uint256 _debtPayment ) external returns ( uint256 ); function sweep ( address _token ) external; function sweep ( address _token, uint256 amount ) external; function balanceOf ( address arg0 ) external view returns ( uint256 ); function allowance ( address arg0, address arg1 ) external view returns ( uint256 ); function totalSupply ( ) external view returns ( uint256 ); function token ( ) external view returns ( address ); function governance ( ) external view returns ( address ); function management ( ) external view returns ( address ); function guardian ( ) external view returns ( address ); function guestList ( ) external view returns ( address ); function strategies ( address arg0 ) external view returns ( uint256 _performanceFee, uint256 _activation, uint256 debtRatio, uint256 rateLimit, uint256 lastReport, uint256 totalDebt, uint256 totalGain, uint256 totalLoss ); function withdrawalQueue ( uint256 arg0 ) external view returns ( address ); function emergencyShutdown ( ) external view returns ( bool ); function depositLimit ( ) external view returns ( uint256 ); function debtRatio ( ) external view returns ( uint256 ); function totalDebt ( ) external view returns ( uint256 ); function lastReport ( ) external view returns ( uint256 ); function activation ( ) external view returns ( uint256 ); function rewards ( ) external view returns ( address ); function managementFee ( ) external view returns ( uint256 ); function performanceFee ( ) external view returns ( uint256 ); function nonces ( address arg0 ) external view returns ( uint256 ); function DOMAIN_SEPARATOR ( ) external view returns ( bytes32 ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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.6.0 <0.8.0; import "../proxy/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. */ 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 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; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../utilities/UnstructuredStorageWithTimelock.sol"; import "../StorageV1Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract StorageV1ConsumerUpgradeable is Initializable { using UnstructuredStorageWithTimelock for bytes32; // bytes32(uint256(keccak256("eip1967.proxy.storage")) - 1 bytes32 private constant _STORAGE_SLOT = 0x23bdfa8033717db08b14621917cfe422b93b161b8e3ef1c873d2197616ec0bb2; modifier onlyGovernance() { require( msg.sender == governance(), "StorageV1ConsumerUpgradeable: Only governance" ); _; } modifier adminPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin"); _; } modifier opsPriviledged() { require(msg.sender == governance() || isAdmin(msg.sender) || isOperator(msg.sender), "StorageV1ConsumerUpgradeable: not governance or admin or operator"); _; } function initialize(address _store) public virtual initializer { address curStorage = (_STORAGE_SLOT).fetchAddress(); require( curStorage == address(0), "StorageV1ConsumerUpgradeable: Initialized" ); (_STORAGE_SLOT).setAddress(_store); } function store() public view returns (address) { return (_STORAGE_SLOT).fetchAddress(); } function governance() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.governance(); } function treasury() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.treasury(); } function swapCenter() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.swapCenter(); } function registry() public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.registry(); } function storageFetchAddress(bytes32 key) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressStorage(key); } function storageFetchAddressInArray(bytes32 key, uint256 index) public view returns (address) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.addressArrayStorage(key, index); } function storageFetchUint256(bytes32 key) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256Storage(key); } function storageFetchUint256InArray(bytes32 key, uint256 index) public view returns (uint256) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.uint256ArrayStorage(key, index); } function storageFetchBool(bytes32 key) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolStorage(key); } function storageFetchBoolInArray(bytes32 key, uint256 index) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.boolArrayStorage(key, index); } function isAdmin(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isAdmin(_who); } function isOperator(address _who) public view returns (bool) { StorageV1Upgradeable storageContract = StorageV1Upgradeable(store()); return storageContract.isOperator(_who); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IDebtor { // Debtor should implement accounting at `withdrawAsCreditor()` and `askToInvestAsCreditor()` function withdrawAsCreditor(uint256 _amount) external returns (uint256); function askToInvestAsCreditor(uint256 _amount) external returns (uint256); function baseAssetBalanceOf( address _address ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICreditor { } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IInsuranceProvider { function fileClaim(uint256 amount) external; function processClaim(address iv, uint256 amountIn, uint256 minAmountOut) external; function onGoingClaim() view external returns(bool haveClaim); function removeInsuranceClient(address iv) external; function addInsuranceClient(address iv) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // 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)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** UnstructuredStorageWithTimelock is a set of functions that facilitates setting/fetching unstructured storage along with information of future updates and its timelock information. For every content storage, there are two other slots that could be calculated automatically: * Slot (The current value) * Scheduled Slot (The future value) * Scheduled Time (The future time) Note that the library does NOT enforce timelock and does NOT store the timelock information. */ library UnstructuredStorageWithTimelock { // This is used to calculate the time slot and scheduled content for different variables uint256 private constant SCHEDULED_SIGNATURE = 0x111; uint256 private constant TIMESLOT_SIGNATURE = 0xAAA; function updateAddressWithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setAddress(_slot, scheduledAddress(_slot)); } function updateUint256WithTimelock(bytes32 _slot) internal { require( scheduledTime(_slot) > block.timestamp, "Timelock has not passed" ); setUint256(_slot, scheduledUint256(_slot)); } function setAddress(bytes32 _slot, address _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchAddress(bytes32 _slot) internal view returns (address result) { assembly { result := sload(_slot) } } function scheduledAddress(bytes32 _slot) internal view returns (address result) { result = fetchAddress(scheduledContentSlot(_slot)); } function scheduledUint256(bytes32 _slot) internal view returns (uint256 result) { result = fetchUint256(scheduledContentSlot(_slot)); } function setUint256(bytes32 _slot, uint256 _target) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(_slot, _target) } } function fetchUint256(bytes32 _slot) internal view returns (uint256 result) { assembly { result := sload(_slot) } } function scheduledContentSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, SCHEDULED_SIGNATURE))) ); } function scheduledTime(bytes32 _slot) internal view returns (uint256) { return fetchUint256(scheduledTimeSlot(_slot)); } function scheduledTimeSlot(bytes32 _slot) internal pure returns (bytes32) { return bytes32( uint256(keccak256(abi.encodePacked(_slot, TIMESLOT_SIGNATURE))) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "hardhat/console.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; contract StorageV1Upgradeable is Initializable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; address public proxyAdmin; address public governance; address public _treasury; EnumerableSetUpgradeable.AddressSet admin; EnumerableSetUpgradeable.AddressSet operator; address public swapCenter; address public registry; bool public registryLocked; mapping(bytes32 => address) public addressStorage; mapping(bytes32 => address[]) public addressArrayStorage; mapping(bytes32 => uint256) public uint256Storage; mapping(bytes32 => uint256[]) public uint256ArrayStorage; mapping(bytes32 => bool) public boolStorage; mapping(bytes32 => bool[]) public boolArrayStorage; event GovernanceChanged(address oldGov, address newGov); event TreasuryChanged(address oldTreasury, address newTreasury); event AdminAdded(address newAdmin); event AdminRetired(address retiredAdmin); event OperatorAdded(address newOperator); event OperatorRetired(address oldOperator); event RegistryChanged(address oldRegistry, address newRegistry); event SwapCenterChanged(address oldSwapCenter, address newSwapCenter); event RegistryLocked(); modifier onlyGovernance() { require(msg.sender == governance, "StorageV1: not governance"); _; } modifier adminPriviledged() { require(msg.sender == governance || isAdmin(msg.sender), "StorageV1: not governance or admin"); _; } modifier registryNotLocked() { require(!registryLocked, "StorageV1: registry locked"); _; } constructor() { governance = msg.sender; } function initialize(address _governance, address _proxyAdmin) external initializer { require(_governance != address(0), "!empty"); require(_proxyAdmin != address(0), "!empty"); governance = _governance; proxyAdmin = _proxyAdmin; } function setGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "!empty"); emit GovernanceChanged(governance, _governance); governance = _governance; } function treasury() external view returns (address) { if(_treasury == address(0)) { return governance; } else { return _treasury; } } function setTreasury(address _newTreasury) external onlyGovernance { require(_newTreasury != address(0)); emit TreasuryChanged(_treasury, _newTreasury); _treasury = _newTreasury; } function setRegistry(address _registry) external onlyGovernance registryNotLocked { require(_registry != address(0), "!empty"); emit RegistryChanged(registry, _registry); registry = _registry; } function lockRegistry() external onlyGovernance { emit RegistryLocked(); registryLocked = true; // While the contract doesn't provide an unlock method // It is still possible to unlock this via Timelock, by upgrading the // implementation of the Timelock proxy. } function setSwapCenter(address _swapCenter) external onlyGovernance { emit SwapCenterChanged(swapCenter, _swapCenter); swapCenter = _swapCenter; } function setAddress(bytes32 index, address _newAddr) external onlyGovernance { addressStorage[index] = _newAddr; } function setAddressArray(bytes32 index, address[] memory _newAddrs) external onlyGovernance { addressArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, uint256 _newUint256) external onlyGovernance { uint256Storage[index] = _newUint256; } function setUint256Array(bytes32 index, uint256[] memory _newAddrs) external onlyGovernance { uint256ArrayStorage[index] = _newAddrs; } function setUint256(bytes32 index, bool _newBool) external onlyGovernance { boolStorage[index] = _newBool; } function setBoolArray(bytes32 index, bool[] memory _newBools) external onlyGovernance { boolArrayStorage[index] = _newBools; } function numOfAdmin() public view returns (uint256) { return admin.length(); } function numOfOperator() public view returns (uint256) { return operator.length(); } function getAdmin(uint256 idx) public view returns (address){ return admin.at(idx); } function getOperator(uint256 idx) public view returns (address){ return operator.at(idx); } function addAdmin(address _who) public onlyGovernance returns (bool) { emit AdminAdded(_who); return admin.add(_who); } function addOperator(address _who) public adminPriviledged returns (bool) { emit OperatorAdded(_who); return operator.add(_who); } function removeAdmin(address _who) public onlyGovernance returns (bool) { emit AdminRetired(_who); return admin.remove(_who); } function removeOperator(address _who) public adminPriviledged returns (bool) { emit OperatorRetired(_who); return operator.remove(_who); } function isAdmin(address _who) public view returns (bool) { return admin.contains(_who); } function isOperator(address _who) public view returns (bool) { return operator.contains(_who); } }
* Collecting profits */ Operators can call this to account all the profit that has accumulated to all the creditors and beneficiaries of the IV. @param minBaseProfit the minimum profit that should be accounted. Withdraws native interests as baseAsset and collects FARM profit accounting for baseAsset invest the baseAsset back
function collectProfitAndDistribute(uint256 minBaseProfit) external virtual opsPriviledged { uint256 baseProfit = _collectProfitAsBaseAsset(); require(baseProfit >= minBaseProfit, "IVSABU: profit did not achieve minBaseProfit"); emit OpsCollectProfit(baseProfit); _accountProfit(baseProfit); _investAll(); }
1,475,704
[ 1, 10808, 310, 9214, 1282, 342, 7692, 3062, 848, 745, 333, 358, 2236, 777, 326, 450, 7216, 716, 711, 24893, 358, 777, 326, 12896, 1383, 471, 27641, 74, 14463, 5646, 434, 326, 21602, 18, 225, 1131, 2171, 626, 7216, 326, 5224, 450, 7216, 716, 1410, 506, 2236, 329, 18, 3423, 9446, 87, 6448, 16513, 87, 487, 1026, 6672, 471, 30976, 478, 26120, 450, 7216, 2236, 310, 364, 1026, 6672, 2198, 395, 326, 1026, 6672, 1473, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3274, 626, 7216, 1876, 1669, 887, 12, 11890, 5034, 1131, 2171, 626, 7216, 13, 3903, 5024, 6727, 15475, 1411, 2423, 288, 203, 3639, 2254, 5034, 1026, 626, 7216, 273, 389, 14676, 626, 7216, 1463, 2171, 6672, 5621, 203, 3639, 2583, 12, 1969, 626, 7216, 1545, 1131, 2171, 626, 7216, 16, 315, 8188, 55, 2090, 57, 30, 450, 7216, 5061, 486, 20186, 537, 1131, 2171, 626, 7216, 8863, 203, 3639, 3626, 19374, 10808, 626, 7216, 12, 1969, 626, 7216, 1769, 203, 3639, 389, 4631, 626, 7216, 12, 1969, 626, 7216, 1769, 203, 203, 3639, 389, 5768, 395, 1595, 5621, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./IlluviumPoolBase.sol"; /** * @title Illuvium Core Pool * * @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool, * core pools allow staking for arbitrary periods of time up to 1 year * * @dev See IlluviumPoolBase for more details * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumCorePool is IlluviumPoolBase { /// @dev Flag indicating pool type, false means "core pool" bool public constant override isFlashPool = false; /// @dev Link to deployed IlluviumVault instance address public vault; /// @dev Used to calculate vault rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public vaultRewardsPerWeight; /// @dev Pool tokens value available in the pool; /// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool) /// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards /// while for ILV core pool it does count for such tokens as well uint256 public poolTokenReserve; /** * @dev Fired in receiveVaultRewards() * * @param _by an address that sent the rewards, always a vault * @param amount amount of tokens received */ event VaultRewardsReceived(address indexed _by, uint256 amount); /** * @dev Fired in _processVaultRewards() and dependent functions, like processRewards() * * @param _by an address which executed the function * @param _to an address which received a reward * @param amount amount of reward received */ event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in setVault() * * @param _by an address which executed the function, always a factory owner */ event VaultUpdated(address indexed _by, address _fromVal, address _toVal); /** * @dev Creates/deploys an instance of the core pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {} /** * @notice Calculates current vault rewards value available for address specified * * @dev Performs calculations based on current smart contract state only, * not taking into account any additional time/blocks which might have passed * * @param _staker an address to calculate vault rewards value for * @return pending calculated vault reward value for the given address */ function pendingVaultRewards(address _staker) public view returns (uint256 pending) { User memory user = users[_staker]; return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards; } /** * @dev Executed only by the factory owner to Set the vault * * @param _vault an address of deployed IlluviumVault instance */ function setVault(address _vault) external { // verify function is executed by the factory owner require(factory.owner() == msg.sender, "access denied"); // verify input is set require(_vault != address(0), "zero input"); // emit an event emit VaultUpdated(msg.sender, vault, _vault); // update vault address vault = _vault; } /** * @dev Executed by the vault to transfer vault rewards ILV from the vault * into the pool * * @dev This function is executed only for ILV core pools * * @param _rewardsAmount amount of ILV rewards to transfer into the pool */ function receiveVaultRewards(uint256 _rewardsAmount) external { require(msg.sender == vault, "access denied"); // return silently if there is no reward to receive if (_rewardsAmount == 0) { return; } require(usersLockingWeight > 0, "zero locking weight"); transferIlvFrom(msg.sender, address(this), _rewardsAmount); vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { poolTokenReserve += _rewardsAmount; } emit VaultRewardsReceived(msg.sender, _rewardsAmount); } /** * @notice Service function to calculate and pay pending vault and yield rewards to the sender * * @dev Internally executes similar function `_processRewards` from the parent smart contract * to calculate and pay yield rewards; adds vault rewards processing * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when "staking as a pool" (`stakeAsPool`) * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @dev _useSILV flag has a context of yield rewards only * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external override { _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract) * as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function) * @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards` * * @param _staker an address which stakes (the yield reward) * @param _amount amount to be staked (yield reward amount) */ function stakeAsPool(address _staker, uint256 _amount) external { require(factory.poolExists(msg.sender), "access denied"); _sync(); User storage user = users[_staker]; if (user.tokenAmount > 0) { _processRewards(_staker, true, false); } uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER; Deposit memory newDeposit = Deposit({ tokenAmount: _amount, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), weight: depositWeight, isYield: true }); user.tokenAmount += _amount; user.totalWeight += depositWeight; user.deposits.push(newDeposit); usersLockingWeight += depositWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool) poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (increases) pool token reserve (pool tokens value available in the pool) */ function _stake( address _staker, uint256 _amount, uint64 _lockedUntil, bool _useSILV, bool _isYield ) internal override { super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield); User storage user = users[_staker]; user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); poolTokenReserve += _amount; } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, updates vault rewards of the holder, * and updates (decreases) pool token reserve (pool tokens value available in the pool) */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal override { User storage user = users[_staker]; Deposit memory stakeDeposit = user.deposits[_depositId]; require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked"); poolTokenReserve -= _amount; super._unstake(_staker, _depositId, _amount, _useSILV); user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); } /** * @inheritdoc IlluviumPoolBase * * @dev Additionally to the parent smart contract, processes vault rewards of the holder, * and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool) */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal override returns (uint256 pendingYield) { _processVaultRewards(_staker); pendingYield = super._processRewards(_staker, _useSILV, _withUpdate); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv && !_useSILV) { poolTokenReserve += pendingYield; } } /** * @dev Used internally to process vault rewards for the staker * * @param _staker address of the user (staker) to process rewards for */ function _processVaultRewards(address _staker) private { User storage user = users[_staker]; uint256 pendingVaultClaim = pendingVaultRewards(_staker); if (pendingVaultClaim == 0) return; // read ILV token balance of the pool via standard ERC20 interface uint256 ilvBalance = IERC20(ilv).balanceOf(address(this)); require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low"); // update `poolTokenReserve` only if this is a ILV Core Pool if (poolToken == ilv) { // protects against rounding errors poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim; } user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight); // transfer fails if pool ILV balance is not enough - which is a desired behavior transferIlv(_staker, pendingVaultClaim); emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IPool.sol"; import "../interfaces/ICorePool.sol"; import "./ReentrancyGuard.sol"; import "./IlluviumPoolFactory.sol"; import "../utils/SafeERC20.sol"; import "../token/EscrowedIlluviumERC20.sol"; /** * @title Illuvium Pool Base * * @notice An abstract contract containing common logic for any pool, * be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool) * * @dev Deployment and initialization. * Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory) * Additionally, 3 token instance addresses must be defined on deployment: * - ILV token address * - sILV token address, used to mint sILV rewards * - pool token address, it can be ILV token address, ILV/ETH pair address, and others * * @dev Pool weight defines the fraction of the yield current pool receives among the other pools, * pool factory is responsible for the weight synchronization between the pools. * @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool. * Since Solidity doesn't support fractions the weight is defined by the division of * pool weight by total pools weight (sum of all registered pools within the factory) * @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900. * * @author Pedro Bergamini, reviewed by Basil Gorin */ abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard { /// @dev Data structure representing token holder using a pool struct User { // @dev Total staked amount uint256 tokenAmount; // @dev Total weight uint256 totalWeight; // @dev Auxiliary variable for yield calculation uint256 subYieldRewards; // @dev Auxiliary variable for vault rewards calculation uint256 subVaultRewards; // @dev An array of holder's deposits Deposit[] deposits; } /// @dev Token holder storage, maps token holder address to their data record mapping(address => User) public users; /// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance address public immutable override silv; /// @dev Link to the pool factory IlluviumPoolFactory instance IlluviumPoolFactory public immutable factory; /// @dev Link to the pool token instance, for example ILV or ILV/ETH pair address public immutable override poolToken; /// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH uint32 public override weight; /// @dev Block number of the last yield distribution event uint64 public override lastYieldDistribution; /// @dev Used to calculate yield rewards /// @dev This value is different from "reward per token" used in locked pool /// @dev Note: stakes are different in duration and "weight" reflects that uint256 public override yieldRewardsPerWeight; /// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking uint256 public override usersLockingWeight; /** * @dev Stake weight is proportional to deposit amount and time locked, precisely * "deposit amount wei multiplied by (fraction of the year locked plus one)" * @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1], * weight is stored multiplied by 1e6 constant, as an integer * @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6 * @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and * weight is a deposit amount multiplied by 2 * 1e6 */ uint256 internal constant WEIGHT_MULTIPLIER = 1e6; /** * @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one, * we use simplified calculation and use the following constant instead previos one */ uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER; /** * @dev Rewards per weight are stored multiplied by 1e12, as integers. */ uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12; /** * @dev Fired in _stake() and stake() * * @param _by an address which performed an operation, usually token holder * @param _from token holder address, the tokens will be returned to that address * @param amount amount of tokens staked */ event Staked(address indexed _by, address indexed _from, uint256 amount); /** * @dev Fired in _updateStakeLock() and updateStakeLock() * * @param _by an address which performed an operation * @param depositId updated deposit ID * @param lockedFrom deposit locked from value * @param lockedUntil updated deposit locked until value */ event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil); /** * @dev Fired in _unstake() and unstake() * * @param _by an address which performed an operation, usually token holder * @param _to an address which received the unstaked tokens, usually token holder * @param amount amount of tokens unstaked */ event Unstaked(address indexed _by, address indexed _to, uint256 amount); /** * @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param yieldRewardsPerWeight updated yield rewards per weight value * @param lastYieldDistribution usually, current block number */ event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution); /** * @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.) * * @param _by an address which performed an operation * @param _to an address which claimed the yield reward * @param sIlv flag indicating if reward was paid (minted) in sILV * @param amount amount of yield paid */ event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount); /** * @dev Fired in setWeight() * * @param _by an address which performed an operation, always a factory * @param _fromVal old pool weight value * @param _toVal new pool weight value */ event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal); /** * @dev Overridden in sub-contracts to construct the pool * * @param _ilv ILV ERC20 Token IlluviumERC20 address * @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address * @param _factory Pool factory IlluviumPoolFactory instance/address * @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair * @param _initBlock initial block used to calculate the rewards * note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing * @param _weight number representing a weight of the pool, actual weight fraction * is calculated as that number divided by the total pools weight and doesn't exceed one */ constructor( address _ilv, address _silv, IlluviumPoolFactory _factory, address _poolToken, uint64 _initBlock, uint32 _weight ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(address(_factory) != address(0), "ILV Pool fct address not set"); require(_poolToken != address(0), "pool token address not set"); require(_initBlock > 0, "init block not set"); require(_weight > 0, "pool weight not set"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // verify IlluviumPoolFactory instance supplied require( _factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7, "unexpected FACTORY_UID" ); // save the inputs into internal state variables silv = _silv; factory = _factory; poolToken = _poolToken; weight = _weight; // init the dependent internal state variables lastYieldDistribution = _initBlock; } /** * @notice Calculates current yield rewards value available for address specified * * @param _staker an address to calculate yield rewards value for * @return calculated yield reward value for the given address */ function pendingYieldRewards(address _staker) external view override returns (uint256) { // `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight` uint256 newYieldRewardsPerWeight; // if smart contract state was not updated recently, `yieldRewardsPerWeight` value // is outdated and we need to recalculate it in order to calculate pending rewards correctly if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) { uint256 endBlock = factory.endBlock(); uint256 multiplier = blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution; uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight(); // recalculated value for `yieldRewardsPerWeight` newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight; } else { // if smart contract state is up to date, we don't recalculate newYieldRewardsPerWeight = yieldRewardsPerWeight; } // based on the rewards per weight value, calculate pending rewards; User memory user = users[_staker]; uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards; return pending; } /** * @notice Returns total staked token balance for the given address * * @param _user an address to query balance for * @return total staked token balance */ function balanceOf(address _user) external view override returns (uint256) { // read specified user token amount and return return users[_user].tokenAmount; } /** * @notice Returns information on the given deposit for the given address * * @dev See getDepositsLength * * @param _user an address to query deposit for * @param _depositId zero-indexed deposit ID for the address specified * @return deposit info as Deposit structure */ function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) { // read deposit at specified index and return return users[_user].deposits[_depositId]; } /** * @notice Returns number of deposits for the given address. Allows iteration over deposits. * * @dev See getDeposit * * @param _user an address to query deposit length for * @return number of deposits for the given address */ function getDepositsLength(address _user) external view override returns (uint256) { // read deposits array length and return return users[_user].deposits.length; } /** * @notice Stakes specified amount of tokens for the specified amount of time, * and pays pending yield rewards if any * * @dev Requires amount to stake to be greater than zero * * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV */ function stake( uint256 _amount, uint64 _lockUntil, bool _useSILV ) external override { // delegate call to an internal function _stake(msg.sender, _amount, _lockUntil, _useSILV, false); } /** * @notice Unstakes specified amount of tokens, and pays pending yield rewards if any * * @dev Requires amount to unstake to be greater than zero * * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function unstake( uint256 _depositId, uint256 _amount, bool _useSILV ) external override { // delegate call to an internal function _unstake(msg.sender, _depositId, _amount, _useSILV); } /** * @notice Extends locking period for a given deposit * * @dev Requires new lockedUntil value to be: * higher than the current one, and * in the future, but * no more than 1 year in the future * * @param depositId updated deposit ID * @param lockedUntil updated deposit locked until value * @param useSILV used for _processRewards check if it should use ILV or sILV */ function updateStakeLock( uint256 depositId, uint64 lockedUntil, bool useSILV ) external { // sync and call processRewards _sync(); _processRewards(msg.sender, useSILV, false); // delegate call to an internal function _updateStakeLock(msg.sender, depositId, lockedUntil); } /** * @notice Service function to synchronize pool state with current time * * @dev Can be executed by anyone at any time, but has an effect only when * at least one block passes between synchronizations * @dev Executed internally when staking, unstaking, processing rewards in order * for calculations to be correct and to reflect state progress of the contract * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently */ function sync() external override { // delegate call to an internal function _sync(); } /** * @notice Service function to calculate and pay pending yield rewards to the sender * * @dev Can be executed by anyone at any time, but has an effect only when * executed by deposit holder and when at least one block passes from the * previous reward processing * @dev Executed internally when staking and unstaking, executes sync() under the hood * before making further calculations and payouts * @dev When timing conditions are not met (executed too frequently, or after factory * end block), function doesn't throw and exits silently * * @param _useSILV flag indicating whether to mint sILV token as a reward or not; * when set to true - sILV reward is minted immediately and sent to sender, * when set to false - new ILV reward deposit gets created if pool is an ILV pool * (poolToken is ILV token), or new pool deposit gets created together with sILV minted * when pool is not an ILV pool (poolToken is not an ILV token) */ function processRewards(bool _useSILV) external virtual override { // delegate call to an internal function _processRewards(msg.sender, _useSILV, true); } /** * @dev Executed by the factory to modify pool weight; the factory is expected * to keep track of the total pools weight when updating * * @dev Set weight to zero to disable the pool * * @param _weight new weight to set for the pool */ function setWeight(uint32 _weight) external override { // verify function is executed by the factory require(msg.sender == address(factory), "access denied"); // emit an event logging old and new weight values emit PoolWeightUpdated(msg.sender, weight, _weight); // set the new weight value weight = _weight; } /** * @dev Similar to public pendingYieldRewards, but performs calculations based on * current smart contract state only, not taking into account any additional * time/blocks which might have passed * * @param _staker an address to calculate yield rewards value for * @return pending calculated yield reward value for the given address */ function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) { // read user data structure into memory User memory user = users[_staker]; // and perform the calculation using the values read return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards; } /** * @dev Used internally, mostly by children implementations, see stake() * * @param _staker an address which stakes tokens and which will receive them back * @param _amount amount of tokens to stake * @param _lockUntil stake period as unix timestamp; zero means no locking * @param _useSILV a flag indicating if previous reward to be paid as sILV * @param _isYield a flag indicating if that stake is created to store yield reward * from the previously unstaked stake */ function _stake( address _staker, uint256 _amount, uint64 _lockUntil, bool _useSILV, bool _isYield ) internal virtual { // validate the inputs require(_amount > 0, "zero amount"); require( _lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days), "invalid lock interval" ); // update smart contract state _sync(); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // process current pending rewards if any if (user.tokenAmount > 0) { _processRewards(_staker, _useSILV, false); } // in most of the cases added amount `addedAmount` is simply `_amount` // however for deflationary tokens this can be different // read the current balance uint256 previousBalance = IERC20(poolToken).balanceOf(address(this)); // transfer `_amount`; note: some tokens may get burnt here transferPoolTokenFrom(address(msg.sender), address(this), _amount); // read new balance, usually this is just the difference `previousBalance - _amount` uint256 newBalance = IERC20(poolToken).balanceOf(address(this)); // calculate real amount taking into account deflation uint256 addedAmount = newBalance - previousBalance; // set the `lockFrom` and `lockUntil` taking into account that // zero value for `_lockUntil` means "no locking" and leads to zero values // for both `lockFrom` and `lockUntil` uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0; uint64 lockUntil = _lockUntil; // stake weight formula rewards for locking uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount; // makes sure stakeWeight is valid assert(stakeWeight > 0); // create and save the deposit (append it to deposits array) Deposit memory deposit = Deposit({ tokenAmount: addedAmount, weight: stakeWeight, lockedFrom: lockFrom, lockedUntil: lockUntil, isYield: _isYield }); // deposit ID is an index of the deposit in `deposits` array user.deposits.push(deposit); // update user record user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight += stakeWeight; // emit an event emit Staked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see unstake() * * @param _staker an address which unstakes tokens (which previously staked them) * @param _depositId deposit ID to unstake from, zero-indexed * @param _amount amount of tokens to unstake * @param _useSILV a flag indicating if reward to be paid as sILV */ function _unstake( address _staker, uint256 _depositId, uint256 _amount, bool _useSILV ) internal virtual { // verify an amount is set require(_amount > 0, "zero amount"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // deposit structure may get deleted, so we save isYield flag to be able to use it bool isYield = stakeDeposit.isYield; // verify available balance // if staker address ot deposit doesn't exist this check will fail as well require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake"); // update smart contract state _sync(); // and process current pending rewards if any _processRewards(_staker, _useSILV, false); // recalculate deposit weight uint256 previousWeight = stakeDeposit.weight; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount); // update the deposit, or delete it if its depleted if (stakeDeposit.tokenAmount - _amount == 0) { delete user.deposits[_depositId]; } else { stakeDeposit.tokenAmount -= _amount; stakeDeposit.weight = newWeight; } // update user record user.tokenAmount -= _amount; user.totalWeight = user.totalWeight - previousWeight + newWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); // update global variable usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // if the deposit was created by the pool itself as a yield reward if (isYield) { // mint the yield via the factory factory.mintYieldTo(msg.sender, _amount); } else { // otherwise just return tokens back to holder transferPoolToken(msg.sender, _amount); } // emit an event emit Unstaked(msg.sender, _staker, _amount); } /** * @dev Used internally, mostly by children implementations, see sync() * * @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`), * updates factory state via `updateILVPerBlock` */ function _sync() internal virtual { // update ILV per block value in factory if required if (factory.shouldUpdateRatio()) { factory.updateILVPerBlock(); } // check bound conditions and if these are not met - // exit silently, without emitting an event uint256 endBlock = factory.endBlock(); if (lastYieldDistribution >= endBlock) { return; } if (blockNumber() <= lastYieldDistribution) { return; } // if locking weight is zero - update only `lastYieldDistribution` and exit if (usersLockingWeight == 0) { lastYieldDistribution = uint64(blockNumber()); return; } // to calculate the reward we need to know how many blocks passed, and reward per block uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber(); uint256 blocksPassed = currentBlock - lastYieldDistribution; uint256 ilvPerBlock = factory.ilvPerBlock(); // calculate the reward uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight(); // update rewards per weight and `lastYieldDistribution` yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight); lastYieldDistribution = uint64(currentBlock); // emit an event emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution); } /** * @dev Used internally, mostly by children implementations, see processRewards() * * @param _staker an address which receives the reward (which has staked some tokens earlier) * @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() * @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false * @return pendingYield the rewards calculated and optionally re-staked */ function _processRewards( address _staker, bool _useSILV, bool _withUpdate ) internal virtual returns (uint256 pendingYield) { // update smart contract state if required if (_withUpdate) { _sync(); } // calculate pending yield rewards, this value will be returned pendingYield = _pendingYieldRewards(_staker); // if pending yield is zero - just return silently if (pendingYield == 0) return 0; // get link to a user data structure, we will write into it later User storage user = users[_staker]; // if sILV is requested if (_useSILV) { // - mint sILV mintSIlv(_staker, pendingYield); } else if (poolToken == ilv) { // calculate pending yield weight, // 2e6 is the bonus weight when staking for 1 year uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER; // if the pool is ILV Pool - create new ILV deposit // and save it - push it into deposits array Deposit memory newDeposit = Deposit({ tokenAmount: pendingYield, lockedFrom: uint64(now256()), lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year weight: depositWeight, isYield: true }); user.deposits.push(newDeposit); // update user record user.tokenAmount += pendingYield; user.totalWeight += depositWeight; // update global variable usersLockingWeight += depositWeight; } else { // for other pools - stake as pool address ilvPool = factory.getPoolAddress(ilv); ICorePool(ilvPool).stakeAsPool(_staker, pendingYield); } // update users's record for `subYieldRewards` if requested if (_withUpdate) { user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight); } // emit an event emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield); } /** * @dev See updateStakeLock() * * @param _staker an address to update stake lock * @param _depositId updated deposit ID * @param _lockedUntil updated deposit locked until value */ function _updateStakeLock( address _staker, uint256 _depositId, uint64 _lockedUntil ) internal { // validate the input time require(_lockedUntil > now256(), "lock should be in the future"); // get a link to user data struct, we will write to it later User storage user = users[_staker]; // get a link to the corresponding deposit, we may write to it later Deposit storage stakeDeposit = user.deposits[_depositId]; // validate the input against deposit structure require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock"); // verify locked from and locked until values if (stakeDeposit.lockedFrom == 0) { require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days"); stakeDeposit.lockedFrom = uint64(now256()); } else { require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days"); } // update locked until value, calculate new weight stakeDeposit.lockedUntil = _lockedUntil; uint256 newWeight = (((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount; // save previous weight uint256 previousWeight = stakeDeposit.weight; // update weight stakeDeposit.weight = newWeight; // update user total weight and global locking weight user.totalWeight = user.totalWeight - previousWeight + newWeight; usersLockingWeight = usersLockingWeight - previousWeight + newWeight; // emit an event emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil); } /** * @dev Converts stake weight (not to be mixed with the pool weight) to * ILV reward value, applying the 10^12 division on weight * * @param _weight stake weight * @param rewardPerWeight ILV reward per weight * @return reward value normalized to 10^12 */ function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) { // apply the formula and return return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER; } /** * @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight), * applying the 10^12 multiplication on the reward * - OR - * @dev Converts reward ILV value to reward/weight if stake weight is supplied as second * function parameter instead of reward/weight * * @param reward yield reward * @param rewardPerWeight reward/weight (or stake weight) * @return stake weight (or reward/weight) */ function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) { // apply the reverse formula and return return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override time in helper test smart contracts * * @return `block.timestamp` in mainnet, custom values in testnets (if overridden) */ function now256() public view virtual returns (uint256) { // return current block timestamp return block.timestamp; } /** * @dev Executes EscrowedIlluviumERC20.mint(_to, _values) * on the bound EscrowedIlluviumERC20 instance * * @dev Reentrancy safe due to the EscrowedIlluviumERC20 design */ function mintSIlv(address _to, uint256 _value) private { // just delegate call to the target EscrowedIlluviumERC20(silv).mint(_to, _value); } /** * @dev Executes SafeERC20.safeTransfer on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolToken(address _to, uint256 _value) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransfer(IERC20(poolToken), _to, _value); } /** * @dev Executes SafeERC20.safeTransferFrom on a pool token * * @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant` */ function transferPoolTokenFrom( address _from, address _to, uint256 _value ) internal nonReentrant { // just delegate call to the target SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./ILinkedToILV.sol"; /** * @title Illuvium Pool * * @notice An abstraction representing a pool, see IlluviumPoolBase for details * * @author Pedro Bergamini, reviewed by Basil Gorin */ interface IPool is ILinkedToILV { /** * @dev Deposit is a key data structure used in staking, * it represents a unit of stake with its amount, weight and term (time interval) */ struct Deposit { // @dev token amount staked uint256 tokenAmount; // @dev stake weight uint256 weight; // @dev locking period - from uint64 lockedFrom; // @dev locking period - until uint64 lockedUntil; // @dev indicates if the stake was created as a yield reward bool isYield; } // for the rest of the functions see Soldoc in IlluviumPoolBase function silv() external view returns (address); function poolToken() external view returns (address); function isFlashPool() external view returns (bool); function weight() external view returns (uint32); function lastYieldDistribution() external view returns (uint64); function yieldRewardsPerWeight() external view returns (uint256); function usersLockingWeight() external view returns (uint256); function pendingYieldRewards(address _user) external view returns (uint256); function balanceOf(address _user) external view returns (uint256); function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory); function getDepositsLength(address _user) external view returns (uint256); function stake( uint256 _amount, uint64 _lockedUntil, bool useSILV ) external; function unstake( uint256 _depositId, uint256 _amount, bool useSILV ) external; function sync() external; function processRewards(bool useSILV) external; function setWeight(uint32 _weight) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./IPool.sol"; interface ICorePool is IPool { function vaultRewardsPerToken() external view returns (uint256); function poolTokenReserve() external view returns (uint256); function stakeAsPool(address _staker, uint256 _amount) external; function receiveVaultRewards(uint256 _amount) external; } // https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.sol // #24a0bc23cfe3fbc76f8f2510b78af1e948ae6651 // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @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.1; import "../interfaces/IPool.sol"; import "./IlluviumAware.sol"; import "./IlluviumCorePool.sol"; import "../token/EscrowedIlluviumERC20.sol"; import "../utils/Ownable.sol"; /** * @title Illuvium Pool Factory * * @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single * public interface to access the pools, provides an interface for the pools * to mint yield rewards, access pool-related info, update weights, etc. * * @notice The factory is authorized (via its owner) to register new pools, change weights * of the existing pools, removing the pools (by changing their weights to zero) * * @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield * (see `mintYieldTo` function) * * @author Pedro Bergamini, reviewed by Basil Gorin */ contract IlluviumPoolFactory is Ownable, IlluviumAware { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7; /// @dev Auxiliary data structure used only in getPoolData() view function struct PoolData { // @dev pool token address (like ILV) address poolToken; // @dev pool address (like deployed core pool instance) address poolAddress; // @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment) uint32 weight; // @dev flash pool flag bool isFlashPool; } /** * @dev ILV/block determines yield farming reward base * used by the yield pools controlled by the factory */ uint192 public ilvPerBlock; /** * @dev The yield is distributed proportionally to pool weights; * total weight is here to help in determining the proportion */ uint32 public totalWeight; /** * @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment); * an update is triggered by executing `updateILVPerBlock` public function */ uint32 public immutable blocksPerUpdate; /** * @dev End block is the last block when ILV/block can be decreased; * it is implied that yield farming stops after that block */ uint32 public endBlock; /** * @dev Each time the ILV/block ratio gets updated, the block number * when the operation has occurred gets recorded into `lastRatioUpdate` * @dev This block number is then used to check if blocks/update `blocksPerUpdate` * has passed when decreasing yield reward by 3% */ uint32 public lastRatioUpdate; /// @dev sILV token address is used to create ILV core pool(s) address public immutable silv; /// @dev Maps pool token address (like ILV) -> pool address (like core pool instance) mapping(address => address) public pools; /// @dev Keeps track of registered pool addresses, maps pool address -> exists flag mapping(address => bool) public poolExists; /** * @dev Fired in createPool() and registerPool() * * @param _by an address which executed an action * @param poolToken pool token address (like ILV) * @param poolAddress deployed pool instance address * @param weight pool weight * @param isFlashPool flag indicating if pool is a flash pool */ event PoolRegistered( address indexed _by, address indexed poolToken, address indexed poolAddress, uint64 weight, bool isFlashPool ); /** * @dev Fired in changePoolWeight() * * @param _by an address which executed an action * @param poolAddress deployed pool instance address * @param weight new pool weight */ event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight); /** * @dev Fired in updateILVPerBlock() * * @param _by an address which executed an action * @param newIlvPerBlock new ILV/block value */ event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock); /** * @dev Creates/deploys a factory instance * * @param _ilv ILV ERC20 token address * @param _silv sILV ERC20 token address * @param _ilvPerBlock initial ILV/block value for rewards * @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks * @param _initBlock block number to measure _blocksPerUpdate from * @param _endBlock block number when farming stops and rewards cannot be updated anymore */ constructor( address _ilv, address _silv, uint192 _ilvPerBlock, uint32 _blocksPerUpdate, uint32 _initBlock, uint32 _endBlock ) IlluviumAware(_ilv) { // verify the inputs are set require(_silv != address(0), "sILV address not set"); require(_ilvPerBlock > 0, "ILV/block not set"); require(_blocksPerUpdate > 0, "blocks/update not set"); require(_initBlock > 0, "init block not set"); require(_endBlock > _initBlock, "invalid end block: must be greater than init block"); // verify sILV instance supplied require( EscrowedIlluviumERC20(_silv).TOKEN_UID() == 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62, "unexpected sILV TOKEN_UID" ); // save the inputs into internal state variables silv = _silv; ilvPerBlock = _ilvPerBlock; blocksPerUpdate = _blocksPerUpdate; lastRatioUpdate = _initBlock; endBlock = _endBlock; } /** * @notice Given a pool token retrieves corresponding pool address * * @dev A shortcut for `pools` mapping * * @param poolToken pool token address (like ILV) to query pool address for * @return pool address for the token specified */ function getPoolAddress(address poolToken) external view returns (address) { // read the mapping and return return pools[poolToken]; } /** * @notice Reads pool information for the pool defined by its pool token address, * designed to simplify integration with the front ends * * @param _poolToken pool token address to query pool information for * @return pool information packed in a PoolData struct */ function getPoolData(address _poolToken) public view returns (PoolData memory) { // get the pool address from the mapping address poolAddr = pools[_poolToken]; // throw if there is no pool registered for the token specified require(poolAddr != address(0), "pool not found"); // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // create the in-memory structure and return it return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool }); } /** * @dev Verifies if `blocksPerUpdate` has passed since last ILV/block * ratio update and if ILV/block reward can be decreased by 3% * * @return true if enough time has passed and `updateILVPerBlock` can be executed */ function shouldUpdateRatio() public view returns (bool) { // if yield farming period has ended if (blockNumber() > endBlock) { // ILV/block reward cannot be updated anymore return false; } // check if blocks/update (91252 blocks) have passed since last update return blockNumber() >= lastRatioUpdate + blocksPerUpdate; } /** * @dev Creates a core pool (IlluviumCorePool) and registers it within the factory * * @dev Can be executed by the pool factory owner only * * @param poolToken pool token address (like ILV, or ILV/ETH pair) * @param initBlock init block to be used for the pool created * @param weight weight of the pool to be created */ function createPool( address poolToken, uint64 initBlock, uint32 weight ) external virtual onlyOwner { // create/deploy new core pool instance IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight); // register it within a factory registerPool(address(pool)); } /** * @dev Registers an already deployed pool instance within the factory * * @dev Can be executed by the pool factory owner only * * @param poolAddr address of the already deployed pool instance */ function registerPool(address poolAddr) public onlyOwner { // read pool information from the pool smart contract // via the pool interface (IPool) address poolToken = IPool(poolAddr).poolToken(); bool isFlashPool = IPool(poolAddr).isFlashPool(); uint32 weight = IPool(poolAddr).weight(); // ensure that the pool is not already registered within the factory require(pools[poolToken] == address(0), "this pool is already registered"); // create pool structure, register it within the factory pools[poolToken] = poolAddr; poolExists[poolAddr] = true; // update total pool weight of the factory totalWeight += weight; // emit an event emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool); } /** * @notice Decreases ILV/block reward by 3%, can be executed * no more than once per `blocksPerUpdate` blocks */ function updateILVPerBlock() external { // checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed require(shouldUpdateRatio(), "too frequent"); // decreases ILV/block reward by 3% ilvPerBlock = (ilvPerBlock * 97) / 100; // set current block as the last ratio update block lastRatioUpdate = uint32(blockNumber()); // emit an event emit IlvRatioUpdated(msg.sender, ilvPerBlock); } /** * @dev Mints ILV tokens; executed by ILV Pool only * * @dev Requires factory to have ROLE_TOKEN_CREATOR permission * on the ILV ERC20 token instance * * @param _to an address to mint tokens to * @param _amount amount of ILV tokens to mint */ function mintYieldTo(address _to, uint256 _amount) external { // verify that sender is a pool registered withing the factory require(poolExists[msg.sender], "access denied"); // mint ILV tokens as required mintIlv(_to, _amount); } /** * @dev Changes the weight of the pool; * executed by the pool itself or by the factory owner * * @param poolAddr address of the pool to change weight for * @param weight new weight value to set to */ function changePoolWeight(address poolAddr, uint32 weight) external { // verify function is executed either by factory owner or by the pool itself require(msg.sender == owner() || poolExists[msg.sender]); // recalculate total weight totalWeight = totalWeight + weight - IPool(poolAddr).weight(); // set the new pool weight IPool(poolAddr).setWeight(weight); // emit an event emit WeightUpdated(msg.sender, poolAddr, weight); } /** * @dev Testing time-dependent functionality is difficult and the best way of * doing it is to override block number in helper test smart contracts * * @return `block.number` in mainnet, custom values in testnets (if overridden) */ function blockNumber() public view virtual returns (uint256) { // return current block number return block.number; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IERC20.sol"; import "./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 { uint256 newAllowance = token.allowance(address(this), spender) - 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.1; import "../utils/ERC20.sol"; import "../utils/AccessControl.sol"; contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62; /** * @notice Must be called by ROLE_TOKEN_CREATOR addresses. * * @param recipient address to receive the tokens. * @param amount number of tokens to be minted. */ function mint(address recipient, uint256 amount) external { require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); _mint(recipient, amount); } /** * @param amount number of tokens to be burned. */ function burn(uint256 amount) external { _burn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Linked to ILV Marker Interface * * @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction, * all these smart contracts share a common ilv() address getter * * @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance * and that ilv() getter returns this very same instance address * * @author Basil Gorin */ interface ILinkedToILV { /** * @notice Getter for a verified IlluviumERC20 instance address * * @return IlluviumERC20 token instance address smart contract is linked to */ function ilv() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../token/IlluviumERC20.sol"; import "../interfaces/ILinkedToILV.sol"; /** * @title Illuvium Aware * * @notice Helper smart contract to be inherited by other smart contracts requiring to * be linked to verified IlluviumERC20 instance and performing some basic tasks on it * * @author Basil Gorin */ abstract contract IlluviumAware is ILinkedToILV { /// @dev Link to ILV ERC20 Token IlluviumERC20 instance address public immutable override ilv; /** * @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address * * @param _ilv deployed IlluviumERC20 instance address */ constructor(address _ilv) { // verify ILV address is set and is correct require(_ilv != address(0), "ILV address not set"); require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID"); // write ILV address ilv = _ilv; } /** * @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "") * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlv(address _to, uint256 _value) internal { // just delegate call to the target transferIlvFrom(address(this), _to, _value); } /** * @dev Executes IlluviumERC20.transferFrom(_from, _to, _value) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function transferIlvFrom(address _from, address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).transferFrom(_from, _to, _value); } /** * @dev Executes IlluviumERC20.mint(_to, _values) * on the bound IlluviumERC20 instance * * @dev Reentrancy safe due to the IlluviumERC20 design */ function mintIlv(address _to, uint256 _value) internal { // just delegate call to the target IlluviumERC20(ilv).mint(_to, _value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @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 { 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 = msg.sender; _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() == msg.sender, "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.1; import "../utils/AddressUtils.sol"; import "../utils/AccessControl.sol"; import "./ERC20Receiver.sol"; /** * @title Illuvium (ILV) ERC20 token * * @notice Illuvium is a core ERC20 token powering the game. * It serves as an in-game currency, is tradable on exchanges, * it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming. * * @dev Token Summary: * - Symbol: ILV * - Name: Illuvium * - Decimals: 18 * - Initial token supply: 7,000,000 ILV * - Maximum final token supply: 10,000,000 ILV * - Up to 3,000,000 ILV may get minted in 3 years period via yield farming * - Mintable: total supply may increase * - Burnable: total supply may decrease * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.1 enforces overflow/underflow safety. * * @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20 * * @dev ERC20: contract has passed OpenZeppelin ERC20 tests, * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * see adopted copies of these tests in the `test` folder * * @dev ERC223/ERC777: not supported; * send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead * * @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved * Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag: * - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @author Basil Gorin */ contract IlluviumERC20 is AccessControl { /** * @dev Smart contract unique identifier, a random number * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c; /** * @notice Name of the token: Illuvium * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Illuvium"; /** * @notice Symbol of the token: ILV * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "ILV"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 7,000,000, * with the potential to grow up to 10,000,000 during yield farming period (3 years) * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) public tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened */ struct VotingPowerRecord { /* * @dev block.number when delegation has changed; starting from * that block voting power value is in effect */ uint64 blockNumber; /* * @dev cumulative voting power a delegate has obtained starting * from the block stored in blockNumber */ uint192 votingPower; } /** * @notice A record of each account's voting power * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints. * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => VotingPowerRecord[]) public votingPowerHistory; /** * @dev A record of nonces for signing/validating signatures in `delegateWithSig` * for every delegate, increases after successful validation * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public nonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) public transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `safeTransferFrom` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners, * including locked tokens which are burnt first * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegateWithSig()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s) * @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector` */ bytes4 private constant ERC20_RECEIVED = 0x4fc35859; /** * @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /** * @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)"); /** * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)` * * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Fired in approve() and approveAtomic() functions * * @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)` * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _value amount of tokens granted to transfer on behalf */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @dev Fired in mint() function * * @param _by an address which minted some tokens (transaction sender) * @param _to an address the tokens were minted to * @param _value an amount of tokens minted */ event Minted(address indexed _by, address indexed _to, uint256 _value); /** * @dev Fired in burn() function * * @param _by an address which burned some tokens (transaction sender) * @param _from an address the tokens were burnt from * @param _value an amount of tokens burnt */ event Burnt(address indexed _by, address indexed _from, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param _by an address which performed the transfer * @param _from an address tokens were consumed from * @param _to an address tokens were sent to * @param _value number of tokens transferred */ event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve() and approveAtomic() functions * * @param _owner an address which granted a permission to transfer * tokens on its behalf * @param _spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param _oldValue previously granted amount of tokens to transfer on behalf * @param _value new granted amount of tokens to transfer on behalf */ event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param _of delegator address, a token owner * @param _from old delegate, an address which delegate right is revoked * @param _to new delegate, an address which received the voting power */ event DelegateChanged(address indexed _of, address indexed _from, address indexed _to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param _of delegate whose voting power has changed * @param _fromVal previous number of votes delegate had * @param _toVal new number of votes delegate has */ event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // mint initial supply mint(_initialHolder, 7_000_000e18); } // ===== Start: ERC20/ERC223/ERC777 functions ===== /** * @notice Gets the balance of a particular address * * @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)` * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Inspired by ERC721 safeTransferFrom, this function allows to * send arbitrary data to the receiver on successful token transfer * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20Receiver interface * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero * @param _data [optional] additional data with no specified format, * sent in onERC20Received call to `_to` in case if its a smart contract */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public { // first delegate call to `unsafeTransferFrom` // to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC20Receiver and execute a callback handler `onERC20Received`, // reverting whole transaction on any error: // check if receiver `_to` supports ERC20Receiver interface if(AddressUtils.isContract(_to)) { // if `_to` is a contract - execute onERC20Received bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data); // expected response is ERC20_RECEIVED require(response == ERC20_RECEIVED, "invalid onERC20Received response"); } } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `safeTransferFrom` doesn't check recipient * smart contract to support ERC20 tokens (ERC20Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC20Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred, must * be greater than zero */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg // non-zero recipient address check require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(_from, msg.sender, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event emit Transferred(msg.sender, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner * * @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)` * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public returns (bool success) { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg // read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9) uint256 _oldValue = transferAllowances[msg.sender][_spender]; // perform an operation: write value requested into the storage transferAllowances[msg.sender][_spender] = _value; // emit an improved atomic approve event (ISBN:978-1-7281-3027-9) emit Approved(msg.sender, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)` * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20/ERC223/ERC777 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) * * @dev Throws if value to decrease by is zero or is bigger than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `mintTo` function, allowing * to specify an address to mint tokens to * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)"); // non-zero recipient address check require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow"); // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // create voting power associated with the tokens minted __moveVotingPower(address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event emit Transferred(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Behaves effectively as `burnFrom` function, allowing * to specify an address to burn tokens from * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event emit Approved(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // destroy voting power associated with the tokens burnt __moveVotingPower(votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event emit Transferred(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function getVotingPower(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].votingPower; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * @dev Throws if `_blockNum` is not in the past (not the finalized block) * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "not yet determined"); // Compound msg // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if voting power history for the account provided is empty if(history.length == 0) { // than voting power is zero - return the result return 0; } // check latest voting power history record block number: // if history was not updated after the block of interest if(history[history.length - 1].blockNumber <= _blockNum) { // we're done - return last voting power record return getVotingPower(_of); } // check first voting power history record block number: // if history was never updated before the block of interest if(history[0].blockNumber > _blockNum) { // we're done - voting power at the block num of interest was zero return 0; } // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].blockNumber > _blockNum` // return the result - voting power found at index `i` return history[__binaryLookup(_of, _blockNum)].votingPower; } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function getVotingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @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 delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // build the EIP-712 contract domain separator bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); // build the EIP-712 hashStruct of the delegation message bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp)); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct)); // recover the address who signed the message with v, r, s address signer = ecrecover(digest, v, r, s); // perform message integrity and security validations require(signer != address(0), "invalid signature"); // Compound msg require(_nonce == nonces[signer], "invalid nonce"); // Compound msg require(block.timestamp < _exp, "signature expired"); // Compound msg // update the nonce for that particular signer to avoid replay attack nonces[signer]++; // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // read current source address voting power uint256 _fromVal = getVotingPower(_from); // calculate decreased voting power // underflow is not possible by design: // voting power is limited by token balance which is checked by the callee uint256 _toVal = _fromVal - _value; // update source voting power from `_fromVal` to `_toVal` __updateVotingPower(_from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // read current destination address voting power uint256 _fromVal = getVotingPower(_to); // calculate increased voting power // overflow is not possible by design: // max token supply limits the cumulative voting power uint256 _toVal = _fromVal + _value; // update destination voting power from `_fromVal` to `_toVal` __updateVotingPower(_to, _fromVal, _toVal); } } /** * @dev Auxiliary function to update voting power of the delegate `_of` * from value `_fromVal` to value `_toVal` * * @param _of delegate to update its voting power * @param _fromVal old voting power of the delegate * @param _toVal new voting power of the delegate */ function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_of]; // if there is an existing voting power value stored for current block if(history.length != 0 && history[history.length - 1].blockNumber == block.number) { // update voting power which is already stored in the current block history[history.length - 1].votingPower = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal))); } // emit an event emit VotingPowerChanged(_of, _fromVal, _toVal); } /** * @dev Auxiliary function to lookup an element in a sorted (asc) array of elements * * @dev This function finds the closest element in an array to the value * of interest (not exceeding that value) and returns its index within an array * * @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`, * it is sorted in ascending order (blockNumber increases) * * @param _to an address of the delegate to get an array for * @param n value of interest to look for * @return an index of the closest element in an array to the value * of interest (not exceeding that value) */ function __binaryLookup(address _to, uint256 n) private view returns(uint256) { // get a link to an array of voting power history records for an address specified VotingPowerRecord[] storage history = votingPowerHistory[_to]; // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = history.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest VotingPowerRecord memory cp = history[k]; // if we've got a strict equal - we're lucky and done if(cp.blockNumber == n) { // just return the result - index `k` return k; } // if the value of interest is bigger - move left bound to the middle else if (cp.blockNumber < n) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is bigger and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not bigger than the // element of interest, we return the lower bound `i` return i; } } // ===== End: DAO Support (Compound-like voting delegation) ===== // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @author Basil Gorin */ library AddressUtils { /** * @notice Checks if the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { // a variable to load `extcodesize` to uint256 size = 0; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. // TODO: Check this again before the Serenity release, because all addresses will be contracts. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @author Basil Gorin */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev Zero address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Auxiliary getter function to maintain compatibility with previous * versions of the Access Control List smart contract, where * features was a separate uint256 public field * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // according to new design features are stored in zero address // mapping of `userRoles` structure return userRoles[address(0)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(0), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; /** * @title ERC20 token receiver interface * * @dev Interface for any contract that wants to support safe transfers * from ERC20 token smart contracts. * @dev Inspired by ERC721 and ERC223 token standards * * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @dev See https://github.com/ethereum/EIPs/issues/223 * * @author Basil Gorin */ interface ERC20Receiver { /** * @notice Handle the receipt of a ERC20 token(s) * @dev The ERC20 smart contract calls this function on the recipient * after a successful transfer (`safeTransferFrom`). * This function MAY throw to revert and reject the transfer. * Return of other than the magic value MUST result in the transaction being reverted. * @notice The contract address is always the message sender. * A wallet/broker/auction application MUST implement the wallet interface * if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _value amount of tokens which is being transferred * @param _data additional data with no specified format * @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing */ function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "../interfaces/IERC20.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}. */ // Copied from Open Zeppelin contract ERC20 is IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual 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 virtual returns (uint8) { return _decimals; } /** * @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(msg.sender, 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(msg.sender, 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, msg.sender, _allowances[sender][msg.sender] - 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 virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 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] - amount; _balances[recipient] = _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 virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply + amount; _balances[account] = _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 virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account] - amount; _totalSupply = _totalSupply - 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 virtual { _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.8.1; /** * @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.1; /** * @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); } } } }
@dev sILV token address is used to create ILV core pool(s)
address public immutable silv;
898,406
[ 1, 87, 2627, 58, 1147, 1758, 353, 1399, 358, 752, 467, 48, 58, 2922, 2845, 12, 87, 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, 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, 565, 1758, 1071, 11732, 17714, 90, 31, 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, -100, -100, -100 ]
./partial_match/1/0x2132110A63c623EAcA0A888fFe9580135a758355/sources/Sprial2.sol
addresses limits status flags
contract Sprial2 is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable router; address public immutable uniswapV2Pair; address private devWallet; address private marketingWallet; uint256 private maxBuyAmount; uint256 private maxSellAmount; uint256 private maxWalletAmount; uint256 private thresholdSwapAmount; bool private isTrading = false; bool public swapEnabled = false; bool public isSwapping; struct Fees { uint256 buyTotalFees; uint256 buyMarketingFee; uint256 buyDevFee; uint256 buyLiquidityFee; uint256 sellTotalFees; uint256 sellMarketingFee; uint256 sellDevFee; uint256 sellLiquidityFee; } Fees public _fees = Fees({ buyTotalFees: 0, buyMarketingFee: 0, buyDevFee:0, buyLiquidityFee: 0, sellTotalFees: 0, sellMarketingFee: 0, sellDevFee:0, sellLiquidityFee: 0 }); uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 private taxTill; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public _isExcludedMaxWalletAmount; event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived ); mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public marketPair; constructor() ERC20("Spiral 2.0", "SPIRAL2") { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH()); _isExcludedMaxTransactionAmount[address(router)] = true; _isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true; _isExcludedMaxTransactionAmount[owner()] = true; _isExcludedMaxTransactionAmount[address(this)] = true; _isExcludedFromFees[owner()] = true; _isExcludedFromFees[address(this)] = true; _isExcludedMaxWalletAmount[owner()] = true; _isExcludedMaxWalletAmount[address(this)] = true; _isExcludedMaxWalletAmount[address(uniswapV2Pair)] = true; marketPair[address(uniswapV2Pair)] = true; approve(address(router), type(uint256).max); uint256 totalSupply = 1e8 * 1e18; _fees.buyMarketingFee = 0; _fees.buyLiquidityFee = 1; _fees.buyDevFee = 1; _fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevFee; _fees.sellMarketingFee = 0; _fees.sellLiquidityFee = 0; _fees.sellDevFee = 0; _fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevFee; marketingWallet = address(0x5b508a6A8f495629BcbC7C86F754abF2CBb21241); devWallet = address(0xEcFf00aB0bC0aeAE74c2Ce2ce25D476F9A8D7C4d); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function swapTrading() external onlyOwner { isTrading = true; swapEnabled = true; taxTill = block.number + 2; } function updateThresholdSwapAmount(uint256 newAmount) external onlyOwner returns(bool){ thresholdSwapAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newMaxBuy, uint256 newMaxSell) external onlyOwner { require(((totalSupply() * newMaxBuy) / 1000) >= (totalSupply() / 100), "Cannot set maxTransactionAmounts lower than 1%"); require(((totalSupply() * newMaxSell) / 1000) >= (totalSupply() / 100), "Cannot set maxTransactionAmounts lower than 1%"); maxBuyAmount = (totalSupply() * newMaxBuy) / 1000; maxSellAmount = (totalSupply() * newMaxSell) / 1000; } function updateMaxWalletAmount(uint256 newPercentage) external onlyOwner { require(((totalSupply() * newPercentage) / 1000) >= (totalSupply() / 100), "Cannot set maxWallet lower than 1%"); maxWalletAmount = (totalSupply() * newPercentage) / 1000; } function toggleSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateFees(uint256 _marketingFeeBuy, uint256 _liquidityFeeBuy,uint256 _devFeeBuy,uint256 _marketingFeeSell, uint256 _liquidityFeeSell,uint256 _devFeeSell) external onlyOwner{ _fees.buyMarketingFee = _marketingFeeBuy; _fees.buyLiquidityFee = _liquidityFeeBuy; _fees.buyDevFee = _devFeeBuy; _fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevFee; _fees.sellMarketingFee = _marketingFeeSell; _fees.sellLiquidityFee = _liquidityFeeSell; _fees.sellDevFee = _devFeeSell; _fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevFee; require(_fees.buyTotalFees <= 99, "Must keep fees at 99% or less"); require(_fees.sellTotalFees <= 99, "Must keep fees at 99% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; } function excludeFromWalletLimit(address account, bool excluded) public onlyOwner { _isExcludedMaxWalletAmount[account] = excluded; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function setMarketPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from marketPair"); marketPair[pair] = value; } function setWallets(address _marketingWallet,address _devWallet) external onlyOwner{ marketingWallet = _marketingWallet; devWallet = _devWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } } else if (marketPair[recipient] && _fees.sellTotalFees > 0) { function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { if (amount == 0) { super._transfer(sender, recipient, 0); return; } if ( sender != owner() && recipient != owner() && !isSwapping ) { if (!isTrading) { require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active."); } if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[recipient]) { require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded"); } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= thresholdSwapAmount; if ( canSwap && swapEnabled && !isSwapping && marketPair[recipient] && !_isExcludedFromFees[sender] && !_isExcludedFromFees[recipient] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) { takeFee = false; } if (takeFee) { uint256 fees = 0; if(block.number < taxTill) { fees = amount.mul(99).div(100); tokensForMarketing += (fees * 94) / 99; tokensForDev += (fees * 5) / 99; fees = amount.mul(_fees.sellTotalFees).div(100); tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees; tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees; tokensForDev += fees * _fees.sellDevFee / _fees.sellTotalFees; } else if (marketPair[sender] && _fees.buyTotalFees > 0) { fees = amount.mul(_fees.buyTotalFees).div(100); tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees; tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees; tokensForDev += fees * _fees.buyDevFee / _fees.buyTotalFees; } if (fees > 0) { super._transfer(sender, address(this), fees); } amount -= fees; } super._transfer(sender, recipient, amount); } function swapTokensForEth(uint256 tAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); _approve(address(this), address(router), tAmount); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tAmount, uint256 ethAmount) private { _approve(address(this), address(router), tAmount); } router.addLiquidityETH{ value: ethAmount } (address(this), tAmount, 0, 0 , address(this), block.timestamp); function swapBack() private { uint256 contractTokenBalance = balanceOf(address(this)); uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractTokenBalance > thresholdSwapAmount * 20) { contractTokenBalance = thresholdSwapAmount * 20; } uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 newBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap); uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap); uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev); tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity); } } if (contractTokenBalance == 0 || toSwap == 0) { return; } function swapBack() private { uint256 contractTokenBalance = balanceOf(address(this)); uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractTokenBalance > thresholdSwapAmount * 20) { contractTokenBalance = thresholdSwapAmount * 20; } uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 newBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap); uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap); uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev); tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity); } } uint256 liquidityTokens = contractTokenBalance * tokensForLiquidity / toSwap / 2; function swapBack() private { uint256 contractTokenBalance = balanceOf(address(this)); uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractTokenBalance > thresholdSwapAmount * 20) { contractTokenBalance = thresholdSwapAmount * 20; } uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 newBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap); uint256 ethForDev = newBalance.mul(tokensForDev).div(toSwap); uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDev); tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity); } } (success,) = address(devWallet).call{ value: (address(this).balance - ethForMarketing) } (""); (success,) = address(marketingWallet).call{ value: address(this).balance } (""); }
2,875,193
[ 1, 13277, 8181, 1267, 2943, 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, 16351, 5878, 566, 287, 22, 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, 11732, 4633, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 203, 565, 2254, 5034, 3238, 943, 38, 9835, 6275, 31, 203, 565, 2254, 5034, 3238, 943, 55, 1165, 6275, 31, 27699, 565, 2254, 5034, 3238, 943, 16936, 6275, 31, 203, 7010, 565, 2254, 5034, 3238, 5573, 12521, 6275, 31, 203, 203, 565, 1426, 3238, 353, 1609, 7459, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 353, 12521, 1382, 31, 203, 203, 203, 565, 1958, 5782, 281, 288, 203, 3639, 2254, 5034, 30143, 5269, 2954, 281, 31, 203, 3639, 2254, 5034, 30143, 3882, 21747, 14667, 31, 203, 3639, 2254, 5034, 30143, 8870, 14667, 31, 203, 3639, 2254, 5034, 30143, 48, 18988, 24237, 14667, 31, 203, 203, 3639, 2254, 5034, 357, 80, 5269, 2954, 281, 31, 203, 3639, 2254, 5034, 357, 80, 3882, 21747, 14667, 31, 203, 3639, 2254, 5034, 357, 80, 8870, 14667, 31, 203, 3639, 2254, 5034, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 289, 21281, 203, 565, 5782, 281, 1071, 389, 3030, 281, 273, 5782, 281, 12590, 203, 3639, 30143, 5269, 2954, 281, 30, 374, 16, 203, 3639, 30143, 3882, 21747, 14667, 30, 374, 2 ]
pragma solidity >=0.4.22 <0.7.0; /** ****************************************************************** * * ██████████████████ * ██ ██ * ██ ██████████████████ ██ * ██ ██████████████████████ ██ * ██ ██████████████████████████ ██ * ██ ██████████████████████████████ ██ * ██ ██████████████████████████████████ ██ * ██ ██████████████████████████████████████ ██ * ██ ██████ ██ ████ ████ ██████ ██ * ██ ████ ████████ ████ ██ ██ ██ ████ ██ * ██ ████ ████████ ████ ██ ██ ██ ████ ██ * ██ ██████ ██████ ████ ██ ██ ██████ ██ * ██ ████████ ████ ████ ██ ██ ████████ ██ * ██ ████████ ████ ████ ██ ██ ████████ ██ * ██ ████ ██████ ██████ ████ ████████ ██ * ██ ██████████████████████████████████████ ██ * ██ ██████████████████████████████████ ██ * ██ ██████████████████████████████ ██ * ██ ██████████████████████████ ██ * ██ ██████████████████████ ██ * ██ ██████████████████ ██ * ██ ██ * ██████████████████ * ****************************************************************** * DO NOT SEND ETH HERE! ****************************************************************** */ /** * @title DoNotSendFundsHere * @dev This contract is a stub to recover mainnet funds sent to the Prysmatic Labs testnet address. * The testnet contract is deployed on Goerli, not on Ethereum's main network. Do not send funds here! * If you sent funds here by mistake, please email contact at prysmaticlabs.com with * proof that you are the originator of the lost funds. */ contract DoNotSendFundsHere { address payable public owner; /// @dev Initialize the contract with the contract creator as the owner. constructor() public { owner = msg.sender; } /// @dev Modifier to require the message sender to be the owner. modifier onlyOwner() { require( msg.sender == owner, "Sender not authorized." ); _; } /// @dev Change the sole owner of the contract. /// @param _newOwner the address of the new owner of this contract. function changeOwner(address payable _newOwner) public onlyOwner { owner = _newOwner; } /// @dev Send all ETH held by the contract to the contract owner. function recoverETHFunds() public onlyOwner { owner.transfer(address(this).balance); } /// @dev Approve ERC20 spending for a particular ERC20 token. /// @param _token The ERC20 token address. /// @param _spender The spender address to authorize spending on behalf of this contract. /// @param _value The amount authorized for the _spender. function approveERC20Funds(ERC20 _token, address _spender, uint _value) public onlyOwner { _token.approve(_spender, _value); } /// @dev Send all of the ERC20 token owned by this contract to the contract owner. /// @param _token The ERC20 token address. function recoverERC20Funds(ERC20 _token) public onlyOwner { _token.transfer(owner, _token.balanceOf(address(this))); } /// @dev Fallback payable. DO NOT SEND ETH HERE!!! The reason this does not reject any non-zero transaction /// is that users sending directly from centralized exchanges may experience a total loss if their transaction /// is rejected. Do not send ETH here. receive() external payable { } } interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); }
* @title DoNotSendFundsHere @dev This contract is a stub to recover mainnet funds sent to the Prysmatic Labs testnet address. The testnet contract is deployed on Goerli, not on Ethereum's main network. Do not send funds here! If you sent funds here by mistake, please email contact at prysmaticlabs.com with proof that you are the originator of the lost funds./
contract DoNotSendFundsHere { address payable public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require( msg.sender == owner, "Sender not authorized." ); _; } function changeOwner(address payable _newOwner) public onlyOwner { owner = _newOwner; } function recoverETHFunds() public onlyOwner { owner.transfer(address(this).balance); } function approveERC20Funds(ERC20 _token, address _spender, uint _value) public onlyOwner { _token.approve(_spender, _value); } function recoverERC20Funds(ERC20 _token) public onlyOwner { _token.transfer(owner, _token.balanceOf(address(this))); } receive() external payable { } }
1,730,305
[ 1, 3244, 1248, 3826, 42, 19156, 26715, 225, 1220, 6835, 353, 279, 7168, 358, 5910, 2774, 2758, 284, 19156, 3271, 358, 326, 453, 1176, 4808, 2126, 511, 5113, 1842, 2758, 1758, 18, 1021, 1842, 2758, 6835, 353, 19357, 603, 4220, 264, 549, 16, 486, 603, 512, 18664, 379, 1807, 2774, 2483, 18, 2256, 486, 1366, 284, 19156, 2674, 5, 971, 1846, 3271, 284, 19156, 2674, 635, 27228, 911, 16, 9582, 2699, 5388, 622, 846, 1900, 26500, 80, 5113, 18, 832, 598, 14601, 716, 1846, 854, 326, 4026, 639, 434, 326, 13557, 284, 19156, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 2256, 1248, 3826, 42, 19156, 26715, 288, 203, 565, 1758, 8843, 429, 1071, 3410, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 3410, 16, 203, 5411, 315, 12021, 486, 10799, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 445, 2549, 5541, 12, 2867, 8843, 429, 389, 2704, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 3410, 273, 389, 2704, 5541, 31, 203, 565, 289, 203, 377, 203, 565, 445, 5910, 1584, 44, 42, 19156, 1435, 1071, 1338, 5541, 288, 203, 3639, 3410, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 6617, 537, 654, 39, 3462, 42, 19156, 12, 654, 39, 3462, 389, 2316, 16, 1758, 389, 87, 1302, 264, 16, 2254, 389, 1132, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 2316, 18, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 5910, 654, 39, 3462, 42, 19156, 12, 654, 39, 3462, 389, 2316, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 2316, 18, 13866, 12, 8443, 16, 389, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 565, 289, 203, 377, 203, 565, 6798, 1435, 3903, 8843, 429, 288, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x31A327c3827FE05e97a8DBb4F2d756E57371812e/sources/assignmentToken.sol
TODO: specify `MAXSUPPLY`, declare `minter` and `supply` TODO: specify event to be emitted on transfer TODO: specify event to be emitted on approval TODO: create mapping for balances TODO: create mapping for allowances
contract assignmentToken { uint256 constant MAXSUPPLY= 1000000; uint256 public supply = 50000; address public minter; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event MintershipTransfer( address indexed previousMinter, address indexed newMinter ); mapping(address=> uint) public balances; mapping (address=> mapping (address=>uint)) public allowances; pragma solidity ^0.7.0; constructor() { balances[msg.sender]=supply; minter = msg.sender; } function totalSupply() public view returns (uint256) { return supply; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function mint(address receiver, uint256 amount) public returns (bool) { require(amount != 0); require(msg.sender == minter); require(supply+amount<=MAXSUPPLY); balances[receiver]+=amount; supply+=amount; emit Transfer(address(0),receiver,amount); return true; } function burn(uint256 amount) public returns (bool) { require(amount != 0); require(amount <= balances[msg.sender]); supply-=amount; balances[msg.sender]-=amount; balances[address(0)]+=amount; emit Transfer(msg.sender,address(0),amount); return true; } function transferMintership(address newMinter) public returns (bool) { require(newMinter != address(0), "new minter is the zero address"); require(msg.sender==address(0)); emit MintershipTransfer(address(0), address(1)); minter = newMinter; return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value>=1); require(_value <= balances[msg.sender]); balances[msg.sender]-=_value; balances[_to]+=_value-1; balances[minter]+=1; emit Transfer(msg.sender,_to,_value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value<= balances[_from]); require (_value<=allowances[_from][msg.sender] ); balances[_from]-=_value; balances[_to]+=_value; allowances[_from][msg.sender]-=_value; emit Transfer(_from,_to,_value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowances[msg.sender][_spender]=_value; emit Approval(msg.sender,_spender,_value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowances[_owner][_spender]; } }
8,855,244
[ 1, 6241, 30, 4800, 1375, 6694, 13272, 23893, 9191, 14196, 1375, 1154, 387, 68, 471, 1375, 2859, 1283, 68, 2660, 30, 4800, 871, 358, 506, 17826, 603, 7412, 2660, 30, 4800, 871, 358, 506, 17826, 603, 23556, 2660, 30, 752, 2874, 364, 324, 26488, 2660, 30, 752, 2874, 364, 1699, 6872, 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, 16351, 6661, 1345, 288, 203, 565, 2254, 5034, 5381, 4552, 13272, 23893, 33, 15088, 31, 203, 565, 2254, 5034, 1071, 14467, 273, 1381, 2787, 31, 203, 565, 1758, 1071, 1131, 387, 31, 203, 203, 377, 203, 565, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 1132, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 389, 8443, 16, 1758, 8808, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 1769, 203, 377, 203, 377, 203, 565, 871, 490, 2761, 3261, 5912, 12, 203, 3639, 1758, 8808, 2416, 49, 2761, 16, 203, 3639, 1758, 8808, 394, 49, 2761, 203, 565, 11272, 203, 203, 565, 2874, 12, 2867, 9207, 2254, 13, 1071, 324, 26488, 31, 203, 565, 2874, 261, 2867, 9207, 2874, 261, 2867, 9207, 11890, 3719, 1071, 1699, 6872, 31, 203, 377, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 565, 3885, 1435, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 33, 2859, 1283, 31, 203, 3639, 1131, 387, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 14467, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 5971, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 2 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } 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; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts 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), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts 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), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } 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; } } 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)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } 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 {ERC20MinterPauser}. * * 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 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 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: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; /** * @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); } 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 "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } 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); } } 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); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; 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 "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } 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 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"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // 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() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @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() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } 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; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } 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 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } 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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } 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, _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()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } 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; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } 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: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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 (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { 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))), 'TransferHelper::safeApprove: approve failed' ); } 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))), 'TransferHelper::safeTransfer: transfer failed' ); } 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))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } pragma solidity >=0.6.2; 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.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
* @notice Adds an `Signed` to an unscaled int, reverting on overflow. @param a a FixedPoint.Signed. @param b an int256. @return the sum of `a` and `b`./
function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); }
98,903
[ 1, 3655, 392, 1375, 12294, 68, 358, 392, 16804, 12825, 509, 16, 15226, 310, 603, 9391, 18, 225, 279, 279, 15038, 2148, 18, 12294, 18, 225, 324, 392, 509, 5034, 18, 327, 326, 2142, 434, 1375, 69, 68, 471, 1375, 70, 8338, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 527, 12, 12294, 3778, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 12294, 3778, 13, 288, 203, 3639, 327, 527, 12, 69, 16, 628, 984, 20665, 1702, 12, 70, 10019, 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 ]
./full_match/5/0x99B879CF978ed6035bab32fded704186302a6A25/sources/project_/contracts/DevonRex.sol
@TODO: complete param docs @dev Verifies sender's signature
function _verifySignature( uint8 v, bytes32 r, bytes32 s, address _from, address _to, uint256 _deadline ) internal view { uint256 chainId; assembly { chainId := chainId } bytes32 eip712DomainHash = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), chainId, address(this) ) ); bytes32 hashStruct = keccak256( abi.encode( keccak256(("set(address _from,address _to,uint256 _deadline)")), _from, _to, _deadline ) ); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", eip712DomainHash, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer == _from, "ERC20_INVALID_SIGNATURE"); require(signer != address(0), "ERC20_INVALID_SIGNATURE"); }
1,921,198
[ 1, 36, 6241, 30, 3912, 579, 3270, 225, 6160, 5032, 5793, 1807, 3372, 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, 389, 8705, 5374, 12, 203, 1377, 2254, 28, 331, 16, 7010, 1377, 1731, 1578, 436, 16, 7010, 1377, 1731, 1578, 272, 16, 203, 1377, 1758, 389, 2080, 16, 7010, 1377, 1758, 389, 869, 16, 7010, 1377, 2254, 5034, 389, 22097, 1369, 203, 565, 262, 2713, 1476, 288, 203, 1377, 2254, 5034, 2687, 548, 31, 203, 1377, 19931, 288, 203, 1850, 2687, 548, 519, 2687, 548, 203, 1377, 289, 203, 203, 1377, 1731, 1578, 425, 625, 27, 2138, 3748, 2310, 273, 417, 24410, 581, 5034, 12, 203, 1850, 24126, 18, 3015, 12, 203, 2868, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 1080, 1177, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 3631, 203, 2868, 2687, 548, 16, 203, 2868, 1758, 12, 2211, 13, 203, 1850, 262, 203, 1377, 11272, 203, 203, 1377, 1731, 1578, 1651, 3823, 273, 417, 24410, 581, 5034, 12, 203, 1850, 24126, 18, 3015, 12, 203, 2868, 417, 24410, 581, 5034, 12, 2932, 542, 12, 2867, 389, 2080, 16, 2867, 389, 869, 16, 11890, 5034, 389, 22097, 1369, 2225, 13, 3631, 203, 2868, 389, 2080, 16, 203, 2868, 389, 869, 16, 203, 2868, 389, 22097, 1369, 203, 1850, 262, 203, 1377, 11272, 203, 203, 1377, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 31458, 92, 3657, 64, 92, 1611, 3113, 425, 625, 27, 2138, 3748, 2310, 16, 1651, 3823, 10019, 203, 1377, 1758, 10363, 273, 425, 1793, 3165, 12, 2816, 16, 331, 16, 436, 2 ]
./partial_match/42220/0x6023fF93A3b37791a94B15D6AEaD488933b01Db3/sources/C/Users/guill/github/witnet/witnet-solidity-bridge/flattened/WitnetRandomness/FlattenedWitnetRandomness.sol
File: contracts\patterns\Initializable.sol
interface Initializable { function initialize(bytes calldata) external; } }
3,500,416
[ 1, 812, 30, 20092, 64, 13317, 64, 4435, 6934, 18, 18281, 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, 5831, 10188, 6934, 288, 203, 565, 445, 4046, 12, 3890, 745, 892, 13, 3903, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/handlers/maker/IDSProxy.sol pragma solidity ^0.6.0; interface IDSProxy { function execute(address _target, bytes calldata _data) external payable returns (bytes32 response); function owner() external view returns (address); function setAuthority(address authority_) external; } interface IDSProxyFactory { function isProxy(address proxy) external view returns (bool); function build() external returns (address); function build(address owner) external returns (address); } interface IDSProxyRegistry { function proxies(address input) external view returns (address); function build() external returns (address); function build(address owner) external returns (address); } // File: contracts/handlers/maker/IMaker.sol pragma solidity ^0.6.0; interface IMakerManager { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; function count(address) external view returns (uint256); function first(address) external view returns (uint256); function last(address) external view returns (uint256); } interface IMakerVat { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } interface IMakerGemJoin { function dec() external view returns (uint256); function gem() external view returns (address); function join(address, uint256) external payable; function exit(address, uint256) external; } interface IMakerChainLog { function getAddress(bytes32) external view returns (address); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT 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/SafeMath.sol 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; } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @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" ); } } } // File: contracts/interface/IERC20Usdt.sol pragma solidity ^0.6.0; interface IERC20Usdt { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external; function transferFrom( address sender, address recipient, uint256 amount ) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Config.sol pragma solidity ^0.6.0; contract Config { // function signature of "postProcess()" bytes4 public constant POSTPROCESS_SIG = 0xc2722916; // The base amount of percentage function uint256 public constant PERCENTAGE_BASE = 1 ether; // Handler post-process type. Others should not happen now. enum HandlerType {Token, Custom, Others} } // File: contracts/lib/LibCache.sol pragma solidity ^0.6.0; library LibCache { function set( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, bytes32 _value ) internal { _cache[_key] = _value; } function setAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, address _value ) internal { _cache[_key] = bytes32(uint256(uint160(_value))); } function setUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, uint256 _value ) internal { _cache[_key] = bytes32(_value); } function getAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (address ret) { ret = address(uint160(uint256(_cache[_key]))); } function getUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (uint256 ret) { ret = uint256(_cache[_key]); } function get(mapping(bytes32 => bytes32) storage _cache, bytes32 _key) internal view returns (bytes32 ret) { ret = _cache[_key]; } } // File: contracts/lib/LibStack.sol pragma solidity ^0.6.0; library LibStack { function setAddress(bytes32[] storage _stack, address _input) internal { _stack.push(bytes32(uint256(uint160(_input)))); } function set(bytes32[] storage _stack, bytes32 _input) internal { _stack.push(_input); } function setHandlerType(bytes32[] storage _stack, Config.HandlerType _input) internal { _stack.push(bytes12(uint96(_input))); } function getAddress(bytes32[] storage _stack) internal returns (address ret) { ret = address(uint160(uint256(peek(_stack)))); _stack.pop(); } function getSig(bytes32[] storage _stack) internal returns (bytes4 ret) { ret = bytes4(peek(_stack)); _stack.pop(); } function get(bytes32[] storage _stack) internal returns (bytes32 ret) { ret = peek(_stack); _stack.pop(); } function peek(bytes32[] storage _stack) internal view returns (bytes32 ret) { require(_stack.length > 0, "stack empty"); ret = _stack[_stack.length - 1]; } } // File: contracts/Storage.sol pragma solidity ^0.6.0; /// @notice A cache structure composed by a bytes32 array contract Storage { using LibCache for mapping(bytes32 => bytes32); using LibStack for bytes32[]; bytes32[] public stack; mapping(bytes32 => bytes32) public cache; // keccak256 hash of "msg.sender" // prettier-ignore bytes32 public constant MSG_SENDER_KEY = 0xb2f2618cecbbb6e7468cc0f2aa43858ad8d153e0280b22285e28e853bb9d453a; // keccak256 hash of "cube.counter" // prettier-ignore bytes32 public constant CUBE_COUNTER_KEY = 0xf9543f11459ccccd21306c8881aaab675ff49d988c1162fd1dd9bbcdbe4446be; modifier isStackEmpty() { require(stack.length == 0, "Stack not empty"); _; } modifier isCubeCounterZero() { require(_getCubeCounter() == 0, "Cube counter not zero"); _; } modifier isInitialized() { require(_getSender() != address(0), "Sender is not initialized"); _; } modifier isNotInitialized() { require(_getSender() == address(0), "Sender is initialized"); _; } function _setSender() internal isNotInitialized { cache.setAddress(MSG_SENDER_KEY, msg.sender); } function _resetSender() internal { cache.setAddress(MSG_SENDER_KEY, address(0)); } function _getSender() internal view returns (address) { return cache.getAddress(MSG_SENDER_KEY); } function _addCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, _getCubeCounter() + 1); } function _resetCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, 0); } function _getCubeCounter() internal view returns (uint256) { return cache.getUint256(CUBE_COUNTER_KEY); } } // File: contracts/handlers/HandlerBase.sol pragma solidity ^0.6.0; abstract contract HandlerBase is Storage, Config { using SafeERC20 for IERC20; function postProcess() external payable virtual { revert("Invalid post process"); /* Implementation template bytes4 sig = stack.getSig(); if (sig == bytes4(keccak256(bytes("handlerFunction_1()")))) { // Do something } else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) { bytes32 temp = stack.get(); // Do something } else revert("Invalid post process"); */ } function _updateToken(address token) internal { stack.setAddress(token); // Ignore token type to fit old handlers // stack.setHandlerType(uint256(HandlerType.Token)); } function _updatePostProcess(bytes32[] memory params) internal { for (uint256 i = params.length; i > 0; i--) { stack.set(params[i - 1]); } stack.set(msg.sig); stack.setHandlerType(HandlerType.Custom); } function getContractName() public pure virtual returns (string memory); function _revertMsg(string memory functionName, string memory reason) internal view { revert( string( abi.encodePacked( _uint2String(_getCubeCounter()), "_", getContractName(), "_", functionName, ": ", reason ) ) ); } function _revertMsg(string memory functionName) internal view { _revertMsg(functionName, "Unspecified"); } function _uint2String(uint256 n) internal pure returns (string memory) { if (n == 0) { return "0"; } else { uint256 len = 0; for (uint256 temp = n; temp > 0; temp /= 10) { len++; } bytes memory str = new bytes(len); for (uint256 i = len; i > 0; i--) { str[i - 1] = bytes1(uint8(48 + (n % 10))); n /= 10; } return string(str); } } function _getBalance(address token, uint256 amount) internal view returns (uint256) { if (amount != uint256(-1)) { return amount; } // ETH case if ( token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ) { return address(this).balance; } // ERC20 token case return IERC20(token).balanceOf(address(this)); } function _tokenApprove( address token, address spender, uint256 amount ) internal { try IERC20Usdt(token).approve(spender, amount) {} catch { IERC20(token).safeApprove(spender, 0); IERC20(token).safeApprove(spender, amount); } } } // File: contracts/handlers/maker/HMaker.sol pragma solidity ^0.6.0; contract HMaker is HandlerBase { using SafeERC20 for IERC20; // prettier-ignore address public constant PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; // prettier-ignore address public constant DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // prettier-ignore address public constant CHAIN_LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; modifier cdpAllowed(uint256 cdp) { IMakerManager manager = IMakerManager(getCdpManager()); address owner = manager.owns(cdp); address sender = _getSender(); if ( IDSProxyRegistry(PROXY_REGISTRY).proxies(sender) != owner && manager.cdpCan(owner, cdp, sender) != 1 ) _revertMsg("General", "Unauthorized sender of cdp"); _; } function getContractName() public pure virtual override returns (string memory) { return "HMaker"; } function getProxyActions() public pure virtual returns (address) { return 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038; } function getCdpManager() public pure virtual returns (address) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } function getMcdJug() public view returns (address) { return IMakerChainLog(CHAIN_LOG).getAddress("MCD_JUG"); } function openLockETHAndDraw( uint256 value, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD ) external payable returns (uint256 cdp) { IDSProxy proxy = IDSProxy(_getProxy(address(this))); // if amount == uint256(-1) return balance of Proxy value = _getBalance(address(0), value); try proxy.execute.value(value)( getProxyActions(), abi.encodeWithSelector( // selector of "openLockETHAndDraw(address,address,address,address,bytes32,uint256)" 0xe685cc04, getCdpManager(), getMcdJug(), ethJoin, daiJoin, ilk, wadD ) ) returns (bytes32 ret) { cdp = uint256(ret); } catch Error(string memory reason) { _revertMsg("openLockETHAndDraw", reason); } catch { _revertMsg("openLockETHAndDraw"); } // Update post process bytes32[] memory params = new bytes32[](1); params[0] = bytes32(cdp); _updatePostProcess(params); } function openLockGemAndDraw( address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD ) external payable returns (uint256 cdp) { IDSProxy proxy = IDSProxy(_getProxy(address(this))); address token = IMakerGemJoin(gemJoin).gem(); // if amount == uint256(-1) return balance of Proxy wadC = _getBalance(token, wadC); IERC20(token).safeApprove(address(proxy), wadC); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "openLockGemAndDraw(address,address,address,address,bytes32,uint256,uint256,bool)" 0xdb802a32, getCdpManager(), getMcdJug(), gemJoin, daiJoin, ilk, wadC, wadD, true ) ) returns (bytes32 ret) { cdp = uint256(ret); } catch Error(string memory reason) { _revertMsg("openLockGemAndDraw", reason); } catch { _revertMsg("openLockGemAndDraw"); } IERC20(token).safeApprove(address(proxy), 0); // Update post process bytes32[] memory params = new bytes32[](1); params[0] = bytes32(cdp); _updatePostProcess(params); } function safeLockETH( uint256 value, address ethJoin, uint256 cdp ) external payable { IDSProxy proxy = IDSProxy(_getProxy(address(this))); address owner = _getProxy(_getSender()); // if amount == uint256(-1) return balance of Proxy value = _getBalance(address(0), value); try proxy.execute.value(value)( getProxyActions(), abi.encodeWithSelector( // selector of "safeLockETH(address,address,uint256,address)" 0xee284576, getCdpManager(), ethJoin, cdp, owner ) ) {} catch Error(string memory reason) { _revertMsg("safeLockETH", reason); } catch { _revertMsg("safeLockETH"); } } function safeLockGem( address gemJoin, uint256 cdp, uint256 wad ) external payable { IDSProxy proxy = IDSProxy(_getProxy(address(this))); address owner = _getProxy(_getSender()); address token = IMakerGemJoin(gemJoin).gem(); // if amount == uint256(-1) return balance of Proxy wad = _getBalance(token, wad); IERC20(token).safeApprove(address(proxy), wad); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "safeLockGem(address,address,uint256,uint256,bool,address)" 0xead64729, getCdpManager(), gemJoin, cdp, wad, true, owner ) ) {} catch Error(string memory reason) { _revertMsg("safeLockGem", reason); } catch { _revertMsg("safeLockGem"); } IERC20(token).safeApprove(address(proxy), 0); } function freeETH( address ethJoin, uint256 cdp, uint256 wad ) external payable cdpAllowed(cdp) { // Check msg.sender authority IDSProxy proxy = IDSProxy(_getProxy(address(this))); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "freeETH(address,address,uint256,uint256)" 0x7b5a3b43, getCdpManager(), ethJoin, cdp, wad ) ) {} catch Error(string memory reason) { _revertMsg("freeETH", reason); } catch { _revertMsg("freeETH"); } } function freeGem( address gemJoin, uint256 cdp, uint256 wad ) external payable cdpAllowed(cdp) { // Check msg.sender authority IDSProxy proxy = IDSProxy(_getProxy(address(this))); address token = IMakerGemJoin(gemJoin).gem(); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "freeGem(address,address,uint256,uint256)" 0x6ab6a491, getCdpManager(), gemJoin, cdp, wad ) ) {} catch Error(string memory reason) { _revertMsg("freeGem", reason); } catch { _revertMsg("freeGem"); } // Update post process _updateToken(token); } function draw( address daiJoin, uint256 cdp, uint256 wad ) external payable cdpAllowed(cdp) { // Check msg.sender authority IDSProxy proxy = IDSProxy(_getProxy(address(this))); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "draw(address,address,address,uint256,uint256)" 0x9f6f3d5b, getCdpManager(), getMcdJug(), daiJoin, cdp, wad ) ) {} catch Error(string memory reason) { _revertMsg("draw", reason); } catch { _revertMsg("draw"); } // Update post process _updateToken(DAI_TOKEN); } function wipe( address daiJoin, uint256 cdp, uint256 wad ) external payable { IDSProxy proxy = IDSProxy(_getProxy(address(this))); IERC20(DAI_TOKEN).safeApprove(address(proxy), wad); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "wipe(address,address,uint256,uint256)" 0x4b666199, getCdpManager(), daiJoin, cdp, wad ) ) {} catch Error(string memory reason) { _revertMsg("wipe", reason); } catch { _revertMsg("wipe"); } IERC20(DAI_TOKEN).safeApprove(address(proxy), 0); } function wipeAll(address daiJoin, uint256 cdp) external payable { IDSProxy proxy = IDSProxy(_getProxy(address(this))); IERC20(DAI_TOKEN).safeApprove(address(proxy), uint256(-1)); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "wipeAll(address,address,uint256)" 0x036a2395, getCdpManager(), daiJoin, cdp ) ) {} catch Error(string memory reason) { _revertMsg("wipeAll", reason); } catch { _revertMsg("wipeAll"); } IERC20(DAI_TOKEN).safeApprove(address(proxy), 0); } function postProcess() external payable override { bytes4 sig = stack.getSig(); // selector of openLockETHAndDraw(uint256,address,address,bytes32,uint256) // and openLockGemAndDraw(address,address,bytes32,uint256,uint256) if (sig == 0x5481e4a4 || sig == 0x73af24e7) { _transferCdp(uint256(stack.get())); uint256 amount = IERC20(DAI_TOKEN).balanceOf(address(this)); if (amount > 0) IERC20(DAI_TOKEN).safeTransfer(_getSender(), amount); } else revert("Invalid post process"); } function _getProxy(address user) internal returns (address) { return IDSProxyRegistry(PROXY_REGISTRY).proxies(user); } function _transferCdp(uint256 cdp) internal { IDSProxy proxy = IDSProxy(_getProxy(address(this))); try proxy.execute( getProxyActions(), abi.encodeWithSelector( // selector of "giveToProxy(address,address,uint256,address)" 0x493c2049, PROXY_REGISTRY, getCdpManager(), cdp, _getSender() ) ) {} catch Error(string memory reason) { _revertMsg("_transferCdp", reason); } catch { _revertMsg("_transferCdp"); } } }
if amount == uint256(-1) return balance of Proxy selector of "safeLockGem(address,address,uint256,uint256,bool,address)"
) external payable { IDSProxy proxy = IDSProxy(_getProxy(address(this))); address owner = _getProxy(_getSender()); address token = IMakerGemJoin(gemJoin).gem(); wad = _getBalance(token, wad); IERC20(token).safeApprove(address(proxy), wad); try proxy.execute( getProxyActions(), abi.encodeWithSelector( 0xead64729, getCdpManager(), gemJoin, cdp, wad, true, owner ) ) _revertMsg("safeLockGem", reason); _revertMsg("safeLockGem"); {} catch Error(string memory reason) { } catch { }
571,138
[ 1, 430, 3844, 422, 2254, 5034, 19236, 21, 13, 327, 11013, 434, 7659, 3451, 434, 315, 4626, 2531, 43, 351, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 11890, 5034, 16, 6430, 16, 2867, 2225, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 3903, 8843, 429, 288, 203, 3639, 1599, 55, 3886, 2889, 273, 1599, 55, 3886, 24899, 588, 3886, 12, 2867, 12, 2211, 3719, 1769, 203, 3639, 1758, 3410, 273, 389, 588, 3886, 24899, 588, 12021, 10663, 203, 3639, 1758, 1147, 273, 6246, 6388, 43, 351, 4572, 12, 23465, 4572, 2934, 23465, 5621, 203, 3639, 341, 361, 273, 389, 588, 13937, 12, 2316, 16, 341, 361, 1769, 203, 3639, 467, 654, 39, 3462, 12, 2316, 2934, 4626, 12053, 537, 12, 2867, 12, 5656, 3631, 341, 361, 1769, 203, 3639, 775, 203, 5411, 2889, 18, 8837, 12, 203, 7734, 18992, 6100, 9334, 203, 7734, 24126, 18, 3015, 1190, 4320, 12, 203, 10792, 374, 92, 684, 30792, 5540, 16, 203, 10792, 1927, 9295, 1318, 9334, 203, 10792, 17474, 4572, 16, 203, 10792, 7976, 84, 16, 203, 10792, 341, 361, 16, 203, 10792, 638, 16, 203, 10792, 3410, 203, 7734, 262, 203, 5411, 262, 203, 5411, 389, 266, 1097, 3332, 2932, 4626, 2531, 43, 351, 3113, 3971, 1769, 203, 5411, 389, 266, 1097, 3332, 2932, 4626, 2531, 43, 351, 8863, 203, 3639, 2618, 1044, 1068, 12, 1080, 3778, 3971, 13, 288, 203, 3639, 289, 1044, 288, 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 ]
// SPDX-License-Identifier: CC0-1.0 pragma solidity >=0.6.0 <0.8.0; import "./StandardToken.sol"; /** * @notice ERC20Token for test scripts, can be minted by anyone. */ contract TestToken is StandardToken { constructor() { } /** * @notice any caller can mint any `_amount` * @param _amount how much to be minted */ function mint(uint256 _amount) public { mint(msg.sender, _amount); } }
* @notice any caller can mint any `_amount` @param _amount how much to be minted/
function mint(uint256 _amount) public { mint(msg.sender, _amount); }
2,473,297
[ 1, 2273, 4894, 848, 312, 474, 1281, 1375, 67, 8949, 68, 225, 389, 8949, 3661, 9816, 358, 506, 312, 474, 329, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 312, 474, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 312, 474, 12, 3576, 18, 15330, 16, 389, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- 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 function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract BTYCToken is ERC20Interface, Owned { using SafeMath for uint; /* string public symbol; string public name; uint8 public decimals; uint _totalSupply;*/ uint256 public sellPrice; //出售价格 1枚代币换多少以太 /1000 uint256 public buyPrice; //购买价格 多少以太可购买1枚代币 /1000 uint256 public sysPrice; //挖矿的衡量值 uint256 public sysPer; //挖矿的增量百分比 /100 uint256 public onceOuttime; //增量的时间 测试 uint256 public onceAddTime; //挖矿的时间 测试 uint256 public onceoutTimePer; //增量的百分比 测试 mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /* 冻结账户 */ mapping(address => bool) public frozenAccount; // 记录各个账户的冻结数目 //mapping(address => uint256) public freezeOf; // 记录各个账户的可用数目 mapping(address => uint256) public canOf; // 记录各个账户的释放时间 mapping(address => uint) public cronoutOf; // 记录各个账户的增量时间 mapping(address => uint) public cronaddOf; /* 通知 */ event FrozenFunds(address target, bool frozen); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public{ sellPrice = 510; //出售价格 1枚代币换多少以太 /1000000 buyPrice = 526; //购买价格 多少以太可购买1枚代币 /1000000 sysPrice = 766; //挖矿的衡量值 sysPer = 225; //挖矿的增量百分比 /100 //onceOuttime = 86400; //增量的时间 正式 //onceAddTime = 864000; //挖矿的时间 正式 //onceoutTimePer = 8640000; //增量的百分比 正式 onceOuttime = 600; //增量的时间 测试 onceAddTime = 1800; //挖矿的时间 测试 onceoutTimePer = 60000; //增量的百分比 测试 } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function canuseOf(address tokenOwner) public view returns (uint balance) { return canOf[tokenOwner]; } function myuseOf(address tokenOwner) public returns (uint balance) { //return balances[tokenOwner]; if(cronoutOf[tokenOwner] < 1) { return 0; }else{ uint lefttimes = now - cronoutOf[tokenOwner]; if(lefttimes >= onceOuttime) { uint leftpers = lefttimes / onceoutTimePer; if(leftpers > 1) { leftpers = 1; } canOf[tokenOwner] = balances[tokenOwner] * leftpers; return canOf[tokenOwner]; }else{ return canOf[tokenOwner]; } } } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!frozenAccount[msg.sender]); require(!frozenAccount[to]); canOf[msg.sender] = myuseOf(msg.sender); canOf[msg.sender] = canOf[msg.sender].sub(tokens); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } /* function buytoken(address user, uint256 amount) public{ balances[user] = balances[user].sub(amount); //buyeth(amount); emit Transfer(address(0), user, amount); }*/ // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ 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 mintToken(address target, uint256 mintedAmount) onlyOwner public { require(!frozenAccount[target]); if(cronoutOf[target] < 1) { cronoutOf[target] = now + onceOuttime; } if(cronaddOf[target] < 1) { cronaddOf[target] = now + onceAddTime; } balances[target] += mintedAmount; uint256 amounts = mintedAmount / 100; canOf[target] += amounts; //emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } //用户每隔10天挖矿一次 function mint() public { require(!frozenAccount[msg.sender]); require(cronaddOf[msg.sender] > 0 && now > cronaddOf[msg.sender]); uint256 mintAmount = balances[msg.sender] * sysPer / 10000; balances[msg.sender] += mintAmount; cronaddOf[msg.sender] = now + onceAddTime; //emit Transfer(0, this, mintAmount); emit Transfer(this, msg.sender, mintAmount); } /// 冻结 or 解冻账户 function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } // 设置销售购买价格 function setPrices( uint256 newBuyPrice, uint256 newSellPrice, uint256 systyPrice, uint256 sysPermit) onlyOwner public { buyPrice = newBuyPrice; sellPrice = newSellPrice; sysPrice = systyPrice; sysPer = sysPermit; } // 获取价格 function getprice() public view returns (uint256 bprice,uint256 spice,uint256 sprice,uint256 sper) { bprice = buyPrice; spice = sellPrice; sprice = sysPrice; sper = sysPer; } } contract BTYC is BTYCToken{ string public symbol; string public name; uint8 public decimals; uint _totalSupply; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public{ symbol = "BYTCT"; name = "BYTYCT Coin"; decimals = 18; _totalSupply = 1000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function buy(uint money) public payable { require(!frozenAccount[msg.sender]); uint amount = money / buyPrice; balances[msg.sender] += amount; msg.sender.transfer(money); } /* function selleth(uint amount) public payable { //address user = msg.sender; //canOf[user] = myuseOf(user); //require(balances[user] >= amount ); //uint money = amount * sellPrice; // balances[msg.sender] += money; owner.transfer(amount); }*/ function sell(uint amount) public returns (bool success){ //address user = msg.sender; //canOf[msg.sender] = myuseOf(msg.sender); //require(!frozenAccount[msg.sender]); require(canOf[msg.sender] >= amount ); balances[msg.sender] -= amount; canOf[msg.sender] -= amount; uint moneys = amount / sellPrice; owner.transfer(moneys); //canOf[user] -= amount; return true; } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to `to` account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) { require(!frozenAccount[msg.sender]); require(!frozenAccount[to]); canOf[msg.sender] = myuseOf(msg.sender); canOf[msg.sender] = canOf[msg.sender].sub(tokens); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
1,758,876
[ 1, 29461, 12279, 326, 11013, 628, 1147, 3410, 1807, 2236, 358, 1375, 869, 68, 2236, 300, 16837, 1807, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 5, 28138, 3032, 63, 3576, 18, 15330, 19226, 203, 3639, 2583, 12, 5, 28138, 3032, 63, 869, 19226, 203, 3639, 848, 951, 63, 3576, 18, 15330, 65, 273, 3399, 1202, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 848, 951, 63, 3576, 18, 15330, 65, 273, 848, 951, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 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, -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 "lib/Addresses.sol"; /** * This is a manual set of tests, but I would suggest using Truffle if you * develop outside of remix * * WARNING: This is extremely gas heavy and should not be published to the * blockchain! */ contract AddressesTests { using Addresses for address; function testIsContract() public { assert(address(this).isContract()); assert(!msg.sender.isContract()); } }
* This is a manual set of tests, but I would suggest using Truffle if you develop outside of remix WARNING: This is extremely gas heavy and should not be published to the blockchain!/
contract AddressesTests { using Addresses for address; function testIsContract() public { assert(address(this).isContract()); assert(!msg.sender.isContract()); } }
15,790,914
[ 1, 2503, 353, 279, 11297, 444, 434, 7434, 16, 1496, 467, 4102, 19816, 1450, 840, 10148, 309, 1846, 17196, 8220, 434, 849, 697, 9744, 30, 1220, 353, 23755, 2357, 16189, 3904, 23935, 471, 1410, 486, 506, 9487, 358, 326, 16766, 5, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 23443, 14650, 288, 203, 565, 1450, 23443, 364, 1758, 31, 203, 203, 565, 445, 1842, 2520, 8924, 1435, 1071, 288, 203, 3639, 1815, 12, 2867, 12, 2211, 2934, 291, 8924, 10663, 203, 3639, 1815, 12, 5, 3576, 18, 15330, 18, 291, 8924, 10663, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xFe06df139FD9291a218c468a2e318e84b5cF4328/sources/IFOV.sol
* @notice External view function to see user allocations for both pools @param _user: user address @param _pids[]: array of pids @return/
function viewUserAllocationPools(address _user, uint8[] calldata _pids) external view override returns (uint256[] memory) { uint256[] memory allocationPools = new uint256[](_pids.length); for (uint8 i = 0; i < _pids.length; i++) { allocationPools[i] = _getUserAllocationPool(_user, _pids[i]); } return allocationPools; }
3,755,880
[ 1, 6841, 1476, 445, 358, 2621, 729, 23804, 364, 3937, 16000, 225, 389, 1355, 30, 729, 1758, 225, 389, 84, 2232, 8526, 30, 526, 434, 20726, 327, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1476, 1299, 17353, 16639, 12, 2867, 389, 1355, 16, 2254, 28, 8526, 745, 892, 389, 84, 2232, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 13, 203, 565, 288, 203, 3639, 2254, 5034, 8526, 3778, 13481, 16639, 273, 394, 2254, 5034, 8526, 24899, 84, 2232, 18, 2469, 1769, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 389, 84, 2232, 18, 2469, 31, 277, 27245, 288, 203, 5411, 13481, 16639, 63, 77, 65, 273, 389, 588, 1299, 17353, 2864, 24899, 1355, 16, 389, 84, 2232, 63, 77, 19226, 203, 3639, 289, 203, 3639, 327, 13481, 16639, 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 ]
./full_match/82/0x45099f895561d6EE4f41aa2D567187AC7aAa6c29/sources/contracts/access/Ownable.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 public _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _transferOwnership(_msgSender()); } modifier onlyOwner() { _checkOwner(); _; } function owner() public view virtual returns (address) { return _owner; } function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
7,094,013
[ 1, 8924, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 1758, 1071, 389, 8443, 31, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 565, 1758, 8808, 2416, 5541, 16, 203, 565, 1758, 8808, 394, 5541, 203, 225, 11272, 203, 203, 203, 225, 3885, 1435, 288, 203, 565, 389, 13866, 5460, 12565, 24899, 3576, 12021, 10663, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 389, 1893, 5541, 5621, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 3410, 1435, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 565, 327, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 445, 389, 1893, 5541, 1435, 2713, 1476, 5024, 288, 203, 565, 2583, 12, 8443, 1435, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 225, 289, 203, 203, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 565, 389, 13866, 5460, 12565, 12, 2867, 12, 20, 10019, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 5024, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 5460, 429, 30, 394, 3410, 353, 326, 3634, 1758, 8863, 203, 565, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 5024, 288, 203, 565, 1758, 1592, 5541, 273, 389, 8443, 31, 203, 565, 389, 8443, 273, 394, 5541, 31, 203, 2 ]
./full_match/41/0x372Ba972B7337773d6040953De8aeEa72181Cb7d/sources/contracts/protocol/lendingpool/LendingPoolCollateralManager.sol
* @dev Function to liquidate a position if its Health Factor drops below 1 - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives a proportionally amount of the `collateralAsset` plus a bonus to cover market risk @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation @param user The address of the borrower getting liquidated @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover @param receiveViToken `true` if the liquidators wants to receive the collateral viTokens, `false` if he wants to receive the underlying collateral asset directly/ If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the collateral reserve If the user doesn't have variable debt, no need to try to burn variable debt tokens If the collateral being liquidated is equal to the user balance, we set the currency as not being used as collateral anymore
function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveViToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralVitoken = IViToken(collateralReserve.viTokenAddress); vars.userCollateralBalance = vars.collateralVitoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } if (!receiveViToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf( address(vars.collateralVitoken) ); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableVdToken(debtReserve.variableVdTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); if (vars.userVariableDebt > 0) { IVariableVdToken(debtReserve.variableVdTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableVdToken(debtReserve.stableVdTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.viTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveViToken) { vars.liquidatorPreviousViTokenBalance = IERC20(vars.collateralVitoken).balanceOf(msg.sender); vars.collateralVitoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousViTokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralVitoken), 0, vars.maxCollateralToLiquidate ); user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } msg.sender, debtReserve.viTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveViToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); }
16,370,151
[ 1, 2083, 358, 4501, 26595, 340, 279, 1754, 309, 2097, 11745, 26400, 29535, 5712, 404, 300, 1021, 4894, 261, 549, 26595, 639, 13, 25559, 1375, 323, 23602, 774, 8084, 68, 3844, 434, 18202, 88, 434, 326, 729, 8742, 4501, 26595, 690, 16, 471, 17024, 282, 279, 23279, 1230, 3844, 434, 326, 1375, 12910, 2045, 287, 6672, 68, 8737, 279, 324, 22889, 358, 5590, 13667, 18404, 225, 4508, 2045, 287, 6672, 1021, 1758, 434, 326, 6808, 3310, 1399, 487, 4508, 2045, 287, 16, 358, 6798, 487, 563, 434, 326, 4501, 26595, 367, 225, 18202, 88, 6672, 1021, 1758, 434, 326, 6808, 29759, 329, 3310, 358, 506, 2071, 20736, 598, 326, 4501, 26595, 367, 225, 729, 1021, 1758, 434, 326, 29759, 264, 8742, 4501, 26595, 690, 225, 18202, 88, 774, 8084, 1021, 18202, 88, 3844, 434, 29759, 329, 1375, 9406, 68, 326, 4501, 26595, 639, 14805, 358, 5590, 225, 6798, 58, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 4501, 26595, 367, 1477, 12, 203, 565, 1758, 4508, 2045, 287, 6672, 16, 203, 565, 1758, 18202, 88, 6672, 16, 203, 565, 1758, 729, 16, 203, 565, 2254, 5034, 18202, 88, 774, 8084, 16, 203, 565, 1426, 6798, 58, 77, 1345, 203, 225, 262, 3903, 3849, 1135, 261, 11890, 5034, 16, 533, 3778, 13, 288, 203, 565, 1910, 2016, 18, 607, 6527, 751, 2502, 4508, 2045, 287, 607, 6527, 273, 389, 455, 264, 3324, 63, 12910, 2045, 287, 6672, 15533, 203, 565, 1910, 2016, 18, 607, 6527, 751, 2502, 18202, 88, 607, 6527, 273, 389, 455, 264, 3324, 63, 323, 23602, 6672, 15533, 203, 565, 1910, 2016, 18, 1299, 1750, 863, 2502, 729, 809, 273, 389, 5577, 809, 63, 1355, 15533, 203, 203, 565, 511, 18988, 350, 367, 1477, 2042, 5555, 3778, 4153, 31, 203, 203, 565, 261, 16, 269, 269, 269, 4153, 18, 13267, 6837, 13, 273, 7928, 20556, 18, 11162, 1299, 3032, 751, 12, 203, 1377, 729, 16, 203, 1377, 389, 455, 264, 3324, 16, 203, 1377, 729, 809, 16, 203, 1377, 389, 455, 264, 3324, 682, 16, 203, 1377, 389, 455, 264, 3324, 1380, 16, 203, 1377, 389, 13277, 2249, 18, 588, 5147, 23601, 1435, 203, 565, 11272, 203, 203, 565, 261, 4699, 18, 1355, 30915, 758, 23602, 16, 4153, 18, 1355, 3092, 758, 23602, 13, 273, 17090, 18, 588, 1299, 3935, 758, 23602, 12, 1355, 16, 18202, 88, 607, 6527, 1769, 203, 203, 565, 261, 4699, 18, 27754, 16, 4153, 18, 1636, 3332, 13, 273, 5684, 20556, 18, 2 ]
pragma solidity ^0.4.24; /** * @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 SafeERC20Transfer { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } } /** * @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; } } /** * @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() public { _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; } } /** * @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 SafeERC20Transfer 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 1 ETH. uint256 private _rate = 5000; // Amount of wei raised uint256 private _weiRaised; // Accrued tokens amount uint256 private _accruedTokensAmount; // freezing periods in seconds uint256 private _threeMonths = 5256000; uint256 private _sixMonths = 15768000; uint256 private _nineMonths = 21024000; uint256 private _twelveMonths = 31536000; // ICO configuration uint256 private _foundersTokens = 4e7; uint256 private _distributedTokens = 1e9; uint256 public softCap = 1000 ether; uint256 public hardCap = 35000 ether; uint256 public preICO_1_Start = 1541030400; // 01/11/2018 00:00:00 uint256 public preICO_2_Start = 1541980800; // 12/11/2018 00:00:00 uint256 public preICO_3_Start = 1542844800; // 22/11/2018 00:00:00 uint256 public ICO_Start = 1543622400; // 01/12/2018 00:00:00 uint256 public ICO_End = 1548979199; // 31/01/2019 23:59:59 uint32 public bonus1 = 30; // pre ICO phase 1 uint32 public bonus2 = 20; // pre ICO phase 2 uint32 public bonus3 = 10; // pre ICO phase 3 uint32 public whitelistedBonus = 10; mapping (address => bool) private _whitelist; // tokens accrual mapping (address => uint256) public threeMonthsFreezingAccrual; mapping (address => uint256) public sixMonthsFreezingAccrual; mapping (address => uint256) public nineMonthsFreezingAccrual; mapping (address => uint256) public twelveMonthsFreezingAccrual; // investors ledger mapping (address => uint256) public ledger; /** * Event for tokens accrual logging * @param to who tokens where accrued to * @param accruedAmount amount of tokens accrued * @param freezingTime period for freezing in seconds * @param purchasedAmount amount of tokens purchased * @param weiValue amount of ether contributed */ event Accrual( address to, uint256 accruedAmount, uint256 freezingTime, uint256 purchasedAmount, uint256 weiValue ); /** * Event for accrued tokens releasing logging * @param to who tokens where release to * @param amount amount of tokens released */ event Released( address to, uint256 amount ); /** * Event for refund logging * @param to who have got refund * @param value ether refunded */ event Refunded( address to, uint256 value ); /** * 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 ); /** * @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 founders Address for founders tokens accrual * @param token Address of the token being sold */ constructor(address newOwner, address wallet, address founders, IERC20 token) public { require(wallet != address(0)); require(founders != address(0)); require(token != address(0)); require(newOwner != address(0)); transferOwnership(newOwner); _wallet = wallet; _token = token; twelveMonthsFreezingAccrual[founders] = _foundersTokens; _accruedTokensAmount = _foundersTokens; emit Accrual(founders, _foundersTokens, _twelveMonths, 0, 0); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ 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; } /** * @return if who is whitelisted. * @param who investors address */ function whitelist(address who) public view returns (bool) { return _whitelist[who]; } /** * add investor to whitelist * @param who investors address */ function addToWhitelist(address who) public onlyOwner { _whitelist[who] = true; } /** * remove investor from whitelist * @param who investors address */ function removeFromWhitelist(address who) public onlyOwner { _whitelist[who] = false; } /** * Accrue bonuses to advisors * @param to address for accrual * @param amount tokem amount */ function accrueAdvisorsTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); sixMonthsFreezingAccrual[to] = sixMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _sixMonths, 0, 0); } /** * Accrue bonuses to partners * @param to address for accrual * @param amount tokem amount */ function accruePartnersTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); nineMonthsFreezingAccrual[to] = nineMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _nineMonths, 0, 0); } /** * Accrue bounty and airdrop bonuses * @param to address for accrual * @param amount tokem amount */ function accrueBountyTokens(address to, uint256 amount) public onlyOwner { require(now > ICO_End); uint256 tokenBalance = _token.balanceOf(address(this)); require(tokenBalance >= _accruedTokensAmount.add(amount)); _accruedTokensAmount = _accruedTokensAmount.add(amount); twelveMonthsFreezingAccrual[to] = twelveMonthsFreezingAccrual[to].add(amount); emit Accrual(to, amount, _twelveMonths, 0, 0); } /** * release accrued tokens */ function release() public { address who = msg.sender; uint256 amount; if (now > ICO_End.add(_twelveMonths) && twelveMonthsFreezingAccrual[who] > 0) { amount = amount.add(twelveMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(twelveMonthsFreezingAccrual[who]); twelveMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_nineMonths) && nineMonthsFreezingAccrual[who] > 0) { amount = amount.add(nineMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(nineMonthsFreezingAccrual[who]); nineMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_sixMonths) && sixMonthsFreezingAccrual[who] > 0) { amount = amount.add(sixMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(sixMonthsFreezingAccrual[who]); sixMonthsFreezingAccrual[who] = 0; } if (now > ICO_End.add(_threeMonths) && threeMonthsFreezingAccrual[who] > 0) { amount = amount.add(threeMonthsFreezingAccrual[who]); _accruedTokensAmount = _accruedTokensAmount.sub(threeMonthsFreezingAccrual[who]); threeMonthsFreezingAccrual[who] = 0; } if (amount > 0) { _deliverTokens(who, amount); emit Released(who, amount); } } /** * refund ether */ function refund() public { address investor = msg.sender; require(now > ICO_End); require(_weiRaised < softCap); require(ledger[investor] > 0); uint256 value = ledger[investor]; ledger[investor] = 0; investor.transfer(value); emit Refunded(investor, value); } /** * @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); // bonus tokens accrual and ensure token balance is enough for accrued tokens release _accrueBonusTokens(beneficiary, tokens, weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); if (_weiRaised >= softCap) _forwardFunds(); ledger[msg.sender] = ledger[msg.sender].add(msg.value); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Accrue bonus tokens. * @param beneficiary Address for tokens accrual * @param tokenAmount amount of tokens that beneficiary get */ function _accrueBonusTokens(address beneficiary, uint256 tokenAmount, uint256 weiAmount) internal { uint32 bonus = 0; uint256 bonusTokens = 0; uint256 tokenBalance = _token.balanceOf(address(this)); if (_whitelist[beneficiary] && now < ICO_Start) bonus = bonus + whitelistedBonus; if (now < preICO_2_Start) { bonus = bonus + bonus1; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); nineMonthsFreezingAccrual[beneficiary] = nineMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _nineMonths, tokenAmount, weiAmount); } else if (now < preICO_3_Start) { bonus = bonus + bonus2; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); sixMonthsFreezingAccrual[beneficiary] = sixMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _sixMonths, tokenAmount, weiAmount); } else if (now < ICO_Start) { bonus = bonus + bonus3; bonusTokens = tokenAmount.mul(bonus).div(100); require(tokenBalance >= _accruedTokensAmount.add(bonusTokens).add(tokenAmount)); _accruedTokensAmount = _accruedTokensAmount.add(bonusTokens); threeMonthsFreezingAccrual[beneficiary] = threeMonthsFreezingAccrual[beneficiary].add(bonusTokens); emit Accrual(beneficiary, bonusTokens, _threeMonths, tokenAmount, weiAmount); } else { require(tokenBalance >= _accruedTokensAmount.add(tokenAmount)); emit Accrual(beneficiary, 0, 0, tokenAmount, weiAmount); } } /** * @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); require(_weiRaised.add(weiAmount) <= hardCap); require(now >= preICO_1_Start); require(now <= ICO_End); } /** * @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. 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 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).div(1e18); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { uint256 balance = address(this).balance; _wallet.transfer(balance); } }
* @dev low level token purchase DO NOT OVERRIDE @param beneficiary Address performing the token purchase/ calculate token amount to be created bonus tokens accrual and ensure token balance is enough for accrued tokens release update state
function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _accrueBonusTokens(beneficiary, tokens, weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); if (_weiRaised >= softCap) _forwardFunds(); ledger[msg.sender] = ledger[msg.sender].add(msg.value); }
12,909,233
[ 1, 821, 1801, 1147, 23701, 5467, 4269, 22577, 25382, 225, 27641, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 19, 4604, 1147, 3844, 358, 506, 2522, 324, 22889, 2430, 4078, 86, 1462, 471, 3387, 1147, 11013, 353, 7304, 364, 4078, 86, 5957, 2430, 3992, 1089, 919, 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, 225, 445, 30143, 5157, 12, 2867, 27641, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 565, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 565, 389, 1484, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 565, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 1769, 203, 203, 565, 389, 8981, 86, 344, 38, 22889, 5157, 12, 70, 4009, 74, 14463, 814, 16, 2430, 16, 732, 77, 6275, 1769, 203, 203, 565, 389, 1814, 77, 12649, 5918, 273, 389, 1814, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 203, 565, 389, 2567, 23164, 12, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 565, 3626, 13899, 10262, 343, 8905, 12, 203, 1377, 1234, 18, 15330, 16, 203, 1377, 27641, 74, 14463, 814, 16, 203, 1377, 732, 77, 6275, 16, 203, 1377, 2430, 203, 565, 11272, 203, 203, 565, 309, 261, 67, 1814, 77, 12649, 5918, 1545, 8971, 4664, 13, 389, 11565, 42, 19156, 5621, 203, 203, 565, 16160, 63, 3576, 18, 15330, 65, 273, 16160, 63, 3576, 18, 15330, 8009, 1289, 12, 3576, 18, 1132, 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 ]
./full_match/1/0x83f1C175cECC31E71283a87A2878B1040118ff38/sources/browser/BBRPool.sol
Update dev address by the previous dev.
function setEndBlock(uint256 blockNumber) public onlyOwner { endBlock = blockNumber; }
3,028,114
[ 1, 1891, 4461, 1758, 635, 326, 2416, 4461, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 19743, 1768, 12, 11890, 5034, 1203, 1854, 13, 1071, 1338, 5541, 288, 203, 3639, 679, 1768, 273, 1203, 1854, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ bool private operational = true; // Blocks all state changes throughout the contract if false // Access control variables address private contractOwner; // Account used to deploy contract mapping(address => bool) private authorizedCallers; // Contract Owner and Funded Airlines to be authorized address[] private airlines; mapping(address => Airline) private airlineData; bytes32[] private flights; mapping(bytes32 => Flight) private flightsData; mapping(address => uint256) private availableWithdrawals; struct Airline { string name; address airlineAddress; AirlineStatus status; uint256 funds; mapping(address => bool) approvers; uint8 numApprovers; } struct Flight { string flightCode; uint8 statusCode; uint256 scheduledTimestamp; address airlineAddress; mapping(address => Insurance) insurances; address[] insurees; bool isProcessed; } struct Insurance { address ownerAddress; uint256 value; uint8 multiplier; uint8 divider; } enum AirlineStatus { New, Nominated, Registered, Funded } /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(string _airlineName, address _airlineAddress) public { contractOwner = msg.sender; authorizedCallers[msg.sender] = true; // Ensure contractOwner is authorized // First airline should automatically be registered nominateAirline(contractOwner, _airlineName, _airlineAddress); registerAirline(_airlineAddress); } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // event AirlineRegistered(address indexed airlineAddress); // event AirlineFunded(address airlineAddress); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational == true, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the caller to be authorized */ modifier requireAuthorizedCaller() { require( authorizedCallers[msg.sender] == true, "Caller is not authorized" ); _; } modifier requireAirlineIsRegistered(address _airlineAddress) { require(airlineData[_airlineAddress].status >= AirlineStatus.Registered); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() external view requireAuthorizedCaller returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireAuthorizedCaller { operational = mode; } function authorizeCaller(address _address) external requireIsOperational requireContractOwner { authorizedCallers[_address] = true; } function deauthorizeCaller(address _address) external requireIsOperational requireContractOwner { authorizedCallers[_address] = false; } function isAuthorized(address _address) external view requireIsOperational returns (bool) { return authorizedCallers[_address]; } function isAirline(address _address) public view requireIsOperational requireAuthorizedCaller returns (bool) { return airlineData[_address].airlineAddress > address(0); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ function getAirlines() public view returns(address[]) { return airlines; } function getAirlineData(address _airlineAddress) public view returns(string, address, string, uint256, uint8) { Airline storage _airlineData = airlineData[_airlineAddress]; return (_airlineData.name ,_airlineData.airlineAddress, getReadableAirlineStatus(_airlineAddress), _airlineData.funds, _airlineData.numApprovers); } function nominateAirline(address _from, string _name, address _airlineAddress) public requireIsOperational requireAuthorizedCaller returns(string, address, string, uint256, uint8) { // TODO: require not being nominated before airlineData[_airlineAddress] = Airline( _name, _airlineAddress, AirlineStatus.New, 0, // No funding when started 0 ); airlines.push(_airlineAddress); // Whoever nominates an airline also approves it initially approveAirline(_from, _airlineAddress); return getAirlineData(_airlineAddress); } function approveAirline(address _from, address _airlineAddress) public requireIsOperational requireAuthorizedCaller returns (uint8) { // Ensure each Airline has only a single vote for approval per airline require( airlineData[_airlineAddress].approvers[_from] != true, "Vote ignored. You only have a single vote per Airline." ); airlineData[_airlineAddress].approvers[_from] = true; airlineData[_airlineAddress].numApprovers++; return airlineData[_airlineAddress].numApprovers; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address _airlineAddress) public requireIsOperational requireAuthorizedCaller { airlineData[_airlineAddress].status = AirlineStatus.Registered; } function getReadableAirlineStatus(address _airlineAddress) public view returns(string) { AirlineStatus _status = getAirlineStatus(_airlineAddress); if (AirlineStatus.New == _status) return "New"; if (AirlineStatus.Nominated == _status) return "Nominated"; if (AirlineStatus.Registered == _status) return "Registered"; if (AirlineStatus.Funded == _status) return "Funded"; // else return "Unknown"; } function getAirlineStatus(address _airlineAddress) internal view requireIsOperational requireAuthorizedCaller returns (AirlineStatus) { return airlineData[_airlineAddress].status; } function setAirlineStatus(address _airlineAddress, AirlineStatus status) internal requireIsOperational requireAuthorizedCaller { airlineData[_airlineAddress].status = status; } function getAirlineFunds(address _airlineAddress) public view requireIsOperational requireAuthorizedCaller returns (uint256) { return airlineData[_airlineAddress].funds; } function setAirlineFundingStatusByThreshold(address _airlineAddress, uint256 fundingThreshold) external { uint256 currentFunds = getAirlineFunds(_airlineAddress); if(currentFunds >= fundingThreshold) { setAirlineStatus(_airlineAddress, AirlineStatus.Funded); } else { setAirlineStatus(_airlineAddress, AirlineStatus.Registered); } } /** Flight Functions */ function getFlights() external view requireIsOperational returns(bytes32[]) { return flights; } function getFlightData(bytes32 key) external view requireIsOperational returns(address, string, uint256, uint8, bool) { Flight memory flight = flightsData[key]; return (flight.airlineAddress, flight.flightCode, flight.scheduledTimestamp, flight.statusCode, flight.isProcessed); } function registerFlight( address _airlineAddress, string _flightCode, uint256 _timestamp, uint8 _statusCode ) external requireIsOperational { bytes32 key = getFlightKey(_airlineAddress, _flightCode, _timestamp); require( flightsData[key].airlineAddress == address(0), "Flight is already registered" ); flightsData[key] = Flight( _flightCode, _statusCode, _timestamp, _airlineAddress, new address[](0), false ); flights.push(key); } function setFlightStatus( address _airlineAddress, string _flightCode, uint256 _timestamp, uint8 _statusCode ) external requireIsOperational requireAuthorizedCaller { bytes32 flightKey = getFlightKey(_airlineAddress, _flightCode, _timestamp); require( flightsData[flightKey].airlineAddress != address(0), "Flight is not registered" ); flightsData[flightKey].statusCode = _statusCode; } function getInsuranceBalance(address _insuree, address _airline, string _flightCode, uint256 _timestamp) public requireIsOperational requireAuthorizedCaller returns(uint256) { bytes32 flightKey = getFlightKey(_airline, _flightCode, _timestamp); return flightsData[flightKey].insurances[_insuree].value; } /** * @dev Buy insurance for a flight * */ function buy( address _from, address airline, string flightCode, uint256 timestamp, uint8 multiplier, uint8 divider ) external payable { bytes32 flightKey = getFlightKey(airline, flightCode, timestamp); require( flightsData[flightKey].airlineAddress != address(0), "Flight is not registered" ); Insurance memory currentInsurance = flightsData[flightKey].insurances[ _from ]; if (currentInsurance.ownerAddress == address(0)) { // a new insurance Insurance memory newInsurance = Insurance( _from, msg.value, multiplier, divider ); flightsData[flightKey].insurances[_from] = newInsurance; flightsData[flightKey].insurees.push(_from); } else { // an existing insurance flightsData[flightKey].insurances[_from].value = currentInsurance.value + msg.value; } } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, string flightCode, uint256 timestamp) external requireIsOperational requireAuthorizedCaller { bytes32 flightKey = getFlightKey(airline, flightCode, timestamp); require( !flightsData[flightKey].isProcessed, "Flight is already processed." ); Flight storage flight = flightsData[flightKey]; for (uint256 i = 0; i < flight.insurees.length; i++) { address insuranceOwner = flight.insurees[i]; Insurance memory curInsurance = flight.insurances[insuranceOwner]; uint256 insuranceValue = curInsurance.value; uint256 insuranceRefund = insuranceValue .mul(curInsurance.multiplier) .div(curInsurance.divider); availableWithdrawals[ curInsurance.ownerAddress ] = availableWithdrawals[curInsurance.ownerAddress].add( insuranceRefund ); airlineData[flight.airlineAddress].funds.sub(insuranceRefund); } flight.isProcessed = true; } function getWithdrawableBalance(address _from) external view requireIsOperational returns (uint256) { return availableWithdrawals[_from]; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address insuranceOwnerAddress, uint256 amount) external payable requireIsOperational requireAuthorizedCaller { require( availableWithdrawals[insuranceOwnerAddress] > 0, "Nothing to withdraw." ); require( amount <= availableWithdrawals[insuranceOwnerAddress], "Requested amount exceeds eligible amount." ); availableWithdrawals[insuranceOwnerAddress] = availableWithdrawals[ insuranceOwnerAddress ].sub(amount); insuranceOwnerAddress.transfer(amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address _from) public payable requireIsOperational requireAirlineIsRegistered(_from) returns(uint256) { uint256 currentFunds = airlineData[_from].funds; airlineData[_from].funds = currentFunds.add(msg.value); return airlineData[_from].funds; } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
* @dev Transfers eligible payout funds to insuree/
function pay(address insuranceOwnerAddress, uint256 amount) external payable requireIsOperational requireAuthorizedCaller { require( availableWithdrawals[insuranceOwnerAddress] > 0, "Nothing to withdraw." ); require( amount <= availableWithdrawals[insuranceOwnerAddress], "Requested amount exceeds eligible amount." ); availableWithdrawals[insuranceOwnerAddress] = availableWithdrawals[ insuranceOwnerAddress ].sub(amount); insuranceOwnerAddress.transfer(amount); }
976,168
[ 1, 1429, 18881, 21351, 293, 2012, 284, 19156, 358, 316, 2055, 73, 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 ]
[ 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, 8843, 12, 2867, 2763, 295, 1359, 5541, 1887, 16, 2254, 5034, 3844, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 2583, 2520, 2988, 287, 203, 3639, 2583, 15341, 11095, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 2319, 1190, 9446, 1031, 63, 2679, 295, 1359, 5541, 1887, 65, 405, 374, 16, 203, 5411, 315, 23814, 358, 598, 9446, 1199, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 3844, 1648, 2319, 1190, 9446, 1031, 63, 2679, 295, 1359, 5541, 1887, 6487, 203, 5411, 315, 11244, 3844, 14399, 21351, 3844, 1199, 203, 3639, 11272, 203, 3639, 2319, 1190, 9446, 1031, 63, 2679, 295, 1359, 5541, 1887, 65, 273, 2319, 1190, 9446, 1031, 63, 203, 5411, 2763, 295, 1359, 5541, 1887, 203, 3639, 308, 18, 1717, 12, 8949, 1769, 203, 3639, 2763, 295, 1359, 5541, 1887, 18, 13866, 12, 8949, 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 ]
./full_match/1/0x4A7AAce1B48905560Fd8d33D536461bE6fF00F6d/sources/contracts/XRP2_Staking.sol
Withdraw reward. EMERGENCY ONLY.
function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { require(_amount < xrp2.balanceOf(address(this)), 'not enough token'); xrp2.safeTransfer(address(msg.sender), _amount); }
16,468,922
[ 1, 1190, 9446, 19890, 18, 7141, 654, 16652, 16068, 20747, 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, 801, 24530, 17631, 1060, 1190, 9446, 12, 11890, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 8949, 411, 619, 13832, 22, 18, 12296, 951, 12, 2867, 12, 2211, 13, 3631, 296, 902, 7304, 1147, 8284, 203, 3639, 619, 13832, 22, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 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 ]
//SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity 0.8.2; import "../../../asset/ERC1155ERC721.sol"; import "@openzeppelin/contracts-0.8/utils/Address.sol"; // solhint-disable-next-line no-empty-blocks contract PolygonAssetV2 is ERC1155ERC721 { using Address for address; address private _childChainManager; event ChainExit(address indexed to, uint256[] tokenIds, uint256[] amounts, bytes data); /// @notice fulfills the purpose of a constructor in upgradeabale contracts function initialize( address trustedForwarder, address admin, address bouncerAdmin, address childChainManager, uint8 chainIndex ) external { require(trustedForwarder.isContract(), "TRUSTERFORWARDER_NOT_CONTRACT"); require(childChainManager.isContract(), "CHILDCHAINMANAGER_NOT_CONTRACT"); initV2(trustedForwarder, admin, bouncerAdmin, address(0), chainIndex); _childChainManager = childChainManager; } /// @notice called when tokens are deposited on root chain /// @dev Should be callable only by ChildChainManager /// @dev Should handle deposit by minting the required tokens for user /// @dev Make sure minting is done only by this function /// @param user user address for whom deposit is being done /// @param depositData abi encoded ids array and amounts array function deposit(address user, bytes calldata depositData) external { require(_msgSender() == _childChainManager, "!DEPOSITOR"); require(user != address(0), "INVALID_DEPOSIT_USER"); (uint256[] memory ids, uint256[] memory amounts, bytes memory data) = abi.decode(depositData, (uint256[], uint256[], bytes)); address sender = _msgSender(); bytes32 hash = abi.decode(data, (bytes32)); for (uint256 i = 0; i < ids.length; i++) { // ERC-721 if ((amounts[i] == 1) && (ids[i] & IS_NFT > 0)) { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } // ERC-1155 else { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } } } /// @notice called when user wants to withdraw tokens back to root chain /// @dev Should burn user's tokens. This transaction will be verified when exiting on root chain /// @param ids ids to withdraw /// @param amounts amounts to withdraw function withdraw(uint256[] calldata ids, uint256[] calldata amounts) external { if (ids.length == 1) { _burn(_msgSender(), ids[0], amounts[0]); } else { _burnBatch(_msgSender(), ids, amounts); } emit ChainExit(_msgSender(), ids, amounts, ""); } }
solhint-disable-next-line no-empty-blocks
contract PolygonAssetV2 is ERC1155ERC721 { using Address for address; address private _childChainManager; event ChainExit(address indexed to, uint256[] tokenIds, uint256[] amounts, bytes data); function initialize( address trustedForwarder, address admin, address bouncerAdmin, address childChainManager, uint8 chainIndex pragma solidity 0.8.2; ) external { require(trustedForwarder.isContract(), "TRUSTERFORWARDER_NOT_CONTRACT"); require(childChainManager.isContract(), "CHILDCHAINMANAGER_NOT_CONTRACT"); initV2(trustedForwarder, admin, bouncerAdmin, address(0), chainIndex); _childChainManager = childChainManager; } function deposit(address user, bytes calldata depositData) external { require(_msgSender() == _childChainManager, "!DEPOSITOR"); require(user != address(0), "INVALID_DEPOSIT_USER"); (uint256[] memory ids, uint256[] memory amounts, bytes memory data) = abi.decode(depositData, (uint256[], uint256[], bytes)); address sender = _msgSender(); bytes32 hash = abi.decode(data, (bytes32)); for (uint256 i = 0; i < ids.length; i++) { if ((amounts[i] == 1) && (ids[i] & IS_NFT > 0)) { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } else { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } } } function deposit(address user, bytes calldata depositData) external { require(_msgSender() == _childChainManager, "!DEPOSITOR"); require(user != address(0), "INVALID_DEPOSIT_USER"); (uint256[] memory ids, uint256[] memory amounts, bytes memory data) = abi.decode(depositData, (uint256[], uint256[], bytes)); address sender = _msgSender(); bytes32 hash = abi.decode(data, (bytes32)); for (uint256 i = 0; i < ids.length; i++) { if ((amounts[i] == 1) && (ids[i] & IS_NFT > 0)) { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } else { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } } } function deposit(address user, bytes calldata depositData) external { require(_msgSender() == _childChainManager, "!DEPOSITOR"); require(user != address(0), "INVALID_DEPOSIT_USER"); (uint256[] memory ids, uint256[] memory amounts, bytes memory data) = abi.decode(depositData, (uint256[], uint256[], bytes)); address sender = _msgSender(); bytes32 hash = abi.decode(data, (bytes32)); for (uint256 i = 0; i < ids.length; i++) { if ((amounts[i] == 1) && (ids[i] & IS_NFT > 0)) { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } else { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } } } function deposit(address user, bytes calldata depositData) external { require(_msgSender() == _childChainManager, "!DEPOSITOR"); require(user != address(0), "INVALID_DEPOSIT_USER"); (uint256[] memory ids, uint256[] memory amounts, bytes memory data) = abi.decode(depositData, (uint256[], uint256[], bytes)); address sender = _msgSender(); bytes32 hash = abi.decode(data, (bytes32)); for (uint256 i = 0; i < ids.length; i++) { if ((amounts[i] == 1) && (ids[i] & IS_NFT > 0)) { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } else { uint8 rarity = 0; _mint(hash, amounts[i], rarity, sender, user, ids[0], data, false); } } } function withdraw(uint256[] calldata ids, uint256[] calldata amounts) external { if (ids.length == 1) { _burn(_msgSender(), ids[0], amounts[0]); _burnBatch(_msgSender(), ids, amounts); } emit ChainExit(_msgSender(), ids, amounts, ""); } function withdraw(uint256[] calldata ids, uint256[] calldata amounts) external { if (ids.length == 1) { _burn(_msgSender(), ids[0], amounts[0]); _burnBatch(_msgSender(), ids, amounts); } emit ChainExit(_msgSender(), ids, amounts, ""); } } else { }
12,922,564
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 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, 16351, 12681, 6672, 58, 22, 353, 4232, 39, 2499, 2539, 654, 39, 27, 5340, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 1758, 3238, 389, 3624, 3893, 1318, 31, 203, 203, 565, 871, 7824, 6767, 12, 2867, 8808, 358, 16, 2254, 5034, 8526, 1147, 2673, 16, 2254, 5034, 8526, 30980, 16, 1731, 501, 1769, 203, 203, 565, 445, 4046, 12, 203, 3639, 1758, 13179, 30839, 16, 203, 3639, 1758, 3981, 16, 203, 3639, 1758, 324, 465, 2750, 4446, 16, 203, 3639, 1758, 1151, 3893, 1318, 16, 203, 3639, 2254, 28, 2687, 1016, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 22, 31, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 25247, 30839, 18, 291, 8924, 9334, 315, 4349, 23069, 7473, 16777, 4179, 67, 4400, 67, 6067, 2849, 1268, 8863, 203, 3639, 2583, 12, 3624, 3893, 1318, 18, 291, 8924, 9334, 315, 27043, 1792, 6964, 19402, 67, 4400, 67, 6067, 2849, 1268, 8863, 203, 3639, 1208, 58, 22, 12, 25247, 30839, 16, 3981, 16, 324, 465, 2750, 4446, 16, 1758, 12, 20, 3631, 2687, 1016, 1769, 203, 3639, 389, 3624, 3893, 1318, 273, 1151, 3893, 1318, 31, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 12, 2867, 729, 16, 1731, 745, 892, 443, 1724, 751, 13, 3903, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 389, 3624, 3893, 1318, 16, 17528, 1639, 28284, 916, 8863, 203, 3639, 2583, 12, 1355, 480, 1758, 12, 20, 3631, 315, 9347, 67, 1639, 28284, 67, 4714, 8863, 203, 3639, 261, 11890, 5034, 2 ]
pragma solidity ^0.4.24; /**@dev Based on Random Number Generator from Winem project */ contract Random { uint32 state; uint32 MAX = 0xffffffff; uint32 current; constructor(uint32 seed) public { state = seed; } /**@dev Returns random integer number from the range [min, max], including borders */ function getInt(uint32 min, uint32 max) public returns (uint32) { getNextNumber(); current = uint32(min + (uint256(state) * (max + 1 - min) / MAX)); return current; } function getNextNumber() internal { state = (69069 * state) + 362437; } }
*@dev Returns random integer number from the range [min, max], including borders */
function getInt(uint32 min, uint32 max) public returns (uint32) { getNextNumber(); current = uint32(min + (uint256(state) * (max + 1 - min) / MAX)); return current; }
12,676,599
[ 1, 1356, 2744, 3571, 1300, 628, 326, 1048, 306, 1154, 16, 943, 6487, 6508, 24028, 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, 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, 565, 445, 8145, 12, 11890, 1578, 1131, 16, 2254, 1578, 943, 13, 1071, 1135, 261, 11890, 1578, 13, 288, 203, 3639, 6927, 1854, 5621, 540, 203, 3639, 783, 273, 2254, 1578, 12, 1154, 397, 261, 11890, 5034, 12, 2019, 13, 380, 261, 1896, 397, 404, 300, 1131, 13, 342, 4552, 10019, 203, 3639, 327, 783, 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 ]
/** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * ** Code Modified by : TokenMagic ** Change Log: *** Solidity version upgraded from 0.4.8 to 0.4.23 *** Functions Added: setPresaleParticipantWhitelist, setFreezeEnd, getInvestorsCount */ pragma solidity ^0.4.23; 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. */ 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 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; } } contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier stopNonOwnersInEmergency { require(!halted && msg.sender == owner); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract HoardCrowdsale { function invest(address addr,uint tokenAmount) public payable { } } library SafeMathLib { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } /** * @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 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) { uint256 c = a + b; assert(c >= a); return c; } } contract HoardPresale is Ownable { using SafeMathLib for uint; /** Addresses that are allowed to invest even before ICO offical opens. For testing, for ICO partners, etc. */ mapping (address => bool) public presaleParticipantWhitelist; /** Who are our investors */ address[] public investors; mapping (address => bool) private investorsMapping; /** How much they have invested */ mapping(address => uint) public balances; /** A mapping of buyers and their amounts of total tokens due */ mapping(address => uint256) public tokenDue; /** When our refund freeze is over (UNIX timestamp) */ uint public freezeEndsAt; /* How many wei of funding pre-sale have raised */ uint public weiRaised = 0; /** Maximum pre-sale ETH fund limit in Wei */ uint public maxFundLimit = 16000000000000000000000; //16000 ETH /** Our ICO contract where we will move the funds */ HoardCrowdsale public crowdsale; /** * Define pricing schedule using tranches. */ struct Tranche { // Amount in weis when this tranche becomes active uint amount; // How many tokens per satoshi you will get while this tranche is active uint price; } // Store tranches in a fixed array, so that it can be seen in a blockchain explorer // Tranche 0 is always (0, 0) // (TODO: change this when we confirm dynamic arrays are explorable) // /* Calculations made by $500/ETH as rate */ /* 0 to 114 ETH = 120000000000000 WEI = 0.00012 ETH 114 ETH to 10000 ETH = 142857142857500 WEI = 0.0001428571428575 ETH 10000 ETH to 14000 ETH = 200000000000000 WEI = 0.0002 ETH */ Tranche[10] public tranches; // How many active tranches we have uint public trancheCount; uint public constant MAX_TRANCHES = 10; uint public tokenDecimals = 18; event Invested(address investor, uint value); event Refunded(address investor, uint value); //Event to show whitelisted address event Whitelisted(address[] addr, bool status); //Event to show when freezeends data changed event FreezeEndChanged(uint newFreezeEnd); //Event to show crowdsale address changes event CrowdsaleAdded(address newCrowdsale); /** * Create presale contract */ constructor(address _owner, uint _freezeEndsAt) public { require(_owner != address(0) && _freezeEndsAt != 0); owner = _owner; freezeEndsAt = _freezeEndsAt; } /** * Receive funds for presale * Modified by: TokenMagic */ function() public payable { // Only Whitelisted addresses can contribute require(presaleParticipantWhitelist[msg.sender]); require(trancheCount > 0); address investor = msg.sender; bool existing = investorsMapping[investor]; balances[investor] = balances[investor].add(msg.value); weiRaised = weiRaised.add(msg.value); require(weiRaised <= maxFundLimit); uint weiAmount = msg.value; uint tokenAmount = calculatePrice(weiAmount); // Add the amount of tokens they are now due to total tally tokenDue[investor] = tokenDue[investor].add(tokenAmount); if(!existing) { investors.push(investor); investorsMapping[investor] = true; } emit Invested(investor, msg.value); } /** * Add KYC whitelisted pre-sale participant ETH addresses to contract. * Added by: TokenMagic */ function setPresaleParticipantWhitelist(address[] addr, bool status) public onlyOwner { for(uint i = 0; i < addr.length; i++ ){ presaleParticipantWhitelist[addr[i]] = status; } emit Whitelisted(addr, status); } /** * Allow owner to set freezeEndsAt (Timestamp). * Added by: TokenMagic */ function setFreezeEnd(uint _freezeEndsAt) public onlyOwner { require(_freezeEndsAt != 0); freezeEndsAt = _freezeEndsAt; emit FreezeEndChanged(freezeEndsAt); } /** * Move single pre-sale participant&#39;s fund to the crowdsale contract. * Modified by: TokenMagic */ function participateCrowdsaleInvestor(address investor) public onlyOwner { // Crowdsale not yet set require(address(crowdsale) != 0); if(balances[investor] > 0) { uint amount = balances[investor]; uint tokenAmount = tokenDue[investor]; delete balances[investor]; delete tokenDue[investor]; crowdsale.invest.value(amount)(investor,tokenAmount); } } /** * Move all pre-sale participants fund to the crowdsale contract. * */ function participateCrowdsaleAll() public onlyOwner { // We might hit a max gas limit in this loop, // and in this case you can simply call participateCrowdsaleInvestor() for all investors for(uint i = 0; i < investors.length; i++) { participateCrowdsaleInvestor(investors[i]); } } /** * Move selected pre-sale participants fund to the crowdsale contract. * */ function participateCrowdsaleSelected(address[] addr) public onlyOwner { for(uint i = 0; i < addr.length; i++ ){ participateCrowdsaleInvestor(investors[i]); } } /** * ICO never happened. Allow refund. * Modified by: TokenMagic */ function refund() public { // Trying to ask refund too soon require(now > freezeEndsAt && balances[msg.sender] > 0); address investor = msg.sender; uint amount = balances[investor]; delete balances[investor]; emit Refunded(investor, amount); investor.transfer(amount); } /** * Set the crowdsale contract address, where we will move presale funds when the crowdsale opens. */ function setCrowdsale(HoardCrowdsale _crowdsale) public onlyOwner { crowdsale = _crowdsale; emit CrowdsaleAdded(crowdsale); } /** * Get total investors count * Added by: TokenMagic */ function getInvestorsCount() public view returns(uint investorsCount) { return investors.length; } /// @dev Contruction, creating a list of tranches /// @param _tranches uint[] tranches Pairs of (start amount, price) function setPricing(uint[] _tranches) public onlyOwner { // Need to have tuples, length check if(_tranches.length % 2 == 1 || _tranches.length >= MAX_TRANCHES*2) { revert(); } trancheCount = _tranches.length / 2; uint highestAmount = 0; for(uint i=0; i<_tranches.length/2; i++) { tranches[i].amount = _tranches[i*2]; tranches[i].price = _tranches[i*2+1]; // No invalid steps if((highestAmount != 0) && (tranches[i].amount <= highestAmount)) { revert(); } highestAmount = tranches[i].amount; } // We need to start from zero, otherwise we blow up our deployment if(tranches[0].amount != 0) { revert(); } // Last tranche price must be zero, terminating the crowdale if(tranches[trancheCount-1].price != 0) { revert(); } } /// @dev Get the current tranche or bail out if we are not in the tranche periods. /// @return {[type]} [description] function getCurrentTranche() private view returns (Tranche) { uint i; for(i=0; i < tranches.length; i++) { if(weiRaised <= tranches[i].amount) { return tranches[i-1]; } } } /// @dev Get the current price. /// @return The current price or 0 if we are outside trache ranges function getCurrentPrice() public view returns (uint result) { return getCurrentTranche().price; } /// @dev Calculate the current price for buy in amount. function calculatePrice(uint value) public view returns (uint) { uint multiplier = 10 ** tokenDecimals; uint price = getCurrentPrice(); return value.times(multiplier) / price; } /// @dev Iterate through tranches. You reach end of tranches when price = 0 /// @return tuple (time, price) function getTranche(uint n) public view returns (uint, uint) { return (tranches[n].amount, tranches[n].price); } function getFirstTranche() private view returns (Tranche) { return tranches[0]; } function getLastTranche() private view returns (Tranche) { return tranches[trancheCount-1]; } function getPricingStartsAt() public view returns (uint) { return getFirstTranche().amount; } function getPricingEndsAt() public view returns (uint) { return getLastTranche().amount; } }
* Move selected pre-sale participants fund to the crowdsale contract./
function participateCrowdsaleSelected(address[] addr) public onlyOwner { for(uint i = 0; i < addr.length; i++ ){ participateCrowdsaleInvestor(investors[i]); } }
7,785,971
[ 1, 7607, 3170, 675, 17, 87, 5349, 22346, 284, 1074, 358, 326, 276, 492, 2377, 5349, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 30891, 340, 39, 492, 2377, 5349, 7416, 12, 2867, 8526, 3091, 13, 1071, 1338, 5541, 288, 203, 565, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 3091, 18, 2469, 31, 277, 9904, 262, 95, 203, 1377, 30891, 340, 39, 492, 2377, 5349, 3605, 395, 280, 12, 5768, 395, 1383, 63, 77, 19226, 203, 565, 289, 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 ]
./full_match/42161/0x68bfbe1001568da0FeD281a1C99A16794bDa2754/sources/contracts/TalentirMarketplaceV1.sol
just to be safe - don't refund more than what was sent
require(msg.value >= ethQuantity, "Couldn't refund");
16,301,211
[ 1, 3732, 358, 506, 4183, 300, 2727, 1404, 16255, 1898, 2353, 4121, 1703, 3271, 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, 5411, 2583, 12, 3576, 18, 1132, 1545, 13750, 12035, 16, 315, 16342, 1404, 16255, 8863, 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 ]
// SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./ERC20/IERC20.sol"; import "./ERC20/IERC20Permit.sol"; import "./ERC20/SafeERC20.sol"; import "./interfaces/IRERC20.sol"; import "./interfaces/IRulerCore.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IRulerZap.sol"; import "./utils/Ownable.sol"; /** * @title Ruler Protocol Zap * @author alan * Main logic is in _depositAndAddLiquidity & _depositAndSwapToPaired */ contract RulerZap is Ownable, IRulerZap { using SafeERC20 for IERC20; IRulerCore public override core; IRouter public override router; constructor (IRulerCore _core, IRouter _router) { require(address(_core) != address(0), "RulerZap: _core is 0"); require(address(_router) != address(0), "RulerZap: _router is 0"); core = _core; router = _router; initializeOwner(); } /** * @notice Deposit collateral `_col` to receive paired token `_paired` and rrTokens * - deposits collateral to receive rcTokens and rrTokens * - rcTokens are swapped into paired token through router * - paired token and rrTokens are sent to sender */ function depositAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline ) external override { _depositAndSwapToPaired( _col, _paired, _expiry, _mintRatio, _colAmt, _minPairedOut, _path, _deadline ); } function depositWithPermitAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline, Permit calldata _colPermit ) external override { _permit(IERC20Permit(_col), _colPermit); _depositAndSwapToPaired( _col, _paired, _expiry, _mintRatio, _colAmt, _minPairedOut, _path, _deadline ); } /** * @notice Deposit collateral `_col` to receive LP tokens and rrTokens * - deposits collateral to receive rcTokens and rrTokens * - transfers paired token from sender * - rcTokens and `_paired` tokens are added as liquidity to receive LP tokens * - LP tokens and rrTokens are sent to sender */ function depositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) external override { _depositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _colAmt, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } function depositWithColPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _colPermit ) external override { _permit(IERC20Permit(_col), _colPermit); _depositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _colAmt, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } function depositWithPairedPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _pairedPermit ) external override { _permit(IERC20Permit(_paired), _pairedPermit); _depositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _colAmt, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } function depositWithBothPermitsAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _colPermit, Permit calldata _pairedPermit ) external override { _permit(IERC20Permit(_col), _colPermit); _permit(IERC20Permit(_paired), _pairedPermit); _depositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _colAmt, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } function mmDepositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) external override { _mmDepositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } function mmDepositWithPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _pairedPermit ) external override { _permit(IERC20Permit(_paired), _pairedPermit); _mmDepositAndAddLiquidity( _col, _paired, _expiry, _mintRatio, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, _deadline ); } /// @notice This contract should never hold any funds. /// Any tokens sent here by accident can be retreived. function collect(IERC20 _token) external override onlyOwner { uint256 balance = _token.balanceOf(address(this)); require(balance > 0, "RulerZap: balance is 0"); _token.safeTransfer(msg.sender, balance); } function updateCore(IRulerCore _core) external override onlyOwner { require(address(_core) != address(0), "RulerZap: _core is 0"); core = _core; } function updateRouter(IRouter _router) external override onlyOwner { require(address(_router) != address(0), "RulerZap: _router is 0"); router = _router; } /// @notice check received amount from swap, tokenOut is always the last in array function getAmountOut( uint256 _tokenInAmt, address[] calldata _path ) external view override returns (uint256) { return router.getAmountsOut(_tokenInAmt, _path)[_path.length - 1]; } function _depositAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline ) private { require(_colAmt > 0, "RulerZap: _colAmt is 0"); require(_path.length >= 2, "RulerZap: _path length < 2"); require(_path[_path.length - 1] == _paired, "RulerZap: output != _paired"); require(_deadline >= block.timestamp, "RulerZap: _deadline in past"); (address _rcToken, uint256 _rcTokensReceived, ) = _deposit(_col, _paired, _expiry, _mintRatio, _colAmt); require(_path[0] == _rcToken, "RulerZap: input != rcToken"); _approve(IERC20(_rcToken), address(router), _rcTokensReceived); router.swapExactTokensForTokens(_rcTokensReceived, _minPairedOut, _path, msg.sender, _deadline); } function _depositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) private { require(_colAmt > 0, "RulerZap: _colAmt is 0"); require(_deadline >= block.timestamp, "RulerZap: _deadline in past"); require(_rcTokenDepositAmt > 0, "RulerZap: 0 rcTokenDepositAmt"); require(_rcTokenDepositAmt >= _rcTokenDepositMin, "RulerZap: rcToken Amt < min"); require(_pairedDepositAmt > 0, "RulerZap: 0 pairedDepositAmt"); require(_pairedDepositAmt >= _pairedDepositMin, "RulerZap: paired Amt < min"); // deposit collateral to Ruler IERC20 rcToken; uint256 rcTokensBalBefore; { // scope to avoid stack too deep errors (address _rcToken, uint256 _rcTokensReceived, uint256 _rcTokensBalBefore) = _deposit(_col, _paired, _expiry, _mintRatio, _colAmt); require(_rcTokenDepositAmt <= _rcTokensReceived, "RulerZap: rcToken Amt > minted"); rcToken = IERC20(_rcToken); rcTokensBalBefore = _rcTokensBalBefore; } // received paired tokens from sender IERC20 paired = IERC20(_paired); uint256 pairedBalBefore = paired.balanceOf(address(this)); paired.safeTransferFrom(msg.sender, address(this), _pairedDepositAmt); uint256 receivedPaired = paired.balanceOf(address(this)) - pairedBalBefore; require(receivedPaired > 0, "RulerZap: paired transfer failed"); // add liquidity for sender _approve(rcToken, address(router), _rcTokenDepositAmt); _approve(paired, address(router), _pairedDepositAmt); router.addLiquidity( address(rcToken), address(paired), _rcTokenDepositAmt, receivedPaired, _rcTokenDepositMin, _pairedDepositMin, msg.sender, _deadline ); // sending leftover tokens back to sender uint256 rcTokensLeftover = rcToken.balanceOf(address(this)) - rcTokensBalBefore; if (rcTokensLeftover > 0) { rcToken.safeTransfer(msg.sender, rcTokensLeftover); } uint256 pairedTokensLeftover = paired.balanceOf(address(this)) - pairedBalBefore; if (pairedTokensLeftover > 0) { paired.safeTransfer(msg.sender, pairedTokensLeftover); } } function _mmDepositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) private { require(_deadline >= block.timestamp, "RulerZap: _deadline in past"); require(_rcTokenDepositAmt > 0, "RulerZap: 0 rcTokenDepositAmt"); require(_rcTokenDepositAmt >= _rcTokenDepositMin, "RulerZap: rcToken Amt < min"); require(_pairedDepositAmt > 0, "RulerZap: 0 pairedDepositAmt"); require(_pairedDepositAmt >= _pairedDepositMin, "RulerZap: paired Amt < min"); // transfer all paired tokens from sender to this contract IERC20 paired = IERC20(_paired); uint256 pairedBalBefore = paired.balanceOf(address(this)); paired.safeTransferFrom(msg.sender, address(this), _rcTokenDepositAmt + _pairedDepositAmt); require(paired.balanceOf(address(this)) - pairedBalBefore == _rcTokenDepositAmt + _pairedDepositAmt, "RulerZap: paired transfer failed"); // mmDeposit paired to Ruler to receive rcTokens ( , , , IRERC20 rcToken, , , , ) = core.pairs(_col, _paired, _expiry, _mintRatio); require(address(rcToken) != address(0), "RulerZap: pair not exist"); uint256 rcTokenBalBefore = rcToken.balanceOf(address(this)); _approve(paired, address(core), _rcTokenDepositAmt); core.mmDeposit(_col, _paired, _expiry, _mintRatio, _rcTokenDepositAmt); uint256 rcTokenReceived = rcToken.balanceOf(address(this)) - rcTokenBalBefore; require(_rcTokenDepositAmt <= rcTokenReceived, "RulerZap: rcToken Amt > minted"); // add liquidity for sender _approve(rcToken, address(router), _rcTokenDepositAmt); _approve(paired, address(router), _pairedDepositAmt); router.addLiquidity( address(rcToken), _paired, _rcTokenDepositAmt, _pairedDepositAmt, _rcTokenDepositMin, _pairedDepositMin, msg.sender, _deadline ); // sending leftover tokens (since the beginning of user call) back to sender _transferRem(rcToken, rcTokenBalBefore); _transferRem(paired, pairedBalBefore); } function _deposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt ) private returns (address rcTokenAddr, uint256 rcTokenReceived, uint256 rcTokenBalBefore) { ( , , , IRERC20 rcToken, IRERC20 rrToken, , , ) = core.pairs(_col, _paired, _expiry, _mintRatio); require(address(rcToken) != address(0) && address(rrToken) != address(0), "RulerZap: pair not exist"); // receive collateral from sender IERC20 collateral = IERC20(_col); uint256 colBalBefore = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _colAmt); uint256 received = collateral.balanceOf(address(this)) - colBalBefore; require(received > 0, "RulerZap: col transfer failed"); // deposit collateral to Ruler rcTokenBalBefore = rcToken.balanceOf(address(this)); uint256 rrTokenBalBefore = rrToken.balanceOf(address(this)); _approve(collateral, address(core), received); core.deposit(_col, _paired, _expiry, _mintRatio, received); // send rrToken back to sender, and record received rcTokens _transferRem(rrToken, rrTokenBalBefore); rcTokenReceived = rcToken.balanceOf(address(this)) - rcTokenBalBefore; rcTokenAddr = address(rcToken); } function _approve(IERC20 _token, address _spender, uint256 _amount) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _amount) { if (allowance != 0) { _token.safeApprove(_spender, 0); } _token.safeApprove(_spender, type(uint256).max); } } function _permit(IERC20Permit _token, Permit calldata permit) private { _token.permit( permit.owner, permit.spender, permit.amount, permit.deadline, permit.v, permit.r, permit.s ); } // transfer remaining amount (since the beginnning of action) back to sender function _transferRem(IERC20 _token, uint256 _balBefore) private { uint256 tokensLeftover = _token.balanceOf(address(this)) - _balBefore; if (tokensLeftover > 0) { _token.safeTransfer(msg.sender, tokensLeftover); } } } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; /** * @title Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // 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 { uint256 newAllowance = token.allowance(address(this), spender) - 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: No License pragma solidity ^0.8.0; import "../ERC20/IERC20.sol"; /** * @title RERC20 contract interface, implements {IERC20}. See {RERC20}. * @author crypto-pumpkin */ interface IRERC20 is IERC20 { /// @notice access restriction - owner (R) function mint(address _account, uint256 _amount) external returns (bool); function burnByRuler(address _account, uint256 _amount) external returns (bool); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IRERC20.sol"; import "./IOracle.sol"; /** * @title IRulerCore contract interface. See {RulerCore}. * @author crypto-pumpkin */ interface IRulerCore { event RTokenCreated(address); event CollateralUpdated(address col, uint256 old, uint256 _new); event PairAdded(address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio); event MarketMakeDeposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Deposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Repay(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Redeem(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event Collect(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount); event AddressUpdated(string _type, address old, address _new); event PausedStatusUpdated(bool old, bool _new); event RERC20ImplUpdated(address rERC20Impl, address newImpl); event FlashLoanRateUpdated(uint256 old, uint256 _new); struct Pair { bool active; uint48 expiry; address pairedToken; IRERC20 rcToken; // ruler capitol token, e.g. RC_Dai_wBTC_2_2021 IRERC20 rrToken; // ruler repayment token, e.g. RR_Dai_wBTC_2_2021 uint256 mintRatio; // 1e18, price of collateral / collateralization ratio uint256 feeRate; // 1e18 uint256 colTotal; } struct Permit { address owner; address spender; uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } // state vars function oracle() external view returns (IOracle); function version() external pure returns (string memory); function flashLoanRate() external view returns (uint256); function paused() external view returns (bool); function responder() external view returns (address); function feeReceiver() external view returns (address); function rERC20Impl() external view returns (address); function collaterals(uint256 _index) external view returns (address); function minColRatioMap(address _col) external view returns (uint256); function feesMap(address _token) external view returns (uint256); function pairs(address _col, address _paired, uint48 _expiry, uint256 _mintRatio) external view returns ( bool active, uint48 expiry, address pairedToken, IRERC20 rcToken, IRERC20 rrToken, uint256 mintRatio, uint256 feeRate, uint256 colTotal ); // extra view function getCollaterals() external view returns (address[] memory); function getPairList(address _col) external view returns (Pair[] memory); function viewCollectible( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external view returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect); // user action - only when not paused function mmDeposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external; function mmDepositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt, Permit calldata _pairedPermit ) external; function deposit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt ) external; function depositWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, Permit calldata _colPermit ) external; function redeem( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rTokenAmt ) external; function repay( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt ) external; function repayWithPermit( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rrTokenAmt, Permit calldata _pairedPermit ) external; function collect( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenAmt ) external; function collectFees(IERC20[] calldata _tokens) external; // access restriction - owner (dev) & responder function setPaused(bool _paused) external; // access restriction - owner (dev) function addPair( address _col, address _paired, uint48 _expiry, string calldata _expiryStr, uint256 _mintRatio, string calldata _mintRatioStr, uint256 _feeRate ) external; function setPairActive( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, bool _active ) external; function updateCollateral(address _col, uint256 _minColRatio) external; function setFeeReceiver(address _addr) external; function setResponder(address _addr) external; function setRERC20Impl(address _addr) external; function setOracle(address _addr) external; function setFlashLoanRate(uint256 _newRate) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRouter { function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity); function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; import "./IRulerCore.sol"; import "./IRouter.sol"; import "../ERC20/IERC20.sol"; interface IRulerZap { struct Permit { address owner; address spender; uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } // state vars function core() external view returns (IRulerCore); function router() external view returns (IRouter); // extra view function getAmountOut(uint256 _tokenInAmt, address[] calldata _path) external view returns (uint256); // user interactions function depositAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline ) external; function depositWithPermitAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline, Permit calldata _colPermit ) external; function depositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) external; function depositWithColPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _colPermit ) external; function depositWithPairedPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _pairedPermit ) external; function depositWithBothPermitsAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _colPermit, Permit calldata _pairedPermit ) external; function mmDepositAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline ) external; function mmDepositWithPermitAndAddLiquidity( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _rcTokenDepositAmt, uint256 _pairedDepositAmt, uint256 _rcTokenDepositMin, uint256 _pairedDepositMin, uint256 _deadline, Permit calldata _pairedPermit ) external; // admin function collect(IERC20 _token) external; function updateCore(IRulerCore _core) external; function updateRouter(IRouter _router) external; } // SPDX-License-Identifier: No License pragma solidity ^0.8.0; 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. * @author crypto-pumpkin * * By initialization, the owner account will be the one that called initializeOwner. 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 Initializable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Ruler: Initializes the contract setting the deployer as the initial owner. */ function initializeOwner() internal initializer { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @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 == msg.sender, "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; 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 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.8.0; interface IOracle { function getPriceUSD(address _asset) external view returns (uint256 price); function getPricesUSD(address[] calldata _assets) external view returns (uint256[] memory prices); // admin functions function updateFeedETH(address _asset, address _feed) external; function updateFeedUSD(address _asset, address _feed) external; function setSushiKeeperOracle(address _sushiOracle) external; function setUniKeeperOracle(address _uniOracle) external; } // 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 {UpgradeableProxy-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 || _isConstructor() || !_initialized, "Initializable: contract is already 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } }
* @notice Deposit collateral `_col` to receive paired token `_paired` and rrTokens - deposits collateral to receive rcTokens and rrTokens - rcTokens are swapped into paired token through router - paired token and rrTokens are sent to sender/
function depositAndSwapToPaired( address _col, address _paired, uint48 _expiry, uint256 _mintRatio, uint256 _colAmt, uint256 _minPairedOut, address[] calldata _path, uint256 _deadline ) external override { _depositAndSwapToPaired( _col, _paired, _expiry, _mintRatio, _colAmt, _minPairedOut, _path, _deadline ); }
1,517,810
[ 1, 758, 1724, 4508, 2045, 287, 1375, 67, 1293, 68, 358, 6798, 18066, 1147, 1375, 67, 24197, 68, 471, 8354, 5157, 225, 300, 443, 917, 1282, 4508, 2045, 287, 358, 6798, 4519, 5157, 471, 8354, 5157, 225, 300, 4519, 5157, 854, 7720, 1845, 1368, 18066, 1147, 3059, 4633, 225, 300, 18066, 1147, 471, 8354, 5157, 854, 3271, 358, 5793, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 443, 1724, 1876, 12521, 774, 16507, 2921, 12, 203, 3639, 1758, 389, 1293, 16, 7010, 3639, 1758, 389, 24197, 16, 203, 3639, 2254, 8875, 389, 22409, 16, 203, 3639, 2254, 5034, 389, 81, 474, 8541, 16, 203, 3639, 2254, 5034, 389, 1293, 31787, 16, 203, 3639, 2254, 5034, 389, 1154, 16507, 2921, 1182, 16, 203, 3639, 1758, 8526, 745, 892, 389, 803, 16, 203, 3639, 2254, 5034, 389, 22097, 1369, 203, 565, 262, 3903, 3849, 288, 203, 3639, 389, 323, 1724, 1876, 12521, 774, 16507, 2921, 12, 203, 5411, 389, 1293, 16, 7010, 5411, 389, 24197, 16, 7010, 5411, 389, 22409, 16, 7010, 5411, 389, 81, 474, 8541, 16, 7010, 5411, 389, 1293, 31787, 16, 7010, 5411, 389, 1154, 16507, 2921, 1182, 16, 7010, 5411, 389, 803, 16, 7010, 5411, 389, 22097, 1369, 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 ]
pragma solidity ^0.5.1; contract MyContract { mapping(address => uint256) public balances; address payable wallet; // Implicitly declaring that this address can accept Ether constructor(address payable _wallet) public { wallet = _wallet; } // Function that accepts ether - Buy Token and send Ether to the wallet function buyToken() public payable { // Payable modifier allows function to accept Ether balances[msg.sender]+=1; // Buy one token on function call wallet.transfer(msg.value); // `msg.value` returns how much Ether is sent in by the user who calls the function emit Purchase(msg.sender, 1); // Calling an event } // Fallback Function - Default Function that we can wrap other things in function() external payable { // External can only be called from outside of the contract buyToken(); } // Events - Used to allow External consumers to listen for actions on a Smart Contract event Purchase( address indexed _buyer; // `indexed` keyword allows us to filter on based on specific values uint256 amount; ); }
Implicitly declaring that this address can accept Ether
address payable wallet;
1,774,752
[ 1, 15787, 715, 20845, 716, 333, 1758, 848, 2791, 512, 1136, 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, 1758, 8843, 429, 9230, 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 ]
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } /** * v0.4.21+commit.dfe3193c */ contract AIC { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function AIC() public { totalSupply = 1000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Asia Intelligence Credit"; // Set the name for display purposes symbol = "AIC"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
Set the symbol for display purposes
symbol = "AIC";
14,579,017
[ 1, 694, 326, 3273, 364, 2562, 13694, 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, 3639, 3273, 273, 315, 37, 2871, 14432, 27573, 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/0x37aca97A99d1B4260a5E9821d0Ef14947fB68970/sources/src/Wrap.sol
@dev Internal function to calculate fees by amount and BPS. 10,000 is 100%
function calculateFee( uint256 amount, uint16 feeBPS ) internal pure returns (uint256) { return (amount * feeBPS) / 10000; }
2,954,444
[ 1, 3061, 445, 358, 4604, 1656, 281, 635, 3844, 471, 605, 5857, 18, 1728, 16, 3784, 353, 2130, 9, 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, 445, 4604, 14667, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 2313, 14036, 38, 5857, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 261, 8949, 380, 14036, 38, 5857, 13, 342, 12619, 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 ]
// SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IOutputReceiver.sol"; import "../interfaces/IRevest.sol"; import "../interfaces/IAddressRegistry.sol"; import "../interfaces/IRewardsHandler.sol"; import "../interfaces/IFNFTHandler.sol"; import "../interfaces/IAddressLock.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; interface IOldStaking { function config(uint fnftId) external view returns (uint allocPoints, uint timePeriod); function manualMapConfig(uint[] memory fnftIds, uint[] memory timePeriod) external; function customMetadataUrl() external view returns (string memory); } contract Staking is Ownable, IOutputReceiver, ERC165, IAddressLock { using SafeERC20 for IERC20; address private revestAddress; address public lpAddress; address public rewardsHandlerAddress; address public addressRegistry; //TODO: ADD SETTERS FOR THESE address public oldStakingContract; uint public previousStakingIDCutoff; uint private constant ONE_DAY = 86400; uint private constant WINDOW_ONE = ONE_DAY; uint private constant WINDOW_THREE = ONE_DAY*5; uint private constant WINDOW_SIX = ONE_DAY*9; uint private constant WINDOW_TWELVE = ONE_DAY*14; uint private constant MAX_INT = 2**256 - 1; address internal immutable WETH; uint[4] internal interestRates = [4, 13, 27, 56]; string public customMetadataUrl = "https://revest.mypinata.cloud/ipfs/Qmb6ADSCJt1xQ99ACGn2SQfZgGiGNP6qvgont1gAQguaoT"; string public addressMetadataUrl = "https://revest.mypinata.cloud/ipfs/QmY3KUBToJBthPLvN1Knd7Y51Zxx7FenFhXYV8tPEMVAP3"; event StakedRevest(uint indexed timePeriod, bool indexed isBasic, uint indexed amount, uint fnftId); struct StakingData { uint timePeriod; uint dateLockedFrom; } // fnftId -> timePeriods mapping(uint => StakingData) public stakingConfigs; constructor( address revestAddress_, address lpAddress_, address rewardsHandlerAddress_, address addressRegistry_, address wrappedEth_ ) { revestAddress = revestAddress_; lpAddress = lpAddress_; addressRegistry = addressRegistry_; rewardsHandlerAddress = rewardsHandlerAddress_; WETH = wrappedEth_; previousStakingIDCutoff = IFNFTHandler(IAddressRegistry(addressRegistry).getRevestFNFT()).getNextId() - 1; IERC20(lpAddress).approve(address(getRevest()), MAX_INT); IERC20(revestAddress).approve(address(getRevest()), MAX_INT); } function supportsInterface(bytes4 interfaceId) public view override (ERC165, IERC165) returns (bool) { return ( interfaceId == type(IOutputReceiver).interfaceId || interfaceId == type(IAddressLock).interfaceId || super.supportsInterface(interfaceId) ); } function stakeBasicTokens(uint amount, uint monthsMaturity) public returns (uint) { require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(revestAddress).safeTransferFrom(msg.sender, address(this), amount); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = revestAddress; fnftConfig.depositAmount = amount; fnftConfig.isMulti = true; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); // FNFT quantity will always be singular quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; StakingData memory cfg = StakingData(monthsMaturity, block.timestamp); stakingConfigs[fnftId] = cfg; IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoint); emit StakedRevest(monthsMaturity, true, amount, fnftId); return fnftId; } function stakeLPTokens(uint amount, uint monthsMaturity) public returns (uint) { require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(lpAddress).safeTransferFrom(msg.sender, address(this), amount); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = lpAddress; fnftConfig.depositAmount = amount; fnftConfig.isMulti = true; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; StakingData memory cfg = StakingData(monthsMaturity, block.timestamp); stakingConfigs[fnftId] = cfg; IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoint); emit StakedRevest(monthsMaturity, false, amount, fnftId); return fnftId; } function depositAdditionalToStake(uint fnftId, uint amount) public { //Prevent unauthorized access require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); require(fnftId > previousStakingIDCutoff, 'E080'); uint time = stakingConfigs[fnftId].timePeriod; require(time > 0, 'E078'); address asset = ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).asset; require(asset == revestAddress || asset == lpAddress, 'E079'); //Pull tokens from caller IERC20(asset).safeTransferFrom(_msgSender(), address(this), amount); //Claim rewards owed IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); //Write new, extended unlock date stakingConfigs[fnftId].dateLockedFrom = block.timestamp; //Retreive current allocation points – WETH and RVST implicitly have identical alloc points uint oldAllocPoints = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, asset == revestAddress); uint allocPoints = amount * getInterestRate(time) + oldAllocPoints; if(asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoints); } else if (asset == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoints); } //Deposit additional tokens getRevest().depositAdditionalToFNFT(fnftId, amount, 1); } function getInterestRate(uint months) public view returns (uint) { if (months <= 1) { return interestRates[0]; } else if (months <= 3) { return interestRates[1]; } else if (months <= 6) { return interestRates[2]; } else { return interestRates[3]; } } function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external override { address vault = getRegistry().getTokenVault(); require(_msgSender() == vault, "E016"); uint totalQuantity = quantity * ITokenVault(vault).getFNFT(fnftId).depositAmount; IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, owner); if (asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, 0); } else if (asset == lpAddress) { IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, 0); } else { require(false, "E072"); } IERC20(asset).safeTransfer(owner, totalQuantity); } function claimRewards(uint fnftId) external { // Check to make sure user owns the fnftId require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function updateLock(uint fnftId, uint, bytes memory) external override { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); // Receive rewards IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function needsUpdate() external pure override returns (bool) { return true; } function setCustomMetadata(string memory _customMetadataUrl) external onlyOwner { customMetadataUrl = _customMetadataUrl; } function getCustomMetadata(uint fnftId) external view override returns (string memory) { if(fnftId <= previousStakingIDCutoff) { return IOldStaking(oldStakingContract).customMetadataUrl(); } else { return customMetadataUrl; } } function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { bool isRevestToken; { // Will be zero if this is an LP stake uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (,timePeriod) = IOldStaking(oldStakingContract).config(fnftId); return abi.encode(revestRewards, wethRewards, timePeriod, isRevestToken ? revestAddress : lpAddress); } //This parameter has been modified for new stakes return abi.encode(revestRewards, wethRewards, timePeriod, stakingConfigs[fnftId].dateLockedFrom, isRevestToken ? revestAddress : lpAddress, stakingConfigs[fnftId].dateLockedFrom); } function setLPAddress(address lpAddress_) external onlyOwner { lpAddress = lpAddress_; } function setAddressRegistry(address addressRegistry_) external override onlyOwner { addressRegistry = addressRegistry_; } function getAddressRegistry() external view override returns (address) { return addressRegistry; } function getRevest() private view returns (IRevest) { return IRevest(getRegistry().getRevest()); } function getRegistry() public view returns (IAddressRegistry) { return IAddressRegistry(addressRegistry); } function getValue(uint fnftId) external view override returns (uint) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestStake : IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); } function getAsset(uint fnftId) external view override returns (address) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestAddress : WETH; } function setMetadata(string memory _addressMetadataUrl) external onlyOwner { addressMetadataUrl = _addressMetadataUrl; } function setRewardsHandler(address _handler) external onlyOwner { rewardsHandlerAddress = _handler; } function getMetadata() external view override returns (string memory) { return addressMetadataUrl; } function getDisplayValues(uint fnftId, uint) external view override returns (bytes memory) { uint allocPoints; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint lpTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, false); allocPoints = revestTokenAlloc > 0 ? revestTokenAlloc : lpTokenAlloc; } uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (allocPoints, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); } return abi.encode(allocPoints, timePeriod); } function createLock(uint, uint, bytes memory) external pure override { return; } function isUnlockable(uint fnftId, uint) external view override returns (bool) { uint timePeriod = stakingConfigs[fnftId].timePeriod; uint depositTime; if(fnftId <= previousStakingIDCutoff) { (, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); depositTime = ILockManager(getRegistry().getLockManager()).fnftIdToLock(fnftId).creationTime; } else { depositTime = stakingConfigs[fnftId].dateLockedFrom; } uint window = getWindow(timePeriod); bool mature = block.timestamp - depositTime > window; bool window_open = (block.timestamp - depositTime) % (timePeriod * 30 * ONE_DAY) < window; return mature && window_open; } function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } // Admin functions function manualMapConfig( uint[] memory fnftIds, uint[] memory timePeriod, uint [] memory lockedFrom ) external onlyOwner { for(uint i = 0; i < fnftIds.length; i++) { stakingConfigs[fnftIds[i]].timePeriod = timePeriod[i]; stakingConfigs[fnftIds[i]].dateLockedFrom = lockedFrom[i]; } } function updateInterestRates(uint[4] memory newRates) external onlyOwner { interestRates = newRates; } function setCutoff(uint cutoff) external onlyOwner { previousStakingIDCutoff = cutoff; } function setOldStaking(address stake) external onlyOwner { oldStakingContract = stake; } } // 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: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs */ interface IOutputReceiver is IRegistryProvider, IERC165 { function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external; function getCustomMetadata(uint fnftId) external view returns (string memory); function getValue(uint fnftId) external view returns (uint); function getAsset(uint fnftId) external view returns (address); function getOutputDisplayValues(uint fnftId) external view returns (bytes memory); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRevest { event FNFTTimeLockMinted( address indexed asset, address indexed from, uint indexed fnftId, uint endTime, uint[] quantities, FNFTConfig fnftConfig ); event FNFTValueLockMinted( address indexed primaryAsset, address indexed from, uint indexed fnftId, address compareTo, address oracleDispatch, uint[] quantities, FNFTConfig fnftConfig ); event FNFTAddressLockMinted( address indexed asset, address indexed from, uint indexed fnftId, address trigger, uint[] quantities, FNFTConfig fnftConfig ); event FNFTWithdrawn( address indexed from, uint indexed fnftId, uint indexed quantity ); event FNFTSplit( address indexed from, uint[] indexed newFNFTId, uint[] indexed proportions, uint quantity ); event FNFTUnlocked( address indexed from, uint indexed fnftId ); event FNFTMaturityExtended( address indexed from, uint indexed fnftId, uint indexed newExtendedTime ); event FNFTAddionalDeposited( address indexed from, uint indexed newFNFTId, uint indexed quantity, uint amount ); struct FNFTConfig { address asset; // The token being stored address pipeToContract; // Indicates if FNFT will pipe to another contract uint depositAmount; // How many tokens uint depositMul; // Deposit multiplier uint split; // Number of splits remaining uint depositStopTime; // bool maturityExtension; // Maturity extensions remaining bool isMulti; // bool nontransferrable; // False by default (transferrable) // } // Refers to the global balance for an ERC20, encompassing possibly many FNFTs struct TokenTracker { uint lastBalance; uint lastMul; } enum LockType { DoesNotExist, TimeLock, ValueLock, AddressLock } struct LockParam { address addressLock; uint timeLockExpiry; LockType lockType; ValueLock valueLock; } struct Lock { address addressLock; LockType lockType; ValueLock valueLock; uint timeLockExpiry; uint creationTime; bool unlocked; } struct ValueLock { address asset; address compareTo; address oracle; uint unlockValue; bool unlockRisingEdge; } function mintTimeLock( uint endTime, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintValueLock( address primaryAsset, address compareTo, uint unlockValue, bool unlockRisingEdge, address oracleDispatch, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function mintAddressLock( address trigger, bytes memory arguments, address[] memory recipients, uint[] memory quantities, IRevest.FNFTConfig memory fnftConfig ) external payable returns (uint); function withdrawFNFT(uint tokenUID, uint quantity) external; function unlockFNFT(uint tokenUID) external; function splitFNFT( uint fnftId, uint[] memory proportions, uint quantity ) external returns (uint[] memory newFNFTIds); function depositAdditionalToFNFT( uint fnftId, uint amount, uint quantity ) external returns (uint); function setFlatWeiFee(uint wethFee) external; function setERC20Fee(uint erc20) external; function getFlatWeiFee() external returns (uint); function getERC20Fee() external returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; /** * @title Provider interface for Revest FNFTs * @dev * */ interface IAddressRegistry { function initialize( address lock_manager_, address liquidity_, address revest_token_, address token_vault_, address revest_, address fnft_, address metadata_, address admin_, address rewards_ ) external; function getAdmin() external view returns (address); function setAdmin(address admin) external; function getLockManager() external view returns (address); function setLockManager(address manager) external; function getTokenVault() external view returns (address); function setTokenVault(address vault) external; function getRevestFNFT() external view returns (address); function setRevestFNFT(address fnft) external; function getMetadataHandler() external view returns (address); function setMetadataHandler(address metadata) external; function getRevest() external view returns (address); function setRevest(address revest) external; function getDEX(uint index) external view returns (address); function setDex(address dex) external; function getRevestToken() external view returns (address); function setRevestToken(address token) external; function getRewardsHandler() external view returns(address); function setRewardsHandler(address esc) external; function getAddress(bytes32 id) external view returns (address); function getLPs() external view returns (address); function setLPs(address liquidToken) external; } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IRewardsHandler { struct UserBalance { uint allocPoint; // Allocation points uint lastMul; } function receiveFee(address token, uint amount) external; function updateLPShares(uint fnftId, uint newShares) external; function updateBasicShares(uint fnftId, uint newShares) external; function getAllocPoint(uint fnftId, address token, bool isBasic) external view returns (uint); function claimRewards(uint fnftId, address caller) external returns (uint); function setStakingContract(address stake) external; function getRewards(uint fnftId, address token) external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; interface IFNFTHandler { function mint(address account, uint id, uint amount, bytes memory data) external; function mintBatchRec(address[] memory recipients, uint[] memory quantities, uint id, uint newSupply, bytes memory data) external; function mintBatch(address to, uint[] memory ids, uint[] memory amounts, bytes memory data) external; function setURI(string memory newuri) external; function burn(address account, uint id, uint amount) external; function burnBatch(address account, uint[] memory ids, uint[] memory amounts) external; function getBalance(address tokenHolder, uint id) external view returns (uint); function getSupply(uint fnftId) external view returns (uint); function getNextId() external view returns (uint); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRegistryProvider.sol"; import '@openzeppelin/contracts/utils/introspection/IERC165.sol'; /** * @title Provider interface for Revest FNFTs * @dev Address locks MUST be non-upgradeable to be considered for trusted status * @author Revest */ interface IAddressLock is IRegistryProvider, IERC165{ /// Creates a lock to the specified lockID /// @param fnftId the fnftId to map this lock to. Not recommended for typical locks, as it will break on splitting /// @param lockId the lockId to map this lock to. Recommended uint for storing references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev creates a lock for the specified lockId. Will be called during the creation process for address locks when the address /// of a contract implementing this interface is passed in as the "trigger" address for minting an address lock. The bytes /// representing any parameters this lock requires are passed through to this method, where abi.decode must be call on them function createLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Updates a lock at the specified lockId /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @param arguments an abi.encode() bytes array. Allows frontend to encode and pass in an arbitrary set of parameters /// @dev updates a lock for the specified lockId. Will be called by the frontend from the information section if an update is requested /// can further accept and decode parameters to use in modifying the lock's config or triggering other actions /// such as triggering an on-chain oracle to update function updateLock(uint fnftId, uint lockId, bytes memory arguments) external; /// Whether or not the lock can be unlocked /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev this method is called during the unlocking and withdrawal processes by the Revest contract - it is also used by the frontend /// if this method is returning true and someone attempts to unlock or withdraw from an FNFT attached to the requested lock, the request will succeed /// @return whether or not this lock may be unlocked function isUnlockable(uint fnftId, uint lockId) external view returns (bool); /// Provides an encoded bytes arary that represents values this lock wants to display on the info screen /// Info to decode these values is provided in the metadata file /// @param fnftId the fnftId that can map to a lock config stored in implementing contracts. Not recommended, as it will break on splitting /// @param lockId the lockId that maps to the lock config which should be updated. Recommended for retrieving references to lock configurations /// @dev used by the frontend to fetch on-chain data on the state of any given lock /// @return a bytes array that represents the result of calling abi.encode on values which the developer wants to appear on the frontend function getDisplayValues(uint fnftId, uint lockId) external view returns (bytes memory); /// Maps to a URL, typically IPFS-based, that contains information on how to encode and decode paramters sent to and from this lock /// Please see additional documentation for JSON config info /// @dev this method will be called by the frontend only but is crucial to properly implement for proper minting and information workflows /// @return a URL to the JSON file containing this lock's metadata schema function getMetadata() external view returns (string memory); /// Whether or not this lock will need updates and should display the option for them /// @dev this will be called by the frontend to determine if update inputs and buttons should be displayed /// @return whether or not the locks created by this contract will need updates function needsUpdate() external view returns (bool); } // 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' 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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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 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: GNU-GPL v3.0 or later pragma solidity ^0.8.0; import "../interfaces/IAddressRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/ILockManager.sol"; import "../interfaces/ITokenVault.sol"; import "../lib/uniswap/IUniswapV2Factory.sol"; interface IRegistryProvider { function setAddressRegistry(address revest) external; function getAddressRegistry() external view returns (address); } // 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: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ILockManager { function createLock(uint fnftId, IRevest.LockParam memory lock) external returns (uint); function getLock(uint lockId) external view returns (IRevest.Lock memory); function fnftIdToLockId(uint fnftId) external view returns (uint); function fnftIdToLock(uint fnftId) external view returns (IRevest.Lock memory); function pointFNFTToLock(uint fnftId, uint lockId) external; function lockTypes(uint tokenId) external view returns (IRevest.LockType); function unlockFNFT(uint fnftId, address sender) external returns (bool); function getLockMaturity(uint fnftId) external view returns (bool); } // SPDX-License-Identifier: GNU-GPL v3.0 or later pragma solidity >=0.8.0; import "./IRevest.sol"; interface ITokenVault { function createFNFT( uint fnftId, IRevest.FNFTConfig memory fnftConfig, uint quantity, address from ) external; function withdrawToken( uint fnftId, uint quantity, address user ) external; function depositToken( uint fnftId, uint amount, uint quantity ) external; function cloneFNFTConfig(IRevest.FNFTConfig memory old) external returns (IRevest.FNFTConfig memory); function mapFNFTToToken( uint fnftId, IRevest.FNFTConfig memory fnftConfig ) external; function handleMultipleDeposits( uint fnftId, uint newFNFTId, uint amount ) external; function splitFNFT( uint fnftId, uint[] memory newFNFTIds, uint[] memory proportions, uint quantity ) external; function getFNFT(uint fnftId) external view returns (IRevest.FNFTConfig memory); function getFNFTCurrentValue(uint fnftId) external view returns (uint); function getNontransferable(uint fnftId) external view returns (bool); function getSplitsRemaining(uint fnftId) external view returns (uint); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; 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; } // 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); } 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
TODO: ADD SETTERS FOR THESE
contract Staking is Ownable, IOutputReceiver, ERC165, IAddressLock { using SafeERC20 for IERC20; address private revestAddress; address public lpAddress; address public rewardsHandlerAddress; address public addressRegistry; address public oldStakingContract; uint public previousStakingIDCutoff; uint private constant ONE_DAY = 86400; uint private constant WINDOW_ONE = ONE_DAY; uint private constant WINDOW_THREE = ONE_DAY*5; uint private constant WINDOW_SIX = ONE_DAY*9; uint private constant WINDOW_TWELVE = ONE_DAY*14; uint private constant MAX_INT = 2**256 - 1; address internal immutable WETH; uint[4] internal interestRates = [4, 13, 27, 56]; event StakedRevest(uint indexed timePeriod, bool indexed isBasic, uint indexed amount, uint fnftId); struct StakingData { uint timePeriod; uint dateLockedFrom; } constructor( address revestAddress_, address lpAddress_, address rewardsHandlerAddress_, address addressRegistry_, address wrappedEth_ mapping(uint => StakingData) public stakingConfigs; ) { revestAddress = revestAddress_; lpAddress = lpAddress_; addressRegistry = addressRegistry_; rewardsHandlerAddress = rewardsHandlerAddress_; WETH = wrappedEth_; previousStakingIDCutoff = IFNFTHandler(IAddressRegistry(addressRegistry).getRevestFNFT()).getNextId() - 1; IERC20(lpAddress).approve(address(getRevest()), MAX_INT); IERC20(revestAddress).approve(address(getRevest()), MAX_INT); } function supportsInterface(bytes4 interfaceId) public view override (ERC165, IERC165) returns (bool) { return ( interfaceId == type(IOutputReceiver).interfaceId || interfaceId == type(IAddressLock).interfaceId || super.supportsInterface(interfaceId) ); } function stakeBasicTokens(uint amount, uint monthsMaturity) public returns (uint) { require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(revestAddress).safeTransferFrom(msg.sender, address(this), amount); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = revestAddress; fnftConfig.depositAmount = amount; fnftConfig.isMulti = true; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; StakingData memory cfg = StakingData(monthsMaturity, block.timestamp); stakingConfigs[fnftId] = cfg; IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoint); emit StakedRevest(monthsMaturity, true, amount, fnftId); return fnftId; } function stakeLPTokens(uint amount, uint monthsMaturity) public returns (uint) { require(monthsMaturity == 1 || monthsMaturity == 3 || monthsMaturity == 6 || monthsMaturity == 12, 'E055'); IERC20(lpAddress).safeTransferFrom(msg.sender, address(this), amount); IRevest.FNFTConfig memory fnftConfig; fnftConfig.asset = lpAddress; fnftConfig.depositAmount = amount; fnftConfig.isMulti = true; fnftConfig.pipeToContract = address(this); address[] memory recipients = new address[](1); recipients[0] = _msgSender(); uint[] memory quantities = new uint[](1); quantities[0] = 1; uint fnftId = getRevest().mintAddressLock(address(this), '', recipients, quantities, fnftConfig); uint interestRate = getInterestRate(monthsMaturity); uint allocPoint = amount * interestRate; StakingData memory cfg = StakingData(monthsMaturity, block.timestamp); stakingConfigs[fnftId] = cfg; IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoint); emit StakedRevest(monthsMaturity, false, amount, fnftId); return fnftId; } function depositAdditionalToStake(uint fnftId, uint amount) public { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); require(fnftId > previousStakingIDCutoff, 'E080'); uint time = stakingConfigs[fnftId].timePeriod; require(time > 0, 'E078'); address asset = ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).asset; require(asset == revestAddress || asset == lpAddress, 'E079'); IERC20(asset).safeTransferFrom(_msgSender(), address(this), amount); IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); stakingConfigs[fnftId].dateLockedFrom = block.timestamp; uint oldAllocPoints = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, asset == revestAddress); uint allocPoints = amount * getInterestRate(time) + oldAllocPoints; if(asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoints); IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoints); } } function depositAdditionalToStake(uint fnftId, uint amount) public { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); require(fnftId > previousStakingIDCutoff, 'E080'); uint time = stakingConfigs[fnftId].timePeriod; require(time > 0, 'E078'); address asset = ITokenVault(getRegistry().getTokenVault()).getFNFT(fnftId).asset; require(asset == revestAddress || asset == lpAddress, 'E079'); IERC20(asset).safeTransferFrom(_msgSender(), address(this), amount); IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); stakingConfigs[fnftId].dateLockedFrom = block.timestamp; uint oldAllocPoints = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, asset == revestAddress); uint allocPoints = amount * getInterestRate(time) + oldAllocPoints; if(asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, allocPoints); IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, allocPoints); } } } else if (asset == lpAddress) { getRevest().depositAdditionalToFNFT(fnftId, amount, 1); function getInterestRate(uint months) public view returns (uint) { if (months <= 1) { return interestRates[0]; return interestRates[1]; return interestRates[2]; return interestRates[3]; } } function getInterestRate(uint months) public view returns (uint) { if (months <= 1) { return interestRates[0]; return interestRates[1]; return interestRates[2]; return interestRates[3]; } } } else if (months <= 3) { } else if (months <= 6) { } else { function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external override { address vault = getRegistry().getTokenVault(); require(_msgSender() == vault, "E016"); uint totalQuantity = quantity * ITokenVault(vault).getFNFT(fnftId).depositAmount; IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, owner); if (asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, 0); IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, 0); require(false, "E072"); } IERC20(asset).safeTransfer(owner, totalQuantity); } function receiveRevestOutput( uint fnftId, address asset, address payable owner, uint quantity ) external override { address vault = getRegistry().getTokenVault(); require(_msgSender() == vault, "E016"); uint totalQuantity = quantity * ITokenVault(vault).getFNFT(fnftId).depositAmount; IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, owner); if (asset == revestAddress) { IRewardsHandler(rewardsHandlerAddress).updateBasicShares(fnftId, 0); IRewardsHandler(rewardsHandlerAddress).updateLPShares(fnftId, 0); require(false, "E072"); } IERC20(asset).safeTransfer(owner, totalQuantity); } } else if (asset == lpAddress) { } else { function claimRewards(uint fnftId) external { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function updateLock(uint fnftId, uint, bytes memory) external override { require(IFNFTHandler(getRegistry().getRevestFNFT()).getBalance(_msgSender(), fnftId) == 1, 'E061'); IRewardsHandler(rewardsHandlerAddress).claimRewards(fnftId, _msgSender()); } function needsUpdate() external pure override returns (bool) { return true; } function setCustomMetadata(string memory _customMetadataUrl) external onlyOwner { customMetadataUrl = _customMetadataUrl; } function getCustomMetadata(uint fnftId) external view override returns (string memory) { if(fnftId <= previousStakingIDCutoff) { return IOldStaking(oldStakingContract).customMetadataUrl(); return customMetadataUrl; } } function getCustomMetadata(uint fnftId) external view override returns (string memory) { if(fnftId <= previousStakingIDCutoff) { return IOldStaking(oldStakingContract).customMetadataUrl(); return customMetadataUrl; } } } else { function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { bool isRevestToken; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (,timePeriod) = IOldStaking(oldStakingContract).config(fnftId); return abi.encode(revestRewards, wethRewards, timePeriod, isRevestToken ? revestAddress : lpAddress); } } function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { bool isRevestToken; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (,timePeriod) = IOldStaking(oldStakingContract).config(fnftId); return abi.encode(revestRewards, wethRewards, timePeriod, isRevestToken ? revestAddress : lpAddress); } } function getOutputDisplayValues(uint fnftId) external view override returns (bytes memory) { bool isRevestToken; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint wethTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, WETH, true); isRevestToken = revestTokenAlloc > 0 || wethTokenAlloc > 0; } uint revestRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); uint wethRewards = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (,timePeriod) = IOldStaking(oldStakingContract).config(fnftId); return abi.encode(revestRewards, wethRewards, timePeriod, isRevestToken ? revestAddress : lpAddress); } } return abi.encode(revestRewards, wethRewards, timePeriod, stakingConfigs[fnftId].dateLockedFrom, isRevestToken ? revestAddress : lpAddress, stakingConfigs[fnftId].dateLockedFrom); function setLPAddress(address lpAddress_) external onlyOwner { lpAddress = lpAddress_; } function setAddressRegistry(address addressRegistry_) external override onlyOwner { addressRegistry = addressRegistry_; } function getAddressRegistry() external view override returns (address) { return addressRegistry; } function getRevest() private view returns (IRevest) { return IRevest(getRegistry().getRevest()); } function getRegistry() public view returns (IAddressRegistry) { return IAddressRegistry(addressRegistry); } function getValue(uint fnftId) external view override returns (uint) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestStake : IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, WETH); } function getAsset(uint fnftId) external view override returns (address) { uint revestStake = IRewardsHandler(rewardsHandlerAddress).getRewards(fnftId, revestAddress); return revestStake > 0 ? revestAddress : WETH; } function setMetadata(string memory _addressMetadataUrl) external onlyOwner { addressMetadataUrl = _addressMetadataUrl; } function setRewardsHandler(address _handler) external onlyOwner { rewardsHandlerAddress = _handler; } function getMetadata() external view override returns (string memory) { return addressMetadataUrl; } function getDisplayValues(uint fnftId, uint) external view override returns (bytes memory) { uint allocPoints; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint lpTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, false); allocPoints = revestTokenAlloc > 0 ? revestTokenAlloc : lpTokenAlloc; } uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (allocPoints, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); } return abi.encode(allocPoints, timePeriod); } function getDisplayValues(uint fnftId, uint) external view override returns (bytes memory) { uint allocPoints; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint lpTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, false); allocPoints = revestTokenAlloc > 0 ? revestTokenAlloc : lpTokenAlloc; } uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (allocPoints, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); } return abi.encode(allocPoints, timePeriod); } function getDisplayValues(uint fnftId, uint) external view override returns (bytes memory) { uint allocPoints; { uint revestTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, true); uint lpTokenAlloc = IRewardsHandler(rewardsHandlerAddress).getAllocPoint(fnftId, revestAddress, false); allocPoints = revestTokenAlloc > 0 ? revestTokenAlloc : lpTokenAlloc; } uint timePeriod = stakingConfigs[fnftId].timePeriod; if(fnftId <= previousStakingIDCutoff) { (allocPoints, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); } return abi.encode(allocPoints, timePeriod); } function createLock(uint, uint, bytes memory) external pure override { return; } function isUnlockable(uint fnftId, uint) external view override returns (bool) { uint timePeriod = stakingConfigs[fnftId].timePeriod; uint depositTime; if(fnftId <= previousStakingIDCutoff) { (, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); depositTime = ILockManager(getRegistry().getLockManager()).fnftIdToLock(fnftId).creationTime; depositTime = stakingConfigs[fnftId].dateLockedFrom; } uint window = getWindow(timePeriod); bool mature = block.timestamp - depositTime > window; bool window_open = (block.timestamp - depositTime) % (timePeriod * 30 * ONE_DAY) < window; return mature && window_open; } function isUnlockable(uint fnftId, uint) external view override returns (bool) { uint timePeriod = stakingConfigs[fnftId].timePeriod; uint depositTime; if(fnftId <= previousStakingIDCutoff) { (, timePeriod) = IOldStaking(oldStakingContract).config(fnftId); depositTime = ILockManager(getRegistry().getLockManager()).fnftIdToLock(fnftId).creationTime; depositTime = stakingConfigs[fnftId].dateLockedFrom; } uint window = getWindow(timePeriod); bool mature = block.timestamp - depositTime > window; bool window_open = (block.timestamp - depositTime) % (timePeriod * 30 * ONE_DAY) < window; return mature && window_open; } } else { function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } function getWindow(uint timePeriod) private pure returns (uint window) { if(timePeriod == 1) { window = WINDOW_ONE; } if(timePeriod == 3) { window = WINDOW_THREE; } if(timePeriod == 6) { window = WINDOW_SIX; } if(timePeriod == 12) { window = WINDOW_TWELVE; } } function manualMapConfig( uint[] memory fnftIds, uint[] memory timePeriod, uint [] memory lockedFrom ) external onlyOwner { for(uint i = 0; i < fnftIds.length; i++) { stakingConfigs[fnftIds[i]].timePeriod = timePeriod[i]; stakingConfigs[fnftIds[i]].dateLockedFrom = lockedFrom[i]; } } function manualMapConfig( uint[] memory fnftIds, uint[] memory timePeriod, uint [] memory lockedFrom ) external onlyOwner { for(uint i = 0; i < fnftIds.length; i++) { stakingConfigs[fnftIds[i]].timePeriod = timePeriod[i]; stakingConfigs[fnftIds[i]].dateLockedFrom = lockedFrom[i]; } } function updateInterestRates(uint[4] memory newRates) external onlyOwner { interestRates = newRates; } function setCutoff(uint cutoff) external onlyOwner { previousStakingIDCutoff = cutoff; } function setOldStaking(address stake) external onlyOwner { oldStakingContract = stake; } }
5,800,517
[ 1, 6241, 30, 11689, 3174, 1470, 11367, 12108, 12786, 1090, 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, 16351, 934, 6159, 353, 14223, 6914, 16, 467, 1447, 12952, 16, 4232, 39, 28275, 16, 467, 1887, 2531, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1758, 3238, 5588, 395, 1887, 31, 203, 565, 1758, 1071, 12423, 1887, 31, 203, 565, 1758, 1071, 283, 6397, 1503, 1887, 31, 203, 565, 1758, 1071, 1758, 4243, 31, 203, 203, 565, 1758, 1071, 1592, 510, 6159, 8924, 31, 203, 565, 2254, 1071, 2416, 510, 6159, 734, 15812, 3674, 31, 203, 203, 565, 2254, 3238, 5381, 15623, 67, 10339, 273, 21451, 31, 203, 203, 565, 2254, 3238, 5381, 24482, 7306, 67, 5998, 273, 15623, 67, 10339, 31, 203, 565, 2254, 3238, 5381, 24482, 7306, 67, 2455, 9719, 273, 15623, 67, 10339, 14, 25, 31, 203, 565, 2254, 3238, 5381, 24482, 7306, 67, 31773, 273, 15623, 67, 10339, 14, 29, 31, 203, 565, 2254, 3238, 5381, 24482, 7306, 67, 18869, 2247, 3412, 273, 15623, 67, 10339, 14, 3461, 31, 203, 565, 2254, 3238, 5381, 4552, 67, 3217, 273, 576, 636, 5034, 300, 404, 31, 203, 203, 565, 1758, 2713, 11732, 678, 1584, 44, 31, 203, 203, 565, 2254, 63, 24, 65, 2713, 16513, 20836, 273, 306, 24, 16, 5958, 16, 12732, 16, 13850, 15533, 203, 203, 565, 871, 934, 9477, 10070, 395, 12, 11890, 8808, 19470, 16, 1426, 8808, 353, 8252, 16, 2254, 8808, 3844, 16, 2254, 2295, 1222, 548, 1769, 203, 203, 565, 1958, 934, 6159, 751, 288, 203, 3639, 2254, 19470, 31, 203, 3639, 2254, 1509, 8966, 1265, 2 ]
./full_match/5/0xD5d0d51EfB41495fE078Ab0CFbC728027F7a19f6/sources/contracts/Authenticatable.sol
* **************************************************************** AUTHENTICATION STORAGE / @notice Returns the address of the owner that can manage Zayda collection on OpenSea. @notice Returns the address of the Gnosis Safe Multisig contract that can manage Zayda's contract.* **************************************************************** EVENTS / ERRORS / MODIFIERS /
modifier onlyOwner() { if (msg.sender != owner) revert Unauthorized(); _; }
11,611,400
[ 1, 25114, 2689, 2347, 15553, 342, 225, 2860, 326, 1758, 434, 326, 3410, 716, 848, 10680, 2285, 528, 2414, 1849, 603, 3502, 1761, 69, 18, 225, 2860, 326, 1758, 434, 326, 611, 18050, 291, 14060, 7778, 291, 360, 6835, 716, 848, 10680, 2285, 528, 2414, 1807, 6835, 18, 225, 9964, 55, 342, 5475, 55, 342, 8663, 10591, 55, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3410, 13, 15226, 15799, 5621, 203, 203, 3639, 389, 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 ]
pragma solidity >=0.4.22 <0.9.0; contract SupplyChain { //Smart Contract owner will be the person who deploys the contract only he can authorize various roles like retailer, Manufacturer,etc address public Owner; //note this constructor will be called when smart contract will be deployed on blockchain //Roles (flow of pharma supply chain) // RawMaterialSupplier; //This is where Manufacturer will get raw materials to make medicines // Manufacturer; //Various WHO guidelines should be followed by this person // Distributor; //This guy distributes the medicines to retailers // Retailer; //Normal customer buys from the retailer //modifier to make sure only the owner is using the function modifier onlyByOwner() { _; } //stages of a medicine in pharma supply chain enum STAGE { Init, Manufacture, Distribution, Retail, PartiallySold, sold } //using this we are going to track every single medicine the owner orders //Medicine count uint256 public medicineCtr = 4; //Raw material supplier count //uint256 public rmsCtr = 0; //Manufacturer count uint256 public manCtr = 0; //distributor count uint256 public disCtr = 0; //retailer count uint256 public retCtr = 0; uint256 public docCtr = 0; uint256 public patCtr = 0; uint256 public solCtr = 0; uint256 public parCtr = 0; //To store information about the medicine struct medicine { uint256 id; //unique medicine id string name; //name of the medicine //uint256 RMSid; //id of the Raw Material supplier for this particular medicine uint256 MANid; //id of the Manufacturer for this particular medicine uint256 DISid; //id of the distributor for this particular medicine uint256 RETid; //id of the retailer for this particular medicine uint256 ManQuantity; uint256 DisQuantity; uint256 RetQuantity; uint256 PatQuantity; STAGE stage; //current medicine stage } //To store all the medicines on the blockchain mapping(uint256 => medicine) public MedicineStock; constructor() public{ MedicineStock[1] = medicine(1,"crocin",0,0,0,0,0,0,0,STAGE.Init); MedicineStock[2] = medicine(2,"dolo",0,0,0,0,0,0,0,STAGE.Init); MedicineStock[3] = medicine(3,"calpol",0,0,0,0,0,0,0,STAGE.Init); MedicineStock[4] = medicine(4,"montefex",0,0,0,0,0,0,0,STAGE.Init); } //To show status to client applications function showStage(uint256 _medicineID) public view returns (string memory) { require(medicineCtr > 0); if (MedicineStock[_medicineID].stage == STAGE.Init) return "Medicine Ordered"; //else if (MedicineStock[_medicineID].stage == STAGE.RawMaterialSupply) // return "Raw Material Supply Stage"; else if (MedicineStock[_medicineID].stage == STAGE.Manufacture) return "Manufacturing Stage"; else if (MedicineStock[_medicineID].stage == STAGE.Distribution) return "Distribution Stage"; else if (MedicineStock[_medicineID].stage == STAGE.Retail) return "Retail Stage"; else if (MedicineStock[_medicineID].stage == STAGE.PartiallySold) return "Partially Sold"; else if (MedicineStock[_medicineID].stage == STAGE.sold) return "Medicine Sold"; } //To store information about raw material supplier //struct rawMaterialSupplier { // address addr; // uint256 id; //supplier id // string name; //Name of the raw material supplier // string place; //Place the raw material supplier is based in // uint256 Quantity; // } //To store all the raw material suppliers on the blockchain //mapping(uint256 => rawMaterialSupplier) public RMS; //To store information about manufacturer struct manufacturer { address addr; uint256 id; //manufacturer id string name; //Name of the manufacturer string place; //Place the manufacturer is based in uint256 Quantity; } //To store all the manufacturers on the blockchain mapping(uint256 => manufacturer) public MAN; //To store information about distributor struct distributor { address addr; uint256 id; //distributor id string name; //Name of the distributor string place; //Place the distributor is based in uint256 Quantity; } //To store all the distributors on the blockchain mapping(uint256 => distributor) public DIS; //To store information about retailer struct retailer { address addr; uint256 id; //retailer id string name; //Name of the retailer string place; //Place the retailer is based in uint256 Quantity; } //To store all the retailers on the blockchain mapping(uint256 => retailer) public RET; //patient struct patient { uint256 id; //patient id string name; //Name of the patient string phoneNo; string email; uint256 docID; string medName; uint256 Quantity; } mapping(uint256 => patient) public PAT; //Doctor struct doctor { address addr; uint256 id; //doctor id string name; //Name of the doctor } mapping(uint256 => doctor) public DOC; struct soldMed { uint256 Retid; uint256 DocId; uint256 PatId; uint256 MedId; uint256 Quantity; } mapping(uint256 => soldMed) public SOL; struct parPat { uint256 Retid; uint256 DocId; uint256 PatId; uint256 MedId; uint256 balQ; uint256 presQ; } mapping(uint256 => parPat) public PAR; function addDoctor( address _address, string memory _name ) public onlyByOwner() { docCtr++; DOC[docCtr]=doctor(_address,docCtr,_name); } //To add manufacturer. Only contract owner can add a new manufacturer function addManufacturer( address _address, string memory _name, string memory _place ) public onlyByOwner() { manCtr++; MAN[manCtr] = manufacturer(_address, manCtr, _name, _place,0); } //To add distributor. Only contract owner can add a new distributor function addDistributor( address _address, string memory _name, string memory _place ) public onlyByOwner() { disCtr++; DIS[disCtr] = distributor(_address, disCtr, _name, _place,0); } //To add retailer. Only contract owner can add a new retailer function addRetailer( address _address, string memory _name, string memory _place ) public onlyByOwner() { retCtr++; RET[retCtr] = retailer(_address, retCtr, _name, _place,0); } //To manufacture medicine function Manufacturing(uint256 _medicineID,uint256 _quantity) public { require(_medicineID > 0 && _medicineID <= medicineCtr); uint256 _id = findMAN(msg.sender); require(_id > 0); require(_quantity>0); require(MedicineStock[_medicineID].stage == STAGE.Init); MedicineStock[_medicineID].MANid = _id; MedicineStock[_medicineID].ManQuantity = _quantity; MAN[_id].Quantity+=_quantity; MedicineStock[_medicineID].stage = STAGE.Manufacture; } //To check if Manufacturer is available in the blockchain function findMAN(address _address) private view returns (uint256) { require(manCtr > 0); for (uint256 i = 1; i <= manCtr; i++) { if (MAN[i].addr == _address) return MAN[i].id; } return 0; } //To supply medicines from Manufacturer to distributor function Distribute(uint256 _medicineID,uint256 _quantity) public { require(_medicineID > 0 && _medicineID <= medicineCtr); uint256 _id = findDIS(msg.sender); require(_id > 0); require(_quantity>0); MedicineStock[_medicineID].DisQuantity = _quantity; if( MedicineStock[_medicineID].DisQuantity< MedicineStock[_medicineID].ManQuantity){ //error } require(MedicineStock[_medicineID].stage == STAGE.Manufacture); MedicineStock[_medicineID].DISid = _id; DIS[_id].Quantity+=_quantity; MedicineStock[_medicineID].stage = STAGE.Distribution; } //To check if distributor is available in the blockchain function findDIS(address _address) private view returns (uint256) { require(disCtr > 0); for (uint256 i = 1; i <= disCtr; i++) { if (DIS[i].addr == _address) return DIS[i].id; } return 0; } //To supply medicines from distributor to retailer function Retail(uint256 _medicineID) public { require(_medicineID > 0 && _medicineID <= medicineCtr); uint256 _id = findRET(msg.sender); require(_id > 0); uint256 _quantity=MedicineStock[_id].RetQuantity; require(_quantity>0); MedicineStock[_medicineID].RetQuantity = _quantity; //DIS[MED[ID].DISid].id uint256 distId=MedicineStock[_medicineID].DISid; //uint256 distQuant=DIS[disId].Quantity; if(DIS[distId].Quantity- _quantity>0) {DIS[distId].Quantity=DIS[distId].Quantity- _quantity; MedicineStock[_medicineID].DisQuantity-=_quantity;} //else require(MedicineStock[_medicineID].stage == STAGE.Distribution); MedicineStock[_medicineID].RETid = _id; RET[_id].Quantity+=_quantity; MedicineStock[_medicineID].stage = STAGE.Retail; } //To check if retailer is available in the blockchain function findRET(address _address) private view returns (uint256) { require(retCtr > 0); for (uint256 i = 1; i <= retCtr; i++) { if (RET[i].addr == _address) return RET[i].id; } return 0; } //To sell medicines from retailer to consumer function sold(string memory _patName,string memory _patEmail) public { uint256 _RetId = findRET(msg.sender); require(_RetId > 0); uint256 _patId=findPat(_patName,_patEmail); require(_patId > 0); uint256 _docID=PAT[_patId].docID; string memory _medName=PAT[_patId].medName; uint256 _medId = findMed(_medName); require(MedicineStock[_medId].stage==STAGE.Retail||MedicineStock[_medId].stage==STAGE.PartiallySold); uint256 _patQuan = PAT[_patId].Quantity; uint256 _retQuan = RET[_RetId].Quantity; MedicineStock[_medId].PatQuantity = _patQuan; //require(_id == MedicineStock[_medId].RETid); //Only correct retailer can mark medicine as sold if(MedicineStock[_medId].stage == STAGE.Retail) { if(_patQuan <= _retQuan){ MedicineStock[_medId].RetQuantity-=_patQuan; MedicineStock[_medId].stage = STAGE.sold; MedicineStock[_medId].PatQuantity = 0; solCtr++; SOL[solCtr]=soldMed(_RetId,_docID,_patId,_medId,_patQuan); } else{ uint256 bal=_patQuan-_retQuan; MedicineStock[_medId].stage = STAGE.PartiallySold; parCtr++; PAR[parCtr]=parPat(_RetId,_docID,_patId,_medId,bal,_patQuan); } } else if(MedicineStock[_medId].stage == STAGE.PartiallySold) { if(_patQuan <= _retQuan){ MedicineStock[_medId].RetQuantity-=_patQuan; MedicineStock[_medId].stage = STAGE.sold; MedicineStock[_medId].PatQuantity = 0; solCtr++; SOL[solCtr]=soldMed(_RetId,_docID,_patId,_medId,_patQuan); } else{ uint256 bal=_patQuan-_retQuan; MedicineStock[_medId].stage = STAGE.PartiallySold; parCtr++; PAR[parCtr]=parPat(_RetId,_docID,_patId,_medId,bal,_patQuan); } } } function findPat(string memory _name,string memory _email) private view returns (uint256) { require(patCtr > 0); for (uint256 i = 1; i <= patCtr; i++) { string memory _patName=PAT[i].name; string memory _patEmail=PAT[i].email; if (keccak256(abi.encode(_patName)) == keccak256(abi.encode(_name))&&keccak256(abi.encode(_patEmail)) == keccak256(abi.encode(_email))) return PAT[i].id; } return 0; } function prescribe(string memory _patName,string memory _patPhNo,string memory _email,string memory _medName,uint256 _quantity) public{ uint256 _docId = findDoc(msg.sender); require(_docId>0); require(_quantity>0); uint256 _medId=findMed(_medName); require(_medId>0); patCtr++; PAT[patCtr] = patient(patCtr, _patName, _patPhNo,_email,_docId,_medName,_quantity); MedicineStock[_medId].PatQuantity=_quantity; } function findDoc(address _address) private view returns (uint256) { require(docCtr > 0); for (uint256 i = 1; i <= docCtr; i++) { if (DOC[i].addr == _address) return DOC[i].id; } return 0; } function findMed(string memory _name) private view returns (uint256) { require(medicineCtr > 0); string memory _medName; for (uint256 i = 1; i <= medicineCtr; i++) { _medName=MedicineStock[i].name; if (keccak256(abi.encode(_medName)) == keccak256(abi.encode(_name))) return MedicineStock[i].id; } return 0; } // To add new medicines to the stock function addMedicine(uint256 _medId,uint256 _quantity) public onlyByOwner() { //js changes require((manCtr > 0) && (disCtr > 0) && (retCtr > 0)); MedicineStock[_medId].RetQuantity=_quantity; } }
Raw material supplier countuint256 public rmsCtr = 0;Manufacturer count
uint256 public manCtr = 0;
930,253
[ 1, 4809, 9390, 17402, 1056, 11890, 5034, 1071, 27806, 39, 313, 273, 374, 31, 24419, 1056, 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, 565, 2254, 5034, 1071, 3161, 39, 313, 273, 374, 31, 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 ]
pragma solidity ^0.4.24; contract MonkeyEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularMonkeyScam is MonkeyEvents {} contract MonkeyScam is modularMonkeyScam { using SafeMath for *; using NameFilter for string; using LDKeysCalc for uint256; // TODO: check address PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xce7149603aeD4d9468f4025c93cE487c79fC0557); address private monkeyKing = 0xb75603Fd0B0E55b283DAC9A9ED516A8a9515e3dB; address private monkeyQueue = 0x2B215DE0Ec7C1A9b72F48aB357f2E1739487c050; string constant public name = "MonkeyScam Round #1"; string constant public symbol = "MSR"; uint256 private rndGap_ = 0; // TODO: check time uint256 constant private rndInit_ = 72 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 72 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => LDdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => LDdatasets.PlayerRounds) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** LDdatasets.Round public round_; // round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 40; // fee distribution uint256 public potSplit_ = 20; // pot split distribution //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with ratscam */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not LDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not LDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not LDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not LDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data LDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data LDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data LDdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_.end && round_.ended == false && round_.plyr != 0) { // set up our tx event data LDdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_.ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit MonkeyEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit MonkeyEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit MonkeyEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit MonkeyEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit MonkeyEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // grab time uint256 _now = now; if (_now < round_.end) if (_now > round_.strt + rndGap_) return( (round_.end).sub(_now) ); else return( (round_.strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_.end && round_.ended == false && round_.plyr != 0) { // if player is winner if (round_.plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_.pot).mul(45)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID) private view returns(uint256) { return( ((((round_.mask).add(((((round_.pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_.keys))).mul(plyrRnds_[_pID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker * @return airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256) { return ( round_.keys, //0 round_.end, //1 round_.strt, //2 round_.pot, //3 round_.plyr, //4 plyr_[round_.plyr].addr, //5 plyr_[round_.plyr].name, //6 airDropTracker_, //7 airDropPot_ //8 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, LDdatasets.EventReturns memory _eventData_) private { // grab time uint256 _now = now; // if round is active if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { // call core core(_pID, msg.value, _affID, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_.end && round_.ended == false) { // end the round (distributes pot) & start new round round_.ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit MonkeyEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, LDdatasets.EventReturns memory _eventData_) private { // grab time uint256 _now = now; // if round is active if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_pID, _eth, _affID, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_.end && round_.ended == false) { // end the round (distributes pot) & start new round round_.ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit MonkeyEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _pID, uint256 _eth, uint256 _affID, LDdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_.eth < 100000000000000000000 && plyrRnds_[_pID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_.eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys); // set new leaders if (round_.plyr != _pID) round_.plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) // larger 0.1eth { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) // larger 10eth { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID].keys = _keys.add(plyrRnds_[_pID].keys); plyrRnds_[_pID].eth = _eth.add(plyrRnds_[_pID].eth); // update round round_.keys = _keys.add(round_.keys); round_.eth = _eth.add(round_.eth); // distribute eth _eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID) private view returns(uint256) { return((((round_.mask).mul(plyrRnds_[_pID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0))) return ( (round_.keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "only PlayerBook can call this function"); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "only PlayerBook can call this function"); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(LDdatasets.EventReturns memory _eventData_) private returns (LDdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of ratscam if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, LDdatasets.EventReturns memory _eventData_) private returns (LDdatasets.EventReturns) { // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(LDdatasets.EventReturns memory _eventData_) private returns (LDdatasets.EventReturns) { // grab our winning player and team id's uint256 _winPID = round_.plyr; // grab our pot amount // add airdrop pot into the final pot uint256 _pot = round_.pot + airDropPot_; // calculate our winner share, community rewards, gen share, uint256 _win = (_pot.mul(40)) / 100; uint256 _com = (_pot.mul(30)) / 100; uint256 _queen = (_pot.mul(10)) / 100; uint256 _gen = (_pot.mul(20)) / 100; // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); uint256 _dust = _gen.sub((_ppt.mul(round_.keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards if (!address(monkeyKing).call.value(_com)()) { _gen = _gen.add(_com); _com = 0; } if (!address(monkeyQueue).call.value(_queen)()) { _gen = _gen.add(_queen); _queen = 0; } // distribute gen portion to key holders round_.mask = _ppt.add(round_.mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_.end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID) private { uint256 _earnings = calcUnMaskedEarnings(_pID); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID].mask = _earnings.add(plyrRnds_[_pID].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_.end && round_.plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_.end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_.end = _newTime; else round_.end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, LDdatasets.EventReturns memory _eventData_) private returns(LDdatasets.EventReturns) { // pay 15% out to community rewards uint256 _com = _eth * 15 / 100; // distribute share to affiliate 25% uint256 _aff = _eth*25 / 100; uint256 _toqueen = 0; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit MonkeyEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += (_aff*80/100); _toqueen += (_aff*20/100); } if (_toqueen > 0) { if(!address(monkeyQueue).call.value(_toqueen)()) { //do nothing } } if (!address(monkeyKing).call.value(_com)()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _pID, uint256 _eth, uint256 _keys, LDdatasets.EventReturns memory _eventData_) private returns(LDdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (15%) uint256 _pot = (_eth.mul(15) / 100); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_.pot = _pot.add(_dust).add(round_.pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys); round_.mask = _ppt.add(round_.mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID].mask = (((round_.mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_.keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, LDdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit MonkeyEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate // TODO: set owner require( msg.sender == 0xb75603Fd0B0E55b283DAC9A9ED516A8a9515e3dB || msg.sender == 0x029800F64f16d81FC164319Edb84cf85bFf15e80, "only owner can activate" ); // can only be ran once require(activated_ == false, "dogscam already activated"); // activate the contract activated_ = true; round_.strt = now - rndGap_; round_.end = now + rndInit_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library LDdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library LDKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); 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) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
* @dev prepares compression data and fires event for buy or reload tx's/
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, LDdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit MonkeyEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); }
12,032,769
[ 1, 19109, 4807, 9154, 501, 471, 29564, 871, 364, 30143, 578, 7749, 2229, 1807, 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, 679, 4188, 12, 11890, 5034, 389, 84, 734, 16, 2254, 5034, 389, 546, 16, 2254, 5034, 389, 2452, 16, 28083, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 565, 3238, 203, 565, 288, 203, 3639, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 261, 3338, 380, 2130, 12648, 12648, 1769, 203, 3639, 389, 2575, 751, 27799, 15385, 5103, 273, 389, 2575, 751, 27799, 15385, 5103, 397, 389, 84, 734, 31, 203, 203, 3639, 3626, 9041, 856, 3783, 18, 265, 1638, 4188, 203, 3639, 261, 203, 5411, 389, 2575, 751, 27799, 15385, 751, 16, 203, 5411, 389, 2575, 751, 27799, 15385, 5103, 16, 203, 5411, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 389, 546, 16, 203, 5411, 389, 2452, 16, 203, 5411, 389, 2575, 751, 27799, 91, 7872, 3178, 16, 203, 5411, 389, 2575, 751, 27799, 91, 7872, 461, 16, 203, 5411, 389, 2575, 751, 27799, 8949, 59, 265, 16, 203, 5411, 389, 2575, 751, 27799, 2704, 18411, 16, 203, 5411, 389, 2575, 751, 27799, 4507, 6275, 16, 203, 5411, 389, 2575, 751, 27799, 13130, 6275, 16, 203, 5411, 23350, 7544, 18411, 67, 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 ]
pragma solidity 0.4.18; contract CrowdsaleParameters { // Vesting time stamps: // 1534672800 = August 19, 2018. 180 days from February 20, 2018. 10:00:00 GMT // 1526896800 = May 21, 2018. 90 days from February 20, 2018. 10:00:00 GMT uint32 internal vestingTime90Days = 1526896800; uint32 internal vestingTime180Days = 1534672800; uint256 internal constant presaleStartDate = 1513072800; // Dec-12-2017 10:00:00 GMT uint256 internal constant presaleEndDate = 1515751200; // Jan-12-2018 10:00:00 GMT uint256 internal constant generalSaleStartDate = 1516442400; // Jan-20-2018 00:00:00 GMT uint256 internal constant generalSaleEndDate = 1519120800; // Feb-20-2018 00:00:00 GMT struct AddressTokenAllocation { address addr; uint256 amount; uint256 vestingTS; } AddressTokenAllocation internal presaleWallet = AddressTokenAllocation(0x43C5FB6b419E6dF1a021B9Ad205A18369c19F57F, 100e6, 0); AddressTokenAllocation internal generalSaleWallet = AddressTokenAllocation(0x0635c57CD62dA489f05c3dC755bAF1B148FeEdb0, 550e6, 0); AddressTokenAllocation internal wallet1 = AddressTokenAllocation(0xae46bae68D0a884812bD20A241b6707F313Cb03a, 20e6, vestingTime180Days); AddressTokenAllocation internal wallet2 = AddressTokenAllocation(0xfe472389F3311e5ea19B4Cd2c9945b6D64732F13, 20e6, vestingTime180Days); AddressTokenAllocation internal wallet3 = AddressTokenAllocation(0xE37dfF409AF16B7358Fae98D2223459b17be0B0B, 20e6, vestingTime180Days); AddressTokenAllocation internal wallet4 = AddressTokenAllocation(0x39482f4cd374D0deDD68b93eB7F3fc29ae7105db, 10e6, vestingTime180Days); AddressTokenAllocation internal wallet5 = AddressTokenAllocation(0x03736d5B560fE0784b0F5c2D0eA76A7F15E5b99e, 5e6, vestingTime180Days); AddressTokenAllocation internal wallet6 = AddressTokenAllocation(0xD21726226c32570Ab88E12A9ac0fb2ed20BE88B9, 5e6, vestingTime180Days); AddressTokenAllocation internal foundersWallet = AddressTokenAllocation(0xC66Cbb7Ba88F120E86920C0f85A97B2c68784755, 30e6, vestingTime90Days); AddressTokenAllocation internal wallet7 = AddressTokenAllocation(0x24ce108d1975f79B57c6790B9d4D91fC20DEaf2d, 6e6, 0); AddressTokenAllocation internal wallet8genesis = AddressTokenAllocation(0x0125c6Be773bd90C0747012f051b15692Cd6Df31, 5e6, 0); AddressTokenAllocation internal wallet9 = AddressTokenAllocation(0xFCF0589B6fa8A3f262C4B0350215f6f0ed2F630D, 5e6, 0); AddressTokenAllocation internal wallet10 = AddressTokenAllocation(0x0D016B233e305f889BC5E8A0fd6A5f99B07F8ece, 4e6, 0); AddressTokenAllocation internal wallet11bounty = AddressTokenAllocation(0x68433cFb33A7Fdbfa74Ea5ECad0Bc8b1D97d82E9, 19e6, 0); AddressTokenAllocation internal wallet12 = AddressTokenAllocation(0xd620A688adA6c7833F0edF48a45F3e39480149A6, 4e6, 0); AddressTokenAllocation internal wallet13rsv = AddressTokenAllocation(0x8C393F520f75ec0F3e14d87d67E95adE4E8b16B1, 100e6, 0); AddressTokenAllocation internal wallet14partners = AddressTokenAllocation(0x6F842b971F0076C4eEA83b051523d76F098Ffa52, 96e6, 0); AddressTokenAllocation internal wallet15lottery = AddressTokenAllocation(0xcaA48d91D49f5363B2974bb4B2DBB36F0852cf83, 1e6, 0); uint256 public minimumICOCap = 3333; } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * Constructor * * Sets contract owner to address of constructor caller */ function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * Change Owner * * Changes ownership of this contract. Only owner can call this method. * * @param newOwner - new owner's address */ function changeOwner(address newOwner) onlyOwner public { require(newOwner != address(0)); require(newOwner != owner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract TKLNToken is Owned, CrowdsaleParameters { /* Public variables of the token */ string public standard = 'Token 0.1'; string public name = 'Taklimakan'; string public symbol = 'TKLN'; uint8 public decimals = 18; /* Arrays of all balances, vesting, approvals, and approval uses */ mapping (address => uint256) private balances; // Total token balances mapping (address => uint256) private balances90dayFreeze; // Balances frozen for 90 days after ICO end mapping (address => uint256) private balances180dayFreeze; // Balances frozen for 180 days after ICO end mapping (address => uint) private vestingTimesForPools; mapping (address => mapping (address => uint256)) private allowed; mapping (address => mapping (address => bool)) private allowanceUsed; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Transfer(address indexed spender, address indexed from, address indexed to, uint256 value); event VestingTransfer(address indexed from, address indexed to, uint256 value, uint256 vestingTime); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Issuance(uint256 _amount); // triggered when the total supply is increased event Destruction(uint256 _amount); // triggered when the total supply is decreased event NewTKLNToken(address _token); /* Miscellaneous */ uint256 public totalSupply = 0; bool public transfersEnabled = true; /** * Constructor * * Initializes contract with initial supply tokens to the creator of the contract */ function TKLNToken() public { owner = msg.sender; mintToken(presaleWallet); mintToken(generalSaleWallet); mintToken(wallet1); mintToken(wallet2); mintToken(wallet3); mintToken(wallet4); mintToken(wallet5); mintToken(wallet6); mintToken(foundersWallet); mintToken(wallet7); mintToken(wallet8genesis); mintToken(wallet9); mintToken(wallet10); mintToken(wallet11bounty); mintToken(wallet12); mintToken(wallet13rsv); mintToken(wallet14partners); mintToken(wallet15lottery); NewTKLNToken(address(this)); } modifier transfersAllowed { require(transfersEnabled); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * 1. Associate crowdsale contract address with this Token * 2. Allocate general sale amount * * @param _crowdsaleAddress - crowdsale contract address */ function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { approveAllocation(generalSaleWallet, _crowdsaleAddress); } /** * 1. Associate pre-sale contract address with this Token * 2. Allocate presale amount * * @param _presaleAddress - pre-sale contract address */ function approvePresale(address _presaleAddress) external onlyOwner { approveAllocation(presaleWallet, _presaleAddress); } function approveAllocation(AddressTokenAllocation tokenAllocation, address _crowdsaleAddress) internal { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint amount = tokenAllocation.amount * exponent; allowed[tokenAllocation.addr][_crowdsaleAddress] = amount; Approval(tokenAllocation.addr, _crowdsaleAddress, amount); } /** * Get token balance of an address * * @param _address - address to query * @return Token balance of _address */ function balanceOf(address _address) public constant returns (uint256 balance) { return balances[_address]; } /** * Get vested token balance of an address * * @param _address - address to query * @return balance that has vested */ function vestedBalanceOf(address _address) public constant returns (uint256 balance) { return balances[_address] - balances90dayFreeze[_address] - balances180dayFreeze[_address]; } /** * Get token amount allocated for a transaction from _owner to _spender addresses * * @param _owner - owner address, i.e. address to transfer from * @param _spender - spender address, i.e. address to transfer to * @return Remaining amount allowed to be transferred */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Send coins from sender's address to address specified in parameters * * @param _to - address to send to * @param _value - amount to send in Wei */ function transfer(address _to, uint256 _value) public transfersAllowed onlyPayloadSize(2*32) returns (bool success) { updateVesting(msg.sender); require(vestedBalanceOf(msg.sender) >= _value); // Subtract from the sender // _value is never greater than balance of input validation above balances[msg.sender] -= _value; // If tokens issued from this address need to vest (i.e. this address is a pool), freeze them here if (vestingTimesForPools[msg.sender] > 0) { addToVesting(msg.sender, _to, vestingTimesForPools[msg.sender], _value); } // Overflow is never possible due to input validation above balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } /** * Create token and credit it to target address * Created tokens need to vest * */ function mintToken(AddressTokenAllocation tokenAllocation) internal { // Add vesting time for this pool vestingTimesForPools[tokenAllocation.addr] = tokenAllocation.vestingTS; uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint mintedAmount = tokenAllocation.amount * exponent; // Mint happens right here: Balance becomes non-zero from zero balances[tokenAllocation.addr] += mintedAmount; totalSupply += mintedAmount; // Emit Issue and Transfer events Issuance(mintedAmount); Transfer(address(this), tokenAllocation.addr, mintedAmount); } /** * Allow another contract to spend some tokens on your behalf * * @param _spender - address to allocate tokens for * @param _value - number of tokens to allocate * @return True in case of success, otherwise false */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool success) { require(_value == 0 || allowanceUsed[msg.sender][_spender] == false); allowed[msg.sender][_spender] = _value; allowanceUsed[msg.sender][_spender] = false; Approval(msg.sender, _spender, _value); return true; } /** * Allow another contract to spend some tokens on your behalf * * @param _spender - address to allocate tokens for * @param _currentValue - current number of tokens approved for allocation * @param _value - number of tokens to allocate * @return True in case of success, otherwise false */ function approve(address _spender, uint256 _currentValue, uint256 _value) public onlyPayloadSize(3*32) returns (bool success) { require(allowed[msg.sender][_spender] == _currentValue); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * A contract attempts to get the coins. Tokens should be previously allocated * * @param _to - address to transfer tokens to * @param _from - address to transfer tokens from * @param _value - number of tokens to transfer * @return True in case of success, otherwise false */ function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed onlyPayloadSize(3*32) returns (bool success) { updateVesting(_from); // Check if the sender has enough require(vestedBalanceOf(_from) >= _value); // Check allowed require(_value <= allowed[_from][msg.sender]); // Subtract from the sender // _value is never greater than balance because of input validation above balances[_from] -= _value; // Add the same to the recipient // Overflow is not possible because of input validation above balances[_to] += _value; // Deduct allocation // _value is never greater than allowed amount because of input validation above allowed[_from][msg.sender] -= _value; // If tokens issued from this address need to vest (i.e. this address is a pool), freeze them here if (vestingTimesForPools[_from] > 0) { addToVesting(_from, _to, vestingTimesForPools[_from], _value); } Transfer(msg.sender, _from, _to, _value); allowanceUsed[_from][msg.sender] = true; return true; } /** * Default method * * This unnamed function is called whenever someone tries to send ether to * it. Just revert transaction because there is nothing that Token can do * with incoming ether. * * Missing payable modifier prevents accidental sending of ether */ function() public { } /** * Enable or disable transfers * * @param _enable - True = enable, False = disable */ function toggleTransfers(bool _enable) external onlyOwner { transfersEnabled = _enable; } /** * Destroy unsold preICO tokens * */ function closePresale() external onlyOwner { // Destroyed amount is never greater than total supply, // so no underflow possible here uint destroyedAmount = balances[presaleWallet.addr]; totalSupply -= destroyedAmount; balances[presaleWallet.addr] = 0; Destruction(destroyedAmount); Transfer(presaleWallet.addr, 0x0, destroyedAmount); } /** * Destroy unsold general sale tokens * */ function closeGeneralSale() external onlyOwner { // Destroyed amount is never greater than total supply, // so no underflow possible here uint destroyedAmount = balances[generalSaleWallet.addr]; totalSupply -= destroyedAmount; balances[generalSaleWallet.addr] = 0; Destruction(destroyedAmount); Transfer(generalSaleWallet.addr, 0x0, destroyedAmount); } function addToVesting(address _from, address _target, uint256 _vestingTime, uint256 _amount) internal { if (CrowdsaleParameters.vestingTime90Days == _vestingTime) { balances90dayFreeze[_target] += _amount; VestingTransfer(_from, _target, _amount, _vestingTime); } else if (CrowdsaleParameters.vestingTime180Days == _vestingTime) { balances180dayFreeze[_target] += _amount; VestingTransfer(_from, _target, _amount, _vestingTime); } } function updateVesting(address sender) internal { if (CrowdsaleParameters.vestingTime90Days < now) { balances90dayFreeze[sender] = 0; } if (CrowdsaleParameters.vestingTime180Days < now) { balances180dayFreeze[sender] = 0; } } }
Feb-20-2018 00:00:00 GMT
uint256 internal constant generalSaleEndDate = 1519120800;
2,551,311
[ 1, 2954, 70, 17, 3462, 17, 21849, 9631, 30, 713, 30, 713, 21706, 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, 2254, 5034, 2713, 5381, 7470, 30746, 24640, 273, 4711, 3657, 2138, 6840, 713, 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 ]
./full_match/1/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/CryptographIndexLogicV1.sol
@notice Insert a cryptograph in the array and return the new index position @dev Only callable by Factory @param _cryptograph The address of the cryptograph to insert in the index @return (uint) The new index position in the cryptograph arrayUpdate the ERC2665
function insertACryptograph(address _cryptograph) external restrictedToFactory() returns(uint){ ERC2665LogicV1(ERC2665Lieutenant).MintACryptograph(_cryptograph); cryptographs.push(_cryptograph); }
3,151,768
[ 1, 4600, 279, 13231, 8829, 316, 326, 526, 471, 327, 326, 394, 770, 1754, 225, 5098, 4140, 635, 7822, 225, 389, 22784, 8829, 1021, 1758, 434, 326, 13231, 8829, 358, 2243, 316, 326, 770, 327, 261, 11890, 13, 1021, 394, 770, 1754, 316, 326, 13231, 8829, 526, 1891, 326, 4232, 39, 5558, 9222, 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, 445, 2243, 2226, 2015, 8829, 12, 2867, 389, 22784, 8829, 13, 3903, 15693, 774, 1733, 1435, 1135, 12, 11890, 15329, 203, 203, 3639, 4232, 39, 5558, 9222, 20556, 58, 21, 12, 654, 39, 5558, 9222, 48, 1385, 322, 6602, 2934, 49, 474, 2226, 2015, 8829, 24899, 22784, 8829, 1769, 203, 3639, 13231, 8829, 87, 18, 6206, 24899, 22784, 8829, 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 ]
./full_match/42/0xCF489321d7940a93FfAA6922ea52202e3f8891cd/sources/test.sol
set to 1 * 10 ** 18
learnprice = _setlearnprice;
16,225,189
[ 1, 542, 358, 404, 225, 1728, 225, 6549, 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, 16094, 8694, 273, 389, 542, 21346, 8694, 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 ]
./full_match/77/0xbB642E83699392B0DfdfCd5cF5D27fb1EC33A6D1/sources/contracts/Stays.sol
Throws an error if verification of a voucher is fails
function _verifyCheckInVoucher(CheckInVoucher memory voucher) internal view returns (address) { bytes32 voucherHash = _hashTypedDataV4( keccak256( abi.encode( keccak256("Voucher(address from,address to,uint256 tokenId)"), voucher.from, voucher.to, voucher.tokenId ) ) ); (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(voucherHash, voucher.signature); require( error == ECDSA.RecoverError.NoError && recovered == voucher.from, "Broken voucher" ); return recovered; }
5,049,009
[ 1, 21845, 392, 555, 309, 11805, 434, 279, 331, 14329, 353, 6684, 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, 389, 8705, 1564, 382, 19585, 12, 1564, 382, 19585, 3778, 331, 14329, 13, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 565, 1731, 1578, 331, 14329, 2310, 273, 389, 2816, 11985, 751, 58, 24, 12, 203, 1377, 417, 24410, 581, 5034, 12, 203, 3639, 24126, 18, 3015, 12, 203, 1850, 417, 24410, 581, 5034, 2932, 19585, 12, 2867, 628, 16, 2867, 358, 16, 11890, 5034, 1147, 548, 2225, 3631, 203, 1850, 331, 14329, 18, 2080, 16, 203, 1850, 331, 14329, 18, 869, 16, 203, 1850, 331, 14329, 18, 2316, 548, 203, 3639, 262, 203, 1377, 262, 203, 565, 11272, 203, 203, 565, 261, 2867, 24616, 16, 7773, 19748, 18, 27622, 668, 555, 13, 273, 7773, 19748, 18, 698, 27622, 12, 90, 14329, 2310, 16, 331, 14329, 18, 8195, 1769, 203, 203, 565, 2583, 12, 203, 1377, 555, 422, 7773, 19748, 18, 27622, 668, 18, 2279, 668, 597, 24616, 422, 331, 14329, 18, 2080, 16, 203, 1377, 315, 29559, 331, 14329, 6, 203, 565, 11272, 203, 203, 565, 327, 24616, 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 ]
pragma solidity ^0.5.0; /** EthPM */ //import Ownable contract from openzeppelin-solidity for basic authorization control import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; //import SafeMath library from openzeppelin-solidity for integer overflows and underflow import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** @title MarketPlace: a simple smart contract for a market place on Ethereum. * @author Wafa AlDamegh. * @notice Final project for ConsenSys Academy's Developer Bootcamp 2019. */ contract MarketPlace is Ownable { //Uses SafeMath library to avoid integer overflow/underflow attacks using SafeMath for uint256; //state variables uint public storeOwnersCount; uint public adminCount; uint public storeCount; uint public productCount; bool public marktState; mapping (address => bool) public admins; mapping (address => bool) public storeOwners; mapping(uint => StoreFront) public storeFronts; mapping(address => uint[]) public storeOwnertoStoreFront; mapping(uint => address) public storeFronttoStoreOwner; mapping(uint => Product) public StoreProducts; mapping(uint => uint[]) public stotrFronttoProducts; //struct struct StoreFront { string storeName; address storeOwner; address approverAdmin; uint skuCount; uint balance; bool state; } struct Product { string name; uint storeNum; uint productNum; uint price; uint quantity; bool isAvailable; } //enum for address type enum addressTypes { marketOwner, admin, storeOwner, shopper } //events event adminAdded(address newAdmin); event adminRemoved(address admin); event storeOwnerAdded(address newStoreOwner); event storeOwnerRemoved(address storeOwner); event marketStateChanged(bool state); event storeFrontCreated(uint storeNum, string storeName, address storeOwner); event storeFrontApproved(uint storeNum, address admin); event productAdded(uint storeNum, string productName, uint productNum); event productPriceUpdated(uint storeNum, uint productNum); event productRemoved(uint storeNum, uint productNum); event storeWithdrawn(uint amount, uint storeNum, address storeOwner); event productPurchased(uint storeNum, uint productNum, uint quantity, address shopper); //modifiers /** @dev verifies the msg.sender is an admin */ modifier onlyAdmin() {require(admins[msg.sender], "Sorry, you are not admin!"); _;} /** @dev verifies the msg.sender is the store owner */ modifier onlyStoreOwner() {require(storeOwners[msg.sender], "Sorry, you are not a store owner!"); _;} /** @dev verifies market state */ modifier isMarketActive() {require(marktState, "Sorry, Market state is inactive!"); _;} /** @dev verifies the msg.sender is the store owner of the store front */ modifier verifyStoreOwner(uint storeNum) {require(storeFronttoStoreOwner[storeNum] == msg.sender, "Sorry, you are not a store owner!"); _;} /** @dev verifies the msg.sender is not a store owner or admin */ modifier onlyShopper(){require(!storeOwners[msg.sender], "Sorry, store owner is not allowed to buy products!"); require(!admins[msg.sender], "Sorry, admin is not allowed to buy products!"); _;} //functions /** @dev constracter initalises state variables */ constructor() public { admins[msg.sender] = true; storeOwnersCount = 0; adminCount = 1; storeCount = 0; productCount = 0; marktState = true; } /** @dev market owner allowed to add a new admin * @param _newAdmin new admin addrress */ function addAdmin(address _newAdmin) public onlyOwner() isMarketActive() { require(admins[_newAdmin] == false, "Sorry, Admin already exists!"); admins[_newAdmin] = true; adminCount = SafeMath.add(adminCount, 1); emit adminAdded(_newAdmin); } /** @dev market owner allowed to remove an admin * @param _admin admin addrress */ function removeAdmin(address _admin) public onlyOwner() { require(admins[_admin] == true, "Sorry, Admin not exists!"); admins[_admin] = false; adminCount = SafeMath.sub(adminCount, 1); emit adminRemoved(_admin); } /** @dev admin allowed to add a new store owner * @param _newStoreOwner new store owner addrress */ function addStoreOwner(address _newStoreOwner) public onlyAdmin() isMarketActive() { require(storeOwners[_newStoreOwner] == false, "Sorry, store owner already exists!"); storeOwners[_newStoreOwner] = true; storeOwnersCount = SafeMath.add(storeOwnersCount, 1); emit storeOwnerAdded(_newStoreOwner); } /** @dev admin allowed to remove a store owner * @param _storeOwner store owner addrress */ function removeStoreOwner(address _storeOwner) public onlyAdmin() isMarketActive() { require(storeOwners[_storeOwner] == true, "Sorry, store owner not exists!"); storeOwners[_storeOwner] = false; storeOwnersCount = SafeMath.sub(storeOwnersCount, 1); emit storeOwnerRemoved(_storeOwner); } /** @dev market owner allowed to chainge marketplace state * @param _state new market state */ function changeMarketState(bool _state) public onlyOwner { require(marktState != _state, "Sorry, it the the current state!!"); marktState = _state; emit marketStateChanged(_state); } /** @dev returns the current state of marketplace */ function getMarketState() public view returns(bool){ return marktState; } /** @dev returns (true) if the address is an admin, otherwise returns (false) */ function isAdmin(address _address) public view returns(bool) { return admins[_address]; } /** @dev returns the number of active admins */ function getNumberOfAdmins() public view onlyAdmin() returns(uint){ return adminCount; } /** @dev returns (true) if the address is store owner, otherwise returns (false) */ function isStoreOwner(address _address) public view returns(bool) { return storeOwners[_address]; } /** @dev returns the number of active store owners */ function getNumberOfStoreOwners() public view onlyAdmin() returns(uint) { return storeOwnersCount; } /** @dev returns the type of address (market owner, admin, store owner, or shopper) */ function addressType() public view returns(addressTypes) { if(msg.sender == super.owner()) return addressTypes.marketOwner; if(admins[msg.sender]) return addressTypes.admin; if(storeOwners[msg.sender]) return addressTypes.storeOwner; else return addressTypes.shopper; } /** @dev admin can approve created store frontreturns(bool) * @param _storeNum store number */ function approveStoreFront(uint _storeNum) public onlyAdmin() isMarketActive() { require(_storeNum <= storeCount, "Sorry, invalid store number!"); require((storeFronts[_storeNum].state) == false, "Sorry, store front is allrady approved!"); storeFronts[_storeNum].approverAdmin = msg.sender; storeFronts[_storeNum].state = true; emit storeFrontApproved(_storeNum, msg.sender); } /** @dev View contract balance * @return balance of all store fronts */ function getContractBalance() public view onlyOwner() returns(uint){ return address(this).balance; } /** @dev selfdestruct the contract to destroy the contract in case of bugs */ function destroyContract() public onlyOwner() { selfdestruct(address(this)); } //////////////////// /** Store Owner functions */ /** @dev store owner allowed to add a new store front * @param _storeName new market state * @return the store number */ function createStoreFront(string memory _storeName) public onlyStoreOwner() isMarketActive() returns(bool){ storeCount = SafeMath.add(storeCount, 1); storeFronts[storeCount] = StoreFront({storeName: _storeName, storeOwner: msg.sender, approverAdmin: address(0), skuCount: 0, balance: 0, state: false}); storeOwnertoStoreFront[msg.sender].push(storeCount); storeFronttoStoreOwner[storeCount] = msg.sender; emit storeFrontCreated(storeCount, _storeName, msg.sender); return true; } /** @dev Store owner allowed to add a new product to their store front * @param _storeNum store front number * @param _productName product name * @param _productPrice product price * @param _productQuantity available quantity of the product */ function addProduct(uint _storeNum, string memory _productName, uint _productPrice, uint _productQuantity) public verifyStoreOwner(_storeNum) isMarketActive() returns(uint){ require(storeFronts[_storeNum].state == true, "Sorry, store front is not approved yet!"); require(_productPrice > 0, "Sorry, invalid product price!"); require(_productQuantity > 0, "Sorry, invalid product quantity!"); storeFronts[_storeNum].skuCount = SafeMath.add(storeFronts[_storeNum].skuCount, 1); productCount = SafeMath.add(productCount,1); StoreProducts[productCount]= Product({name: _productName, storeNum: _storeNum, productNum: productCount, price: _productPrice, quantity: _productQuantity, isAvailable: true}); stotrFronttoProducts[_storeNum].push(productCount); emit productAdded(_storeNum, _productName, productCount); return productCount; } /** @dev Store owner allowed to update product price * @param _storeNum store front number * @param _productNum product nunmber * @param _newProductPrice product price */ function updateProductPrice(uint _storeNum, uint _productNum, uint _newProductPrice) public verifyStoreOwner(_storeNum) isMarketActive() returns(bool){ require(storeFronts[_storeNum].state == true, "Sorry, store front is not approved yet!"); require(_newProductPrice > 0, "Sorry, invalid product price!"); StoreProducts[_productNum].price = _newProductPrice; emit productPriceUpdated(_storeNum, _productNum); return true; } /** @dev Store owner allowed to remove product * @param _storeNum store front number * @param _productNum product nunmber */ function removeProduct(uint _storeNum, uint _productNum) public verifyStoreOwner(_storeNum) isMarketActive() returns(bool){ require(storeFronts[_storeNum].state == true, "Sorry, store front is not approved yet!"); StoreProducts[_productNum].isAvailable = false; StoreProducts[_productNum].quantity = 0; emit productRemoved(_storeNum, _productNum); return true; } /** @dev Store owner can withdraw balance from their store fronts * @param _storeNum store front number */ function withdraw(uint _storeNum) public payable verifyStoreOwner(_storeNum) isMarketActive() { require(storeFronts[_storeNum].balance > 0, "Sorry, no funds available!"); uint amount = storeFronts[_storeNum].balance; storeFronts[_storeNum].balance = 0; msg.sender.transfer(amount); emit storeWithdrawn(amount, _storeNum, msg.sender); } /** @dev return total number of store fronts */ function getStoreFrontCount() public view returns (uint) { return storeCount; } /** @dev return total number of product in the market */ function getProductCount() public view returns (uint) { return productCount; } /** @dev return total number of products in the store front * @param _storeNum store front number */ function getTotalProducts(uint _storeNum) public view returns (uint) { return storeFronts[_storeNum].skuCount; } /** @dev return store front info * @param _storeNum store front number */ function getStoreFrontInfo(uint _storeNum) public view returns(string memory, address, address, uint, uint, bool){ return ( storeFronts[_storeNum].storeName, storeFronts[_storeNum].storeOwner, storeFronts[_storeNum].approverAdmin, storeFronts[_storeNum].skuCount, storeFronts[_storeNum].balance, storeFronts[_storeNum].state ); } /** @dev return store front by store owner address */ function getStoreFrontByStoreOwner() public view returns(uint[] memory){ return storeOwnertoStoreFront[msg.sender]; } /** @dev return store owner address of the store front * @param _storeNum store front number */ function getStoreOwnerByStoreFront(uint _storeNum) public view returns(address){ return storeFronttoStoreOwner[_storeNum]; } /** @dev return products info * @param _productNum product number */ function getProductInfo(uint _productNum) public view returns(string memory, uint, uint, uint, uint, bool){ return ( StoreProducts[_productNum].name, StoreProducts[_productNum].storeNum, StoreProducts[_productNum].productNum, StoreProducts[_productNum].price, StoreProducts[_productNum].quantity, StoreProducts[_productNum].isAvailable ); } /** @dev return products by store front * @param _storeNum store front number */ function getProductsByStoreFront(uint _storeNum) public view returns(uint[] memory){ return stotrFronttoProducts[_storeNum]; } //////////////////// /** Shopper function */ /** @dev Shopper allowed to purchase a product * @param _storeNum store front number * @param _productNum product number */ function purchaseProduct( uint _storeNum, uint _productNum) public payable onlyShopper() isMarketActive() returns(bool){ require(StoreProducts[_productNum].price <= msg.value, "Sorry, transferred value is less than the product price!"); require(StoreProducts[_productNum].quantity > 0, "Sorry, product is not available!"); uint quantity = SafeMath.div(msg.value, StoreProducts[_productNum].price); StoreProducts[_productNum].quantity = SafeMath.sub(StoreProducts[_productNum].quantity, quantity); if (StoreProducts[_productNum].quantity == 0){StoreProducts[_productNum].isAvailable = false;} storeFronts[_storeNum].balance = SafeMath.add(storeFronts[_storeNum].balance,msg.value); emit productPurchased(_storeNum, _productNum, quantity, msg.sender); return true; } /** @dev fallback function */ function() external payable { } }
* @dev return products info @param _productNum product number/
function getProductInfo(uint _productNum) public view returns(string memory, uint, uint, uint, uint, bool){ return ( StoreProducts[_productNum].name, StoreProducts[_productNum].storeNum, StoreProducts[_productNum].productNum, StoreProducts[_productNum].price, StoreProducts[_productNum].quantity, StoreProducts[_productNum].isAvailable ); }
1,008,317
[ 1, 2463, 10406, 1123, 225, 389, 5896, 2578, 3017, 1300, 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, 15880, 966, 12, 11890, 389, 5896, 2578, 13, 1071, 1476, 1135, 12, 1080, 3778, 16, 2254, 16, 2254, 16, 2254, 16, 2254, 16, 1426, 15329, 203, 3639, 327, 261, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 529, 16, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 2233, 2578, 16, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 5896, 2578, 16, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 8694, 16, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 16172, 16, 203, 3639, 4994, 13344, 63, 67, 5896, 2578, 8009, 291, 5268, 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 ]
// File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @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 is Initializable { address private _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. */ function initialize(address sender) public initializer { _owner = sender; } /** * @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 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; } uint256[50] private ______gap; } // File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork 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. */ pragma solidity >=0.4.24; /** * @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; } } // File: contracts/lib/UInt256Lib.sol pragma solidity >=0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // File: contracts/interface/ISeigniorageShares.sol pragma solidity >=0.4.24; interface ISeigniorageShares { function setDividendPoints(address account, uint256 totalDividends) external returns (bool); function mintShares(address account, uint256 amount) external returns (bool); function lastDividendPoints(address who) external view returns (uint256); function externalRawBalanceOf(address who) external view returns (uint256); function externalTotalSupply() external view returns (uint256); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @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-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @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-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: contracts/dollars.sol pragma solidity >=0.4.24; interface IDollarPolicy { function getUsdSharePrice() external view returns (uint256 price); } /* * Dollar ERC20 */ contract Dollars is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogContraction(uint256 indexed epoch, uint256 dollarsToBurn); event LogRebasePaused(bool paused); event LogBurn(address indexed from, uint256 value); event LogClaim(address indexed from, uint256 value); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; address public sharesAddress; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } // Precautionary emergency controls. bool public rebasePaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } // coins needing to be burned (9 decimals) uint256 private _remainingDollarsToBeBurned; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_DOLLAR_SUPPLY = 1 * 10**6 * 10**DECIMALS; uint256 private _maxDiscount; modifier validDiscount(uint256 discount) { require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH'); _; } uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private constant POINT_MULTIPLIER = 10 ** 9; uint256 private _totalDividendPoints; uint256 private _unclaimedDividends; ISeigniorageShares shares; mapping(address => uint256) private _dollarBalances; // This is denominated in Dollars, because the cents-dollars conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedDollars; IDollarPolicy dollarPolicy; uint256 public burningDiscount; // percentage (10 ** 9 Decimals) uint256 public defaultDiscount; // discount on first negative rebase uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions uint256 public minimumBonusThreshold; bool reEntrancyMutex; bool reEntrancyRebaseMutex; address public uniswapV2Pool; modifier uniqueAddresses(address addr1, address addr2) { require(addr1 != addr2, "Addresses are not unique"); _; } /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; dollarPolicy = IDollarPolicy(monetaryPolicy_); emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function setUniswapV2SyncAddress(address uniswapV2Pair_) external onlyOwner { uniswapV2Pool = uniswapV2Pair_; } function test() external onlyOwner { uniswapV2Pool.call(abi.encodeWithSignature('sync()')); } function setBurningDiscount(uint256 discount) external onlyOwner validDiscount(discount) { burningDiscount = discount; } // amount in is 10 ** 9 decimals function burn(uint256 amount) external updateAccount(msg.sender) { require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); reEntrancyMutex = true; require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE'); require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); _burn(msg.sender, amount); reEntrancyMutex = false; } function setDefaultDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDiscount = discount; } function setMaxDiscount(uint256 discount) external onlyOwner { _maxDiscount = discount; } function setDefaultDailyBonusDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDailyBonusDiscount = discount; } /** * @dev Pauses or unpauses the execution of rebase operations. * @param paused Pauses rebase operations if this is true. */ function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } // action of claiming funds function claimDividends(address account) external updateAccount(account) returns (uint256) { uint256 owing = dividendsOwing(account); return owing; } function setMinimumBonusThreshold(uint256 minimum) external onlyOwner { require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH'); minimumBonusThreshold = minimum; } /** * @dev Notifies Dollars contract about a new rebase cycle. * @param supplyDelta The number of new dollar tokens to add into circulation via expansion. * @return The total number of dollars after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { reEntrancyRebaseMutex = true; uint256 burningDefaultDiscount = burningDiscount.add(defaultDailyBonusDiscount); if (supplyDelta == 0) { if (_remainingDollarsToBeBurned > minimumBonusThreshold) { burningDiscount = burningDefaultDiscount > _maxDiscount ? _maxDiscount : burningDefaultDiscount; } else { burningDiscount = defaultDiscount; } emit LogRebase(epoch, _totalSupply); } else if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); uint256 tenPercent = _totalSupply.div(10); if (dollarsToBurn > tenPercent) { // maximum contraction is 10% of the total USD Supply dollarsToBurn = tenPercent; } if (dollarsToBurn.add(_remainingDollarsToBeBurned) > _totalSupply) { dollarsToBurn = _totalSupply.sub(_remainingDollarsToBeBurned); } if (_remainingDollarsToBeBurned > minimumBonusThreshold) { burningDiscount = burningDefaultDiscount > _maxDiscount ? _maxDiscount : burningDefaultDiscount; } else { burningDiscount = defaultDiscount; // default 1% } _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.add(dollarsToBurn); emit LogContraction(epoch, dollarsToBurn); } else { disburse(uint256(supplyDelta)); uniswapV2Pool.call(abi.encodeWithSignature('sync()')); emit LogRebase(epoch, _totalSupply); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } } reEntrancyRebaseMutex = false; return _totalSupply; } function initialize(address owner_, address seigniorageAddress) public initializer { ERC20Detailed.initialize("Dollars", "USD", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; _totalSupply = INITIAL_DOLLAR_SUPPLY; sharesAddress = seigniorageAddress; shares = ISeigniorageShares(seigniorageAddress); _dollarBalances[owner_] = _totalSupply; _maxDiscount = 50 * 10 ** 9; // 50% defaultDiscount = 1 * 10 ** 9; // 1% burningDiscount = defaultDiscount; defaultDailyBonusDiscount = 1 * 10 ** 9; // 1% minimumBonusThreshold = 100 * 10 ** 9; // 100 dollars is the minimum threshold. Anything above warrants increased discount emit Transfer(address(0x0), owner_, _totalSupply); } function dividendsOwing(address account) public view returns (uint256) { if (_totalDividendPoints > shares.lastDividendPoints(account)) { uint256 newDividendPoints = _totalDividendPoints.sub(shares.lastDividendPoints(account)); uint256 sharesBalance = shares.externalRawBalanceOf(account); return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER); } else { return 0; } } // auto claim modifier // if user is owned, we pay out immedietly // if user is not owned, we prevent them from claiming until the next rebase modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing != 0) { _unclaimedDividends = _unclaimedDividends.sub(owing); _dollarBalances[account] += owing; } shares.setDividendPoints(account, _totalDividendPoints); emit LogClaim(account, owing); _; } /** * @return The total number of dollars. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _dollarBalances[who].add(dividendsOwing(who)); } function getRemainingDollarsToBeBurned() public view returns (uint256) { return _remainingDollarsToBeBurned; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public uniqueAddresses(msg.sender, to) validRecipient(to) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(value); _dollarBalances[to] = _dollarBalances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedDollars[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _allowedDollars[from][msg.sender] = _allowedDollars[from][msg.sender].sub(value); _dollarBalances[from] = _dollarBalances[from].sub(value); _dollarBalances[to] = _dollarBalances[to].add(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. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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 uniqueAddresses(msg.sender, spender) validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @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 uniqueAddresses(msg.sender, spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[msg.sender][spender] = _allowedDollars[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @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 uniqueAddresses(msg.sender, spender) updateAccount(spender) updateAccount(msg.sender) returns (bool) { uint256 oldValue = _allowedDollars[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedDollars[msg.sender][spender] = 0; } else { _allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } function consultBurn(uint256 amount) public returns (uint256) { require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); // 1 share = x dollars uint256 decimals = 10 ** 9; uint256 percentDenominator = 100; usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); // 10^9 uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); // 10^9 return sharesToMint; } function unclaimedDividends() public view returns (uint256) { return _unclaimedDividends; } function totalDividendPoints() public view returns (uint256) { return _totalDividendPoints; } function disburse(uint256 amount) internal returns (bool) { _totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(shares.externalTotalSupply())); _totalSupply = _totalSupply.add(amount); _unclaimedDividends = _unclaimedDividends.add(amount); return true; } function _burn(address account, uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); _dollarBalances[account] = _dollarBalances[account].sub(amount); uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); // 1 share = x dollars uint256 decimals = 10 ** 9; uint256 percentDenominator = 100; usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); // 10^9 uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); // 10^9 _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.sub(amount); shares.mintShares(account, sharesToMint); emit Transfer(account, address(0), amount); emit LogBurn(account, amount); } } // File: contracts/dollarsPolicy.sol pragma solidity >=0.4.24; /* * Dollar Policy */ interface IDecentralizedOracle { function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); } contract DollarsPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Dollars public dollars; // Provides the current CPI, as an 18 decimal fixed point number. IDecentralizedOracle public sharesPerUsdOracle; IDecentralizedOracle public ethPerUsdOracle; IDecentralizedOracle public ethPerUsdcOracle; uint256 public deviationThreshold; uint256 public rebaseLag; uint256 private cpi; uint256 public minRebaseTimeIntervalSec; uint256 public lastRebaseTimestampSec; uint256 public rebaseWindowOffsetSec; uint256 public rebaseWindowLengthSec; uint256 public epoch; address WETH_ADDRESS; address SHARE_ADDRESS; uint256 private constant DECIMALS = 18; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; address public orchestrator; bool private initializedOracle; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } uint256 public minimumDollarCirculation; function getUsdSharePrice() external view returns (uint256) { sharesPerUsdOracle.update(); uint256 shareDecimals = 10 ** 9; uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); // 10^9 decimals return sharePrice; } function rebase() external onlyOrchestrator { require(inRebaseWindow(), "OUTISDE_REBASE"); require(initializedOracle, 'ORACLE_NOT_INITIALIZED'); require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "MIN_TIME_NOT_MET"); lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); sharesPerUsdOracle.update(); ethPerUsdOracle.update(); ethPerUsdcOracle.update(); uint256 wethDecimals = 10 ** 18; uint256 shareDecimals = 10 ** 9; uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 1 * wethDecimals); // 10^18 decimals ropsten, 10^6 mainnet uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 1 * wethDecimals); // 10^9 decimals uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(10 ** 21) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet .div(ethUsdPrice); uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); // 10^9 decimals uint256 shareExchangeRate = sharePrice.mul(dollarCoinExchangeRate).div(shareDecimals); // 10^18 decimals uint256 targetRate = cpi; if (dollarCoinExchangeRate > MAX_RATE) { dollarCoinExchangeRate = MAX_RATE; } // dollarCoinExchangeRate & targetRate arre 10^18 decimals int256 supplyDelta = computeSupplyDelta(dollarCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals // Apply the Dampening factor. // supplyDelta = supplyDelta.mul(10 ** 9).div(rebaseLag.toInt256Safe()); uint256 algorithmicLag_ = getAlgorithmicRebaseLag(supplyDelta); require(algorithmicLag_ != 0, "algorithmic rate must be positive"); rebaseLag = algorithmicLag_; supplyDelta = supplyDelta.mul(10 ** 9).div(algorithmicLag_.toInt256Safe()); // v 0.0.1 // check on the expansionary side if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe(); } // check on the contraction side if (supplyDelta < 0 && dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.getRemainingDollarsToBeBurned())).toInt256Safe(); } // set minimum floor if (supplyDelta < 0 && dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs()))) < minimumDollarCirculation) { supplyDelta = (dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned()).sub(minimumDollarCirculation)).toInt256Safe(); } uint256 supplyAfterRebase; if (supplyDelta < 0) { // contraction, we send the amount of shares to mint uint256 dollarsToBurn = uint256(supplyDelta.abs()); supplyAfterRebase = dollars.rebase(epoch, (dollarsToBurn).toInt256Safe().mul(-1)); } else { // expansion, we send the amount of dollars to mint supplyAfterRebase = dollars.rebase(epoch, supplyDelta); } assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, dollarCoinExchangeRate, cpi, supplyDelta, now); } function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } function setCpi(uint256 cpi_) external onlyOwner { require(cpi_ != 0); cpi = cpi_; } function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ != 0); rebaseLag = rebaseLag_; } function initializeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { require(!initializedOracle, 'ALREADY_INITIALIZED_ORACLE'); sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); initializedOracle = true; } function changeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); } function setWethAddress(address wethAddress) external onlyOwner { WETH_ADDRESS = wethAddress; } function setShareAddress(address shareAddress) external onlyOwner { SHARE_ADDRESS = shareAddress; } function setMinimumDollarCirculation(uint256 minimumDollarCirculation_) external onlyOwner { minimumDollarCirculation = minimumDollarCirculation_; } function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ != 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } function initialize(address owner_, Dollars dollars_) public initializer { Ownable.initialize(owner_); deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 50 * 10 ** 9; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug) rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; cpi = 1 * 10 ** 18; epoch = 0; minimumDollarCirculation = 1000000 * 10 ** 9; // 1M minimum dollar circulation dollars = dollars_; } // takes current marketcap of USD and calculates the algorithmic rebase lag // returns 10 ** 9 rebase lag factor function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) { if (dollars.totalSupply() >= 30000000 * 10 ** 9) { return 30 * 10 ** 9; } else { if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15 return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000)); } else { return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9); } } } function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return dollars.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } // File: contracts/orchestrator.sol pragma solidity >=0.4.24; /* * Orchestrator */ contract Orchestrator is Ownable { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); Transaction[] public transactions; DollarsPolicy public policy; constructor(address policy_) public { Ownable.initialize(msg.sender); policy = DollarsPolicy(policy_); } function rebase() external { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin policy.rebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } function transactionsSize() external view returns (uint256) { return transactions.length; } function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } }
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication./
function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; dollarPolicy = IDollarPolicy(monetaryPolicy_); emit LogMonetaryPolicyUpdated(monetaryPolicy_); }
400,548
[ 1, 2586, 14911, 2582, 67, 1021, 1758, 434, 326, 31198, 3329, 6835, 358, 999, 364, 5107, 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 ]
[ 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, 565, 445, 444, 11415, 14911, 2582, 12, 2867, 31198, 2582, 67, 13, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 31198, 2582, 273, 31198, 2582, 67, 31, 203, 3639, 302, 25442, 2582, 273, 1599, 25442, 2582, 12, 2586, 14911, 2582, 67, 1769, 203, 3639, 3626, 1827, 11415, 14911, 2582, 7381, 12, 2586, 14911, 2582, 67, 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 ]
./full_match/42/0x1c3633676E7e843A80886EBeA23176cB8a40068e/sources/browser/ACOPoolStrategy.sol
* @dev Emitted when the order size factors has been changed. orderSizePenaltyFactor order size percentage ^ orderSizeDampingFactor @param oldOrderSizeMultiplierFactor Value of the previous order size multiplier factor. @param oldOrderSizeDividerFactor Value of the previous order size divider factor. @param oldOrderSizeExponentialFactor Value of the previous order size exponential factor. @param newOrderSizeMultiplierFactor Value of the new order size penalty factor. @param newOrderSizeDividerFactor Value of the new order size divider factor. @param newOrderSizeExponentialFactor Value of the new order size exponential factor./* @dev Emitted when the underlying price percentage adjust has been changed. @param oldUnderlyinPriceAdjustPercentage Value of the previous percentage adjust on the underlying price to calculate the option price. @param newUnderlyingPriceAdjustPercentage Value of the new percentage adjust on the underlying price to calculate the option price./* @dev Emitted when the minimum percentage for the option price calculation has been changed. @param oldMinOptionPricePercentage Value of the previous minimum percentage for the option price calculation. @param newMinOptionPricePercentage Value of the new minimum percentage for the option price calculation./* @dev Emitted when the asset precision has been changed. @param asset Address of the asset. @param oldAssetPrecision Value of the previous asset precision. @param newAssetPrecision Value of the new asset precision./* @dev The percentage precision. (100000 = 100%)/* @dev The percentage adjust on the underlying price to calculate the option price./* @dev The minimum percentage for the option price calculation./* @dev The order size multiplier factor./* @dev The order size divider factor./* @dev The order size exponential factor./* @dev The asset precision. (6 decimals = 1000000)/* @dev The order size exponential divider factor used on the calculation./
) public { super.init(); _setUnderlyingPriceAdjustPercentage(_underlyingPriceAdjustPercentage); _setMinOptionPricePercentage(_minOptionPricePercentage); _setOrderSizeFactors(_orderSizeMultiplierFactor, _orderSizeDividerFactor, _orderSizeExponentialFactor); }
9,592,496
[ 1, 1514, 11541, 1347, 326, 1353, 963, 14490, 711, 2118, 3550, 18, 1353, 1225, 24251, 15006, 6837, 225, 1353, 963, 11622, 3602, 1353, 1225, 40, 931, 310, 6837, 225, 1592, 2448, 1225, 23365, 6837, 1445, 434, 326, 2416, 1353, 963, 15027, 5578, 18, 225, 1592, 2448, 1225, 25558, 6837, 1445, 434, 326, 2416, 1353, 963, 21713, 5578, 18, 225, 1592, 2448, 1225, 17972, 649, 6837, 1445, 434, 326, 2416, 1353, 963, 21774, 5578, 18, 225, 394, 2448, 1225, 23365, 6837, 1445, 434, 326, 394, 1353, 963, 23862, 5578, 18, 225, 394, 2448, 1225, 25558, 6837, 1445, 434, 326, 394, 1353, 963, 21713, 5578, 18, 225, 394, 2448, 1225, 17972, 649, 6837, 1445, 434, 326, 394, 1353, 963, 21774, 5578, 18, 19, 225, 512, 7948, 1347, 326, 6808, 6205, 11622, 5765, 711, 2118, 3550, 18, 225, 1592, 14655, 715, 267, 5147, 10952, 16397, 1445, 434, 326, 2416, 11622, 5765, 603, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 262, 1071, 288, 203, 202, 202, 9565, 18, 2738, 5621, 203, 1082, 203, 3639, 389, 542, 14655, 6291, 5147, 10952, 16397, 24899, 9341, 6291, 5147, 10952, 16397, 1769, 203, 202, 202, 67, 542, 2930, 1895, 5147, 16397, 24899, 1154, 1895, 5147, 16397, 1769, 203, 3639, 389, 542, 2448, 1225, 23535, 24899, 1019, 1225, 23365, 6837, 16, 389, 1019, 1225, 25558, 6837, 16, 389, 1019, 1225, 17972, 649, 6837, 1769, 203, 565, 289, 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 ]
./full_match/4/0xdbD79a5fd475B6370AE1acfaA4301bF287568900/sources/Lottery1.sol
dynamic array of players addresses
address[] public players;
715,205
[ 1, 14507, 526, 434, 18115, 6138, 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, 1758, 8526, 1071, 18115, 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 ]
./full_match/4/0xB26Fac8092a2FA52b3Db3CA415051637C3A15FA4/sources/contracts/EOC_Beta.sol
* @dev Update merkle root to reflect changes in Allowlist @param _newMerkleRoot new merkle root to reflect most recent Allowlist/
function updateMerkleRoot(bytes32 _newMerkleRoot) public onlyOwner { require(_newMerkleRoot != merkleRoot, "Merkle root will be unchanged!"); merkleRoot = _newMerkleRoot; }
811,670
[ 1, 1891, 30235, 1365, 358, 3037, 3478, 316, 7852, 1098, 225, 389, 2704, 8478, 15609, 2375, 394, 30235, 1365, 358, 3037, 4486, 8399, 7852, 1098, 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, 1089, 8478, 15609, 2375, 12, 3890, 1578, 389, 2704, 8478, 15609, 2375, 13, 1071, 1338, 5541, 288, 203, 1377, 2583, 24899, 2704, 8478, 15609, 2375, 480, 30235, 2375, 16, 315, 8478, 15609, 1365, 903, 506, 14827, 4442, 1769, 203, 1377, 30235, 2375, 273, 389, 2704, 8478, 15609, 2375, 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 ]
./full_match/3/0x758efC0c2Fd5eA15E9E92E904462559c6eC70deC/sources/a1.sol
@notice Factory for UchiToken creation.
contract UchiTokenFactory is BaseBoringBatchable { address public uchiDAO = msg.sender; ISushiSwapLaunch constant sushiSwapRouter = ISushiSwapLaunch(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506); mapping(address => uint256) public uchiList; event DeployUchiToken(address indexed uchiToken); event UpdateUchiList(address indexed account, uint256 indexed list, string details); function deployUchiToken( ) external payable returns (UchiToken uchiToken) { uchiToken = new UchiToken( _uchi, _name, _symbol, _timeRestrictionEnds, _totalSupplyCap, pairDistro, uchiDistro); uchiToken.approve(address(sushiSwapRouter), pairDistro); initMarket(address(uchiToken), pairDistro, _uchi[0]); emit DeployUchiToken(address(uchiToken)); } if(list != 0){checkList(_uchi, list);} for(uint256 i = 0; i < uchi.length; i++){require(uchiList[uchi[i]] == list, "!listed");} }
8,218,594
[ 1, 1733, 364, 587, 24010, 1345, 6710, 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 ]
[ 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, 16351, 587, 24010, 1345, 1733, 353, 3360, 38, 6053, 4497, 429, 288, 203, 565, 1758, 1071, 582, 24010, 18485, 273, 1234, 18, 15330, 31, 203, 565, 4437, 1218, 77, 12521, 9569, 5381, 272, 1218, 77, 12521, 8259, 273, 4437, 1218, 77, 12521, 9569, 12, 20, 92, 21, 70, 3103, 72, 37, 28, 15237, 20, 72, 5908, 27, 73, 38, 28, 40, 10321, 37, 4033, 25, 70, 5482, 71, 27, 40, 28, 70, 9462, 2733, 27, 3361, 26, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 582, 24010, 682, 31, 203, 565, 871, 7406, 57, 24010, 1345, 12, 2867, 8808, 582, 24010, 1345, 1769, 203, 565, 871, 2315, 57, 24010, 682, 12, 2867, 8808, 2236, 16, 2254, 5034, 8808, 666, 16, 533, 3189, 1769, 203, 377, 203, 565, 445, 7286, 57, 24010, 1345, 12, 203, 565, 262, 3903, 8843, 429, 1135, 261, 57, 24010, 1345, 582, 24010, 1345, 13, 288, 203, 3639, 582, 24010, 1345, 273, 394, 587, 24010, 1345, 12, 203, 5411, 389, 2648, 77, 16, 203, 5411, 389, 529, 16, 7010, 5411, 389, 7175, 16, 203, 5411, 389, 957, 11670, 24980, 16, 203, 5411, 389, 4963, 3088, 1283, 4664, 16, 203, 5411, 3082, 5133, 303, 16, 203, 5411, 582, 24010, 5133, 303, 1769, 203, 3639, 582, 24010, 1345, 18, 12908, 537, 12, 2867, 12, 87, 1218, 77, 12521, 8259, 3631, 3082, 5133, 303, 1769, 203, 3639, 1208, 3882, 278, 12, 2867, 12, 2648, 77, 1345, 3631, 3082, 5133, 303, 16, 389, 2648, 77, 63, 20, 19226, 203, 3639, 3626, 2 ]
./full_match/4/0x6DF8EE677656b9f6da6079A5f0281Bb1C961862e/sources/_openzeppelin/contracts-upgradeable_4.4.0/governance/extensions/GovernorVotesUpgradeable.sol
* Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes})./
function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { return token.getPastVotes(account, blockNumber); } uint256[50] private __gap;
729,308
[ 1, 1994, 326, 331, 17128, 3119, 628, 326, 1147, 1807, 6650, 316, 4439, 12860, 261, 5946, 288, 3047, 1643, 29561, 17, 588, 29637, 97, 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 ]
[ 1, 1, 1, 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, 11031, 6366, 12, 2867, 2236, 16, 2254, 5034, 1203, 1854, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1147, 18, 588, 52, 689, 29637, 12, 4631, 16, 1203, 1854, 1769, 203, 565, 289, 203, 565, 2254, 5034, 63, 3361, 65, 3238, 1001, 14048, 31, 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 ]
./full_match/84531/0x70302d7cFfCb2a56A39DAf66DC4410fFF2B0242d/sources/contracts/lzApp/LzAppUpgradeable.sol
generic config for LayerZero user Application
function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external override onlyAdmin { lzEndpoint.setConfig(_version, _chainId, _configType, _config); }
14,311,251
[ 1, 13540, 642, 364, 12112, 7170, 729, 4257, 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, 15517, 12, 203, 3639, 2254, 2313, 389, 1589, 16, 203, 3639, 2254, 2313, 389, 5639, 548, 16, 203, 3639, 2254, 5034, 389, 1425, 559, 16, 203, 3639, 1731, 745, 892, 389, 1425, 203, 565, 262, 3903, 3849, 1338, 4446, 288, 203, 3639, 328, 94, 3293, 18, 542, 809, 24899, 1589, 16, 389, 5639, 548, 16, 389, 1425, 559, 16, 389, 1425, 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 ]
./full_match/3/0xA3E23D172bd87dAF6BDCce435CA00dA6d94691D8/sources/browser/ShopContract.sol
address(this).balance += msg.value; for(uint i=0; i<products.length(); i++){ }
function buyProducts() public payable { require(msg.value <= msg.sender.balance); }
8,117,747
[ 1, 2867, 12, 2211, 2934, 12296, 1011, 1234, 18, 1132, 31, 364, 12, 11890, 277, 33, 20, 31, 277, 32, 18736, 18, 2469, 5621, 277, 27245, 95, 289, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 13344, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1648, 1234, 18, 15330, 18, 12296, 1769, 203, 540, 203, 540, 203, 2398, 203, 565, 289, 203, 377, 203, 377, 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, -100, -100, -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() { _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 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 making 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; /** * @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.6; import "./interfaces/IGovernanceToken.sol"; import "../lib/openzeppelin-contracts/contracts/access/Ownable.sol"; /** * @title Delegator Contract * @author Cryptex.Finance * @notice Contract in charge of handling delegations. */ contract Delegator is Ownable { /* ========== STATE VARIABLES ========== */ /// @notice Address of the staking governance token address public immutable token; /// @notice Tracks the amount of staked tokens per user mapping(address => uint256) public stakerBalance; /* ========== CONSTRUCTOR ========== */ /** * @notice Constructor * @param delegatee_ address * @param token_ address * @dev when created delegates all it's power to delegatee_ and can't be changed later * @dev sets delegator factory as owner */ constructor(address delegatee_, address token_) { require( delegatee_ != address(0) && token_ != address(0), "Address can't be 0" ); require(IGovernanceToken(token_).decimals() == 18, "Decimals must be 18"); token = token_; IGovernanceToken(token_).delegate(delegatee_); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Increases the balance of the staker * @param staker_ caller of the stake function * @param amount_ uint to be staked and delegated * @dev Only delegatorFactory can call it * @dev after the balance is updated the amount is transferred from the user to this contract */ function stake(address staker_, uint256 amount_) external onlyOwner { stakerBalance[staker_] += amount_; } /** * @notice Decreases the balance of the staker * @param staker_ caller of the stake function * @param amount_ uint to be withdrawn and undelegated * @dev Only delegatorFactory can call it * @dev after the balance is updated the amount is transferred back to the user from this contract */ function removeStake(address staker_, uint256 amount_) external onlyOwner { stakerBalance[staker_] -= amount_; require( IGovernanceToken(token).transfer(staker_, amount_), "Transfer failed" ); } /* ========== VIEWS ========== */ /// @notice returns the delegatee of this contract function delegatee() external returns (address) { return IGovernanceToken(token).delegates(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "./interfaces/IGovernanceToken.sol"; import "./Delegator.sol"; import "../lib/openzeppelin-contracts/contracts/access/Ownable.sol"; import "../lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol"; /** * @title Delegator Contract Factory * @author Cryptex.Finance * @notice Contract in charge of generating Delegator contracts, handling delegations and CTX balance map, rewards. */ contract DelegatorFactory is Ownable, ReentrancyGuard { /* ========== STATE VARIABLES ========== */ /// @notice Address of the staking governance token address public immutable stakingToken; /// @notice Address of the reward token address public immutable rewardsToken; /// @notice Minimum wait time before removing stake uint256 public waitTime; /// @notice Tracks the period where users stop earning rewards uint256 public periodFinish = 0; uint256 public rewardRate = 0; /// @notice How long the rewards lasts, it updates when more rewards are added uint256 public rewardsDuration = 186 days; /// @notice Last time rewards were updated uint256 public lastUpdateTime; /// @notice Amount of reward calculated per token stored uint256 public rewardPerTokenStored; /// @notice Track the rewards paid to users mapping(address => uint256) public userRewardPerTokenPaid; /// @notice Tracks the user rewards mapping(address => uint256) public rewards; /// @notice Tracks the address of a delegatee with a delegator contract address mapping(address => address) public delegatorToDelegatee; /// @notice Tracks the delegator contract address from delegatee address mapping(address => address) public delegateeToDelegator; /// @notice Tracks if address is an official delegator mapping(address => bool) public delegators; /// @notice Tracks minimum wait time the account has to wait before removing stake mapping(address => mapping(address => uint256)) public stakerWaitTime; /// @dev Tracks the total supply of staked tokens uint256 private _totalSupply; /// @dev Tracks the amount of staked tokens per user mapping(address => uint256) private _balances; /* ========== EVENTS ========== */ /// @notice An event emitted when a Delegator is created event DelegatorCreated(address indexed delegator, address indexed delegatee); /// @notice An event emitted when an user has staked and delegated event Staked( address indexed delegator, address indexed delegatee, uint256 amount ); /// @notice An event emitted when an user removes stake and undelegated event Withdrawn( address indexed delegator, address indexed delegatee, uint256 amount ); /// @notice An event emitted when the minimum wait time is updated event WaitTimeUpdated(uint256 waitTime); /// @notice An event emitted when a reward is added event RewardAdded(uint256 reward); /// @notice An event emitted when reward is paid to a user event RewardPaid(address indexed user, uint256 reward); /// @notice An event emitted when the rewards duration is updated event RewardsDurationUpdated(uint256 newDuration); /* ========== CONSTRUCTOR ========== */ /** * @notice Constructor * @param stakingToken_ address * @param rewardsToken_ address * @param waitTime_ uint256 * @param timelock_ address * @dev transfers ownership to timelock */ constructor( address stakingToken_, address rewardsToken_, uint256 waitTime_, address timelock_ ) { require( stakingToken_ != address(0) && rewardsToken_ != address(0) && timelock_ != address(0), "Address can't be 0" ); require( IGovernanceToken(stakingToken_).decimals() == 18 && IGovernanceToken(rewardsToken_).decimals() == 18, "Decimals must be 18" ); stakingToken = stakingToken_; rewardsToken = rewardsToken_; waitTime = waitTime_; transferOwnership(timelock_); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Updates the reward and time on call. * @param account_ address */ function updateReward(address account_) private { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account_ != address(0)) { rewards[account_] = currentEarned(account_); userRewardPerTokenPaid[account_] = rewardPerTokenStored; } } /** * @notice Notifies the contract that reward has been added to be given. * @param reward_ uint * @dev Only owner can call it * @dev Increases duration of rewards */ function notifyRewardAmount(uint256 reward_) external onlyOwner { updateReward(address(0)); if (block.timestamp >= periodFinish) { rewardRate = reward_ / rewardsDuration; } else { uint256 remaining = periodFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward_ + leftover) / rewardsDuration; } lastUpdateTime = block.timestamp; periodFinish = block.timestamp + 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. uint256 balance = IGovernanceToken(rewardsToken).balanceOf(address(this)); require( rewardRate <= balance / rewardsDuration, "Provided reward too high" ); emit RewardAdded(reward_); } /** * @notice Updates the reward duration * @param rewardsDuration_ uint * @dev Only owner can call it * @dev Previous rewards must be complete */ function setRewardsDuration(uint256 rewardsDuration_) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = rewardsDuration_; emit RewardsDurationUpdated(rewardsDuration); } /** * @notice Transfers to the caller the current amount of rewards tokens earned. * @dev updates rewards on call */ function getReward() external nonReentrant { updateReward(msg.sender); uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; require( IGovernanceToken(rewardsToken).transfer(msg.sender, reward), "Transfer Failed" ); emit RewardPaid(msg.sender, reward); } } /** * @notice Creates a new delegator contract that delegates all votes to delegatee_ * @param delegatee_ address that will be receiving all votes * @dev only one delegator contract pointing to the same delegatee can exist */ function createDelegator(address delegatee_) external { require(delegatee_ != address(0), "Delegatee can't be 0"); require( delegateeToDelegator[delegatee_] == address(0), "Delegator already created" ); Delegator delegator = new Delegator(delegatee_, stakingToken); delegateeToDelegator[delegatee_] = address(delegator); delegatorToDelegatee[address(delegator)] = delegatee_; delegators[address(delegator)] = true; emit DelegatorCreated(address(delegator), delegatee_); } /** * @notice Stakes to delegator_ the amount_ specified * @param delegator_ contract address where to send the amount_ * @param amount_ uint to be staked and delegated * @dev Delegator must be valid and amount has to be greater than 0 * @dev amount_ is transferred to the delegator contract and staker starts earning rewards if active * @dev updates rewards on call */ function stake(address delegator_, uint256 amount_) external nonReentrant { require(delegators[delegator_], "Not a valid delegator"); require(amount_ > 0, "Amount must be greater than 0"); updateReward(msg.sender); _totalSupply = _totalSupply + amount_; _balances[msg.sender] = _balances[msg.sender] + amount_; Delegator d = Delegator(delegator_); d.stake(msg.sender, amount_); stakerWaitTime[msg.sender][delegator_] = block.timestamp + waitTime; require( IGovernanceToken(stakingToken).transferFrom( msg.sender, delegator_, amount_ ), "Transfer Failed" ); emit Staked(delegator_, msg.sender, amount_); } /** * @notice Removes amount_ from delegator_ * @param delegator_ contract address where to remove the stake from * @param amount_ uint to be removed from stake and undelegated * @dev Delegator must be valid and amount has to be greater than 0 * @dev amount_ must be <= that current user stake * @dev amount_ is transferred from the delegator contract to the staker * @dev updates rewards on call * @dev requires that at least waitTime has passed since delegation to unDelegate */ function withdraw(address delegator_, uint256 amount_) external nonReentrant { require(delegators[delegator_], "Not a valid delegator"); require(amount_ > 0, "Amount must be greater than 0"); require( block.timestamp >= stakerWaitTime[msg.sender][delegator_], "Need to wait the minimum staking period" ); updateReward(msg.sender); _totalSupply = _totalSupply - amount_; _balances[msg.sender] = _balances[msg.sender] - amount_; Delegator d = Delegator(delegator_); d.removeStake(msg.sender, amount_); emit Withdrawn(delegator_, msg.sender, amount_); } /** * @notice updates the min wait time between delegation and unDelegation * @param waitTime_ uint new wait time * @dev only the owner can call it */ function updateWaitTime(uint256 waitTime_) external onlyOwner { waitTime = waitTime_; emit WaitTimeUpdated(waitTime_); } /* ========== VIEWS ========== */ /** * @notice Returns the amount of reward tokens a user has earned. * @param account_ address */ function currentEarned(address account_) private view returns (uint256) { return (_balances[account_] * (rewardPerTokenStored - userRewardPerTokenPaid[account_])) / 1e18 + rewards[account_]; } /// @notice Returns the total amount of staked tokens. function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @notice Returns the amount of staked tokens from specific user * @param account_ address */ function balanceOf(address account_) external view returns (uint256) { return _balances[account_]; } /// @notice Returns reward rate for a duration function getRewardForDuration() external view returns (uint256) { return rewardRate * rewardsDuration; } /// @notice Returns the minimum between current block timestamp or the finish period of rewards. function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } /// @notice Returns the calculated reward per token deposited. function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * 1e18) / _totalSupply; } /** * @notice Returns the amount of reward tokens a user has earned. * @param account_ address */ function earned(address account_) public view returns (uint256) { return (_balances[account_] * (rewardPerToken() - userRewardPerTokenPaid[account_])) / 1e18 + rewards[account_]; } /** * @notice Returns the minimum between two variables * @param a_ uint * @param b_ uint */ function min(uint256 a_, uint256 b_) public pure returns (uint256) { return a_ < b_ ? a_ : b_; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IGovernanceToken { function delegate(address delegatee) external; function delegates(address delegator) external returns (address); function transfer(address dst, uint256 rawAmount) external returns (bool); function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool); function balanceOf(address src) external returns (uint256); function decimals() external returns (uint8); }
@notice returns the delegatee of this contract
function delegatee() external returns (address) { return IGovernanceToken(token).delegates(address(this)); }
945,236
[ 1, 6154, 326, 7152, 73, 434, 333, 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 ]
[ 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, 282, 445, 7152, 73, 1435, 3903, 1135, 261, 2867, 13, 288, 203, 1377, 327, 13102, 1643, 82, 1359, 1345, 12, 2316, 2934, 3771, 1332, 815, 12, 2867, 12, 2211, 10019, 203, 282, 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 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/controller/Reputation.sol /** * @title Reputation system * @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust . * A reputation is use to assign influence measure to a DAO'S peers. * Reputation is similar to regular tokens but with one crucial difference: It is non-transferable. * The Reputation contract maintain a map of address to reputation value. * It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address. */ contract Reputation is Ownable { using SafeMath for uint; mapping (address => uint256) public balances; uint256 public totalSupply; uint public decimals = 18; // Event indicating minting of reputation to an address. event Mint(address indexed _to, uint256 _amount); // Event indicating burning of reputation for an address. event Burn(address indexed _from, uint256 _amount); /** * @dev return the reputation amount of a given owner * @param _owner an address of the owner which we want to get his reputation */ function reputationOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Generates `_amount` of reputation that are assigned to `_to` * @param _to The address that will be assigned the new reputation * @param _amount The quantity of reputation to be generated * @return True if the reputation are generated correctly */ function mint(address _to, uint _amount) public onlyOwner returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); return true; } /** * @dev Burns `_amount` of reputation from `_from` * if _amount tokens to burn > balances[_from] the balance of _from will turn to zero. * @param _from The address that will lose the reputation * @param _amount The quantity of reputation to burn * @return True if the reputation are burned correctly */ function burn(address _from, uint _amount) public onlyOwner returns (bool) { uint amountMinted = _amount; if (balances[_from] < _amount) { amountMinted = balances[_from]; } totalSupply = totalSupply.sub(amountMinted); balances[_from] = balances[_from].sub(amountMinted); emit Burn(_from, amountMinted); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @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]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @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; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @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; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @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); } } // File: contracts/token/ERC827/ERC827.sol /** * @title ERC827 interface, an extension of ERC20 token standard * * @dev Interface of a ERC827 token, following the ERC20 standard with extra * methods to transfer value and data and execute calls in transfers and * approvals. */ contract ERC827 is ERC20 { function approveAndCall(address _spender,uint256 _value,bytes _data) public payable returns(bool); function transferAndCall(address _to,uint256 _value,bytes _data) public payable returns(bool); function transferFromAndCall(address _from,address _to,uint256 _value,bytes _data) public payable returns(bool); } // File: contracts/token/ERC827/ERC827Token.sol /* solium-disable security/no-low-level-calls */ pragma solidity ^0.4.24; /** * @title ERC827, an extension of ERC20 token standard * * @dev Implementation the ERC827, following the ERC20 standard with extra * methods to transfer value and data and execute calls in transfers and * approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** * @dev Addition to ERC20 token methods. It allows to * approve the transfer of value and execute a call with the sent data. * 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 that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_spender` address. * @return true if the call function was executed successfully */ function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * address and execute a call with the sent data on the same transaction * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * @return true if the call function was executed successfully */ function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * another and make a contract call on the same transaction * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * 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. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall( address _spender, uint _subtractedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } } // File: contracts/controller/DAOToken.sol /** * @title DAOToken, base on zeppelin contract. * @dev ERC20 compatible token. It is a mintable, destructible, burnable token. */ contract DAOToken is ERC827Token,MintableToken,BurnableToken { string public name; string public symbol; // solium-disable-next-line uppercase uint8 public constant decimals = 18; uint public cap; /** * @dev Constructor * @param _name - token name * @param _symbol - token symbol * @param _cap - token cap - 0 value means no cap */ constructor(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; } /** * @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) public onlyOwner canMint returns (bool) { if (cap > 0) require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/controller/Avatar.sol /** * @title An Avatar holds tokens, reputation and ether for a controller */ contract Avatar is Ownable { bytes32 public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GenericAction(address indexed _action, bytes32[] _params); event SendEther(uint _amountInWei, address indexed _to); event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint _value); event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint _value); event ExternalTokenIncreaseApproval(StandardToken indexed _externalToken, address _spender, uint _addedValue); event ExternalTokenDecreaseApproval(StandardToken indexed _externalToken, address _spender, uint _subtractedValue); event ReceiveEther(address indexed _sender, uint _value); /** * @dev the constructor takes organization name, native token and reputation system and creates an avatar for a controller */ constructor(bytes32 _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } /** * @dev enables an avatar to receive ethers */ function() public payable { emit ReceiveEther(msg.sender, msg.value); } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @return the return bytes of the called contract's function. */ function genericCall(address _contract,bytes _data) public onlyOwner { // solium-disable-next-line security/no-low-level-calls bool result = _contract.call(_data); // solium-disable-next-line security/no-inline-assembly assembly { // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // call returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev send ethers from the avatar's wallet * @param _amountInWei amount to send in Wei units * @param _to send the ethers to this address * @return bool which represents success */ function sendEther(uint _amountInWei, address _to) public onlyOwner returns(bool) { _to.transfer(_amountInWei); emit SendEther(_amountInWei, _to); return true; } /** * @dev external token transfer * @param _externalToken the token contract * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value) public onlyOwner returns(bool) { _externalToken.transfer(_to, _value); emit ExternalTokenTransfer(_externalToken, _to, _value); return true; } /** * @dev external token transfer from a specific account * @param _externalToken the token contract * @param _from the account to spend token from * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransferFrom( StandardToken _externalToken, address _from, address _to, uint _value ) public onlyOwner returns(bool) { _externalToken.transferFrom(_from, _to, _value); emit ExternalTokenTransferFrom(_externalToken, _from, _to, _value); return true; } /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue) public onlyOwner returns(bool) { _externalToken.increaseApproval(_spender, _addedValue); emit ExternalTokenIncreaseApproval(_externalToken, _spender, _addedValue); return true; } /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue ) public onlyOwner returns(bool) { _externalToken.decreaseApproval(_spender, _subtractedValue); emit ExternalTokenDecreaseApproval(_externalToken,_spender, _subtractedValue); return true; } } // File: contracts/globalConstraints/GlobalConstraintInterface.sol contract GlobalConstraintInterface { enum CallPhase { Pre, Post,PreAndPost } function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); /** * @dev when return if this globalConstraints is pre, post or both. * @return CallPhase enum indication Pre, Post or PreAndPost. */ function when() public returns(CallPhase); } // File: contracts/controller/ControllerInterface.sol /** * @title Controller contract * @dev A controller controls the organizations tokens ,reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ interface ControllerInterface { /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to,address _avatar) external returns(bool); /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from,address _avatar) external returns(bool); /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @param _avatar address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary,address _avatar) external returns(bool); /** * @dev register or update a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @param _avatar address * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar) external returns(bool); /** * @dev unregister a scheme * @param _avatar address * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme(address _scheme,address _avatar) external returns(bool); /** * @dev unregister the caller's scheme * @param _avatar address * @return bool which represents a success */ function unregisterSelf(address _avatar) external returns(bool); function isSchemeRegistered( address _scheme,address _avatar) external view returns(bool); function getSchemeParameters(address _scheme,address _avatar) external view returns(bytes32); function getGlobalConstraintParameters(address _globalConstraint,address _avatar) external view returns(bytes32); function getSchemePermissions(address _scheme,address _avatar) external view returns(bytes4); /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint globalConstraintsPre count. * @return uint globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external view returns(uint,uint); function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external view returns(bool); /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @param _avatar the avatar of the organization * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar) external returns(bool); /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @param _avatar the organization avatar. * @return bool which represents a success */ function removeGlobalConstraint (address _globalConstraint,address _avatar) external returns(bool); /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @param _avatar address * @return bool which represents a success */ function upgradeController(address _newController,address _avatar) external returns(bool); /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @return bytes32 - the return value of the called _contract's function. */ function genericCall(address _contract,bytes _data,address _avatar) external returns(bytes32); /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @param _avatar address * @return bool which represents a success */ function sendEther(uint _amountInWei, address _to,address _avatar) external returns(bool); /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar) external returns(bool); /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar) external returns(bool); /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @param _avatar address * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar) external returns(bool); /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @param _avatar address * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar) external returns(bool); /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external view returns(address); } // File: contracts/controller/Controller.sol /** * @title Controller contract * @dev A controller controls the organizations tokens,reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ contract Controller is ControllerInterface { struct Scheme { bytes32 paramsHash; // a hash "configuration" of the scheme bytes4 permissions; // A bitwise flags of permissions, // All 0: Not registered, // 1st bit: Flag if the scheme is registered, // 2nd bit: Scheme can register other schemes // 3rd bit: Scheme can add/remove global constraints // 4th bit: Scheme can upgrade the controller // 5th bit: Scheme can call genericCall on behalf of // the organization avatar } struct GlobalConstraint { address gcAddress; bytes32 params; } struct GlobalConstraintRegister { bool isRegistered; //is registered uint index; //index at globalConstraints } mapping(address=>Scheme) public schemes; Avatar public avatar; DAOToken public nativeToken; Reputation public nativeReputation; // newController will point to the new controller after the present controller is upgraded address public newController; // globalConstraintsPre that determine pre conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPre; // globalConstraintsPost that determine post conditions for all actions on the controller GlobalConstraint[] public globalConstraintsPost; // globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre; // globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost; event MintReputation (address indexed _sender, address indexed _to, uint256 _amount); event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount); event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount); event RegisterScheme (address indexed _sender, address indexed _scheme); event UnregisterScheme (address indexed _sender, address indexed _scheme); event GenericAction (address indexed _sender, bytes32[] _params); event SendEther (address indexed _sender, uint _amountInWei, address indexed _to); event ExternalTokenTransfer (address indexed _sender, address indexed _externalToken, address indexed _to, uint _value); event ExternalTokenTransferFrom (address indexed _sender, address indexed _externalToken, address _from, address _to, uint _value); event ExternalTokenIncreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value); event ExternalTokenDecreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value); event UpgradeController(address indexed _oldController,address _newController); event AddGlobalConstraint(address indexed _globalConstraint, bytes32 _params,GlobalConstraintInterface.CallPhase _when); event RemoveGlobalConstraint(address indexed _globalConstraint ,uint256 _index,bool _isPre); event GenericCall(address indexed _contract,bytes _data); constructor( Avatar _avatar) public { avatar = _avatar; nativeToken = avatar.nativeToken(); nativeReputation = avatar.nativeReputation(); schemes[msg.sender] = Scheme({paramsHash: bytes32(0),permissions: bytes4(0x1F)}); } // Do not allow mistaken calls: function() external { revert(); } // Modifiers: modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(1) == bytes4(1)); _; } modifier onlyRegisteringSchemes() { require(schemes[msg.sender].permissions&bytes4(2) == bytes4(2)); _; } modifier onlyGlobalConstraintsScheme() { require(schemes[msg.sender].permissions&bytes4(4) == bytes4(4)); _; } modifier onlyUpgradingScheme() { require(schemes[msg.sender].permissions&bytes4(8) == bytes4(8)); _; } modifier onlyGenericCallScheme() { require(schemes[msg.sender].permissions&bytes4(16) == bytes4(16)); _; } modifier onlySubjectToConstraint(bytes32 func) { uint idx; for (idx = 0;idx<globalConstraintsPre.length;idx++) { require((GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)).pre(msg.sender,globalConstraintsPre[idx].params,func)); } _; for (idx = 0;idx<globalConstraintsPost.length;idx++) { require((GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)).post(msg.sender,globalConstraintsPost[idx].params,func)); } } modifier isAvatarValid(address _avatar) { require(_avatar == address(avatar)); _; } /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintReputation") isAvatarValid(_avatar) returns(bool) { emit MintReputation(msg.sender, _to, _amount); return nativeReputation.mint(_to, _amount); } /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("burnReputation") isAvatarValid(_avatar) returns(bool) { emit BurnReputation(msg.sender, _from, _amount); return nativeReputation.burn(_from, _amount); } /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("mintTokens") isAvatarValid(_avatar) returns(bool) { emit MintTokens(msg.sender, _beneficiary, _amount); return nativeToken.mint(_beneficiary, _amount); } /** * @dev register a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("registerScheme") isAvatarValid(_avatar) returns(bool) { Scheme memory scheme = schemes[_scheme]; // Check scheme has at least the permissions it is changing, and at least the current permissions: // Implementation is a bit messy. One must recall logic-circuits ^^ // produces non-zero if sender does not have all of the perms that are changing between old and new require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0)); // produces non-zero if sender does not have all of the perms in the old scheme require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Add or change the scheme: schemes[_scheme].paramsHash = _paramsHash; schemes[_scheme].permissions = _permissions|bytes4(1); emit RegisterScheme(msg.sender, _scheme); return true; } /** * @dev unregister a scheme * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme( address _scheme,address _avatar) external onlyRegisteringSchemes onlySubjectToConstraint("unregisterScheme") isAvatarValid(_avatar) returns(bool) { //check if the scheme is registered if (schemes[_scheme].permissions&bytes4(1) == bytes4(0)) { return false; } // Check the unregistering scheme has enough permissions: require(bytes4(0x1F)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0)); // Unregister: emit UnregisterScheme(msg.sender, _scheme); delete schemes[_scheme]; return true; } /** * @dev unregister the caller's scheme * @return bool which represents a success */ function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) { if (_isSchemeRegistered(msg.sender,_avatar) == false) { return false; } delete schemes[msg.sender]; emit UnregisterScheme(msg.sender, msg.sender); return true; } function isSchemeRegistered(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bool) { return _isSchemeRegistered(_scheme,_avatar); } function getSchemeParameters(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes32) { return schemes[_scheme].paramsHash; } function getSchemePermissions(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes4) { return schemes[_scheme].permissions; } function getGlobalConstraintParameters(address _globalConstraint,address) external view returns(bytes32) { GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPre[register.index].params; } register = globalConstraintsRegisterPost[_globalConstraint]; if (register.isRegistered) { return globalConstraintsPost[register.index].params; } } /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint globalConstraintsPre count. * @return uint globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external isAvatarValid(_avatar) view returns(uint,uint) { return (globalConstraintsPre.length,globalConstraintsPost.length); } function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external isAvatarValid(_avatar) view returns(bool) { return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered); } /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) { globalConstraintsPre.push(GlobalConstraint(_globalConstraint,_params)); globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPre.length-1); }else { globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params; } } if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) { globalConstraintsPost.push(GlobalConstraint(_globalConstraint,_params)); globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPost.length-1); }else { globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params; } } emit AddGlobalConstraint(_globalConstraint, _params,when); return true; } /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @return bool which represents a success */ function removeGlobalConstraint (address _globalConstraint,address _avatar) external onlyGlobalConstraintsScheme isAvatarValid(_avatar) returns(bool) { GlobalConstraintRegister memory globalConstraintRegister; GlobalConstraint memory globalConstraint; GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when(); bool retVal = false; if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPre.length-1) { globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1]; globalConstraintsPre[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPre.length--; delete globalConstraintsRegisterPre[_globalConstraint]; retVal = true; } } if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) { globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint]; if (globalConstraintRegister.isRegistered) { if (globalConstraintRegister.index < globalConstraintsPost.length-1) { globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1]; globalConstraintsPost[globalConstraintRegister.index] = globalConstraint; globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index; } globalConstraintsPost.length--; delete globalConstraintsRegisterPost[_globalConstraint]; retVal = true; } } if (retVal) { emit RemoveGlobalConstraint(_globalConstraint,globalConstraintRegister.index,when == GlobalConstraintInterface.CallPhase.Pre); } return retVal; } /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @return bool which represents a success */ function upgradeController(address _newController,address _avatar) external onlyUpgradingScheme isAvatarValid(_avatar) returns(bool) { require(newController == address(0)); // so the upgrade could be done once for a contract. require(_newController != address(0)); newController = _newController; avatar.transferOwnership(_newController); require(avatar.owner()==_newController); if (nativeToken.owner() == address(this)) { nativeToken.transferOwnership(_newController); require(nativeToken.owner()==_newController); } if (nativeReputation.owner() == address(this)) { nativeReputation.transferOwnership(_newController); require(nativeReputation.owner()==_newController); } emit UpgradeController(this,newController); return true; } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @return bytes32 - the return value of the called _contract's function. */ function genericCall(address _contract,bytes _data,address _avatar) external onlyGenericCallScheme onlySubjectToConstraint("genericCall") isAvatarValid(_avatar) returns (bytes32) { emit GenericCall(_contract, _data); avatar.genericCall(_contract, _data); // solium-disable-next-line security/no-inline-assembly assembly { // Copy the returned data. returndatacopy(0, 0, returndatasize) return(0, returndatasize) } } /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @return bool which represents a success */ function sendEther(uint _amountInWei, address _to,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("sendEther") isAvatarValid(_avatar) returns(bool) { emit SendEther(msg.sender, _amountInWei, _to); return avatar.sendEther(_amountInWei, _to); } /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransfer") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenTransfer(msg.sender, _externalToken, _to, _value); return avatar.externalTokenTransfer(_externalToken, _to, _value); } /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @return bool which represents a success */ function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenTransferFrom") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenTransferFrom(msg.sender, _externalToken, _from, _to, _value); return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value); } /** * @dev increase approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _addedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenIncreaseApproval") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenIncreaseApproval(msg.sender,_externalToken,_spender,_addedValue); return avatar.externalTokenIncreaseApproval(_externalToken, _spender, _addedValue); } /** * @dev decrease approval for the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _subtractedValue the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar) external onlyRegisteredScheme onlySubjectToConstraint("externalTokenDecreaseApproval") isAvatarValid(_avatar) returns(bool) { emit ExternalTokenDecreaseApproval(msg.sender,_externalToken,_spender,_subtractedValue); return avatar.externalTokenDecreaseApproval(_externalToken, _spender, _subtractedValue); } /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) { return address(nativeReputation); } function _isSchemeRegistered(address _scheme,address _avatar) private isAvatarValid(_avatar) view returns(bool) { return (schemes[_scheme].permissions&bytes4(1) != bytes4(0)); } } // File: contracts/universalSchemes/ExecutableInterface.sol contract ExecutableInterface { function execute(bytes32 _proposalId, address _avatar, int _param) public returns(bool); } // File: contracts/VotingMachines/IntVoteInterface.sol interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;} modifier votable(bytes32 _proposalId) {revert(); _;} event NewProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _numOfChoices, address _proposer, bytes32 _paramsHash); event ExecuteProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _decision, uint _totalReputation); event VoteProposal(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter, uint _vote, uint _reputation); event CancelProposal(bytes32 indexed _proposalId, address indexed _avatar ); event CancelVoting(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter); /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _proposalParameters defines the parameters of the voting machine used for this proposal * @param _avatar an address to be sent as the payload to the _executable contract. * @param _executable This contract will be executed when vote is over. * @param _proposer address * @return proposal's id. */ function propose( uint _numOfChoices, bytes32 _proposalParameters, address _avatar, ExecutableInterface _executable, address _proposer ) external returns(bytes32); // Only owned proposals and only the owner: function cancelProposal(bytes32 _proposalId) external returns(bool); // Only owned proposals and only the owner: function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external returns(bool); function vote(bytes32 _proposalId, uint _vote) external returns(bool); function voteWithSpecifiedAmounts( bytes32 _proposalId, uint _vote, uint _rep, uint _token) external returns(bool); function cancelVote(bytes32 _proposalId) external; //@dev execute check if the proposal has been decided, and if so, execute the proposal //@param _proposalId the id of the proposal //@return bool true - the proposal has been executed // false - otherwise. function execute(bytes32 _proposalId) external returns(bool); function getNumberOfChoices(bytes32 _proposalId) external view returns(uint); function isVotable(bytes32 _proposalId) external view returns(bool); /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint); /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool); /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint min,uint max); } // File: contracts/universalSchemes/UniversalSchemeInterface.sol contract UniversalSchemeInterface { function updateParameters(bytes32 _hashedParameters) public; function getParametersFromController(Avatar _avatar) internal view returns(bytes32); } // File: contracts/universalSchemes/UniversalScheme.sol contract UniversalScheme is Ownable, UniversalSchemeInterface { bytes32 public hashedParameters; // For other parameters. function updateParameters( bytes32 _hashedParameters ) public onlyOwner { hashedParameters = _hashedParameters; } /** * @dev get the parameters for the current scheme from the controller */ function getParametersFromController(Avatar _avatar) internal view returns(bytes32) { return ControllerInterface(_avatar.owner()).getSchemeParameters(this,address(_avatar)); } } // File: contracts/libs/RealMath.sol /** * RealMath: fixed-point math library, based on fractional and integer parts. * Using int256 as real216x40, which isn't in Solidity yet. * 40 fractional bits gets us down to 1E-12 precision, while still letting us * go up to galaxy scale counting in meters. * Internally uses the wider int256 for some math. * * Note that for addition, subtraction, and mod (%), you should just use the * built-in Solidity operators. Functions for these operations are not provided. * * Note that the fancy functions like sqrt, atan2, etc. aren't as accurate as * they should be. They are (hopefully) Good Enough for doing orbital mechanics * on block timescales in a game context, but they may not be good enough for * other applications. */ library RealMath { /** * How many total bits are there? */ int256 constant REAL_BITS = 256; /** * How many fractional bits are there? */ int256 constant REAL_FBITS = 40; /** * How many integer bits are there? */ int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS; /** * What's the first non-fractional bit */ int256 constant REAL_ONE = int256(1) << REAL_FBITS; /** * What's the last fractional bit? */ int256 constant REAL_HALF = REAL_ONE >> 1; /** * What's two? Two is pretty useful. */ int256 constant REAL_TWO = REAL_ONE << 1; /** * And our logarithms are based on ln(2). */ int256 constant REAL_LN_TWO = 762123384786; /** * It is also useful to have Pi around. */ int256 constant REAL_PI = 3454217652358; /** * And half Pi, to save on divides. * TODO: That might not be how the compiler handles constants. */ int256 constant REAL_HALF_PI = 1727108826179; /** * And two pi, which happens to be odd in its most accurate representation. */ int256 constant REAL_TWO_PI = 6908435304715; /** * What's the sign bit? */ int256 constant SIGN_MASK = int256(1) << 255; /** * Convert an integer to a real. Preserves sign. */ function toReal(int216 ipart) internal pure returns (int256) { return int256(ipart) * REAL_ONE; } /** * Convert a real to an integer. Preserves sign. */ function fromReal(int256 realValue) internal pure returns (int216) { return int216(realValue / REAL_ONE); } /** * Round a real to the nearest integral real value. */ function round(int256 realValue) internal pure returns (int256) { // First, truncate. int216 ipart = fromReal(realValue); if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) { // High fractional bit is set. Round up. if (realValue < int256(0)) { // Rounding up for a negative number is rounding down. ipart -= 1; } else { ipart += 1; } } return toReal(ipart); } /** * Get the absolute value of a real. Just the same as abs on a normal int256. */ function abs(int256 realValue) internal pure returns (int256) { if (realValue > 0) { return realValue; } else { return -realValue; } } /** * Returns the fractional bits of a real. Ignores the sign of the real. */ function fractionalBits(int256 realValue) internal pure returns (uint40) { return uint40(abs(realValue) % REAL_ONE); } /** * Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5). */ function fpart(int256 realValue) internal pure returns (int256) { // This gets the fractional part but strips the sign return abs(realValue) % REAL_ONE; } /** * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5). */ function fpartSigned(int256 realValue) internal pure returns (int256) { // This gets the fractional part but strips the sign int256 fractional = fpart(realValue); if (realValue < 0) { // Add the negative sign back in. return -fractional; } else { return fractional; } } /** * Get the integer part of a fixed point value. */ function ipart(int256 realValue) internal pure returns (int256) { // Subtract out the fractional part to get the real part. return realValue - fpartSigned(realValue); } /** * Multiply one real by another. Truncates overflows. */ function mul(int256 realA, int256 realB) internal pure returns (int256) { // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return int256((int256(realA) * int256(realB)) >> REAL_FBITS); } /** * Divide one real by another real. Truncates overflows. */ function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) { // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return int256((int256(realNumerator) * REAL_ONE) / int256(realDenominator)); } /** * Create a real from a rational fraction. */ function fraction(int216 numerator, int216 denominator) internal pure returns (int256) { return div(toReal(numerator), toReal(denominator)); } // Now we have some fancy math things (like pow and trig stuff). This isn't // in the RealMath that was deployed with the original Macroverse // deployment, so it needs to be linked into your contract statically. /** * Raise a number to a positive integer power in O(log power) time. * See <https://stackoverflow.com/a/101613> */ function ipow(int256 realBase, int216 exponent) internal pure returns (int256) { if (exponent < 0) { // Negative powers are not allowed here. revert(); } int256 tempRealBase = realBase; int256 tempExponent = exponent; // Start with the 0th power int256 realResult = REAL_ONE; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = mul(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; // Do the squaring tempRealBase = mul(tempRealBase, tempRealBase); } // Return the final result. return realResult; } /** * Zero all but the highest set bit of a number. * See <https://stackoverflow.com/a/53184> */ function hibit(uint256 _val) internal pure returns (uint256) { // Set all the bits below the highest set bit uint256 val = _val; val |= (val >> 1); val |= (val >> 2); val |= (val >> 4); val |= (val >> 8); val |= (val >> 16); val |= (val >> 32); val |= (val >> 64); val |= (val >> 128); return val ^ (val >> 1); } /** * Given a number with one bit set, finds the index of that bit. */ function findbit(uint256 val) internal pure returns (uint8 index) { index = 0; // We and the value with alternating bit patters of various pitches to find it. if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) { // Picth 1 index |= 1; } if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) { // Pitch 2 index |= 2; } if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) { // Pitch 4 index |= 4; } if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) { // Pitch 8 index |= 8; } if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) { // Pitch 16 index |= 16; } if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) { // Pitch 32 index |= 32; } if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) { // Pitch 64 index |= 64; } if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) { // Pitch 128 index |= 128; } } /** * Shift realArg left or right until it is between 1 and 2. Return the * rescaled value, and the number of bits of right shift applied. Shift may be negative. * * Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2). * * Rejects 0 or negative arguments. */ function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) { if (realArg <= 0) { // Not in domain! revert(); } // Find the high bit int216 highBit = findbit(hibit(uint256(realArg))); // We'll shift so the high bit is the lowest non-fractional bit. shift = highBit - int216(REAL_FBITS); if (shift < 0) { // Shift left realScaled = realArg << -shift; } else if (shift >= 0) { // Shift right realScaled = realArg >> shift; } } /** * Calculate the natural log of a number. Rescales the input value and uses * the algorithm outlined at <https://math.stackexchange.com/a/977836> and * the ipow implementation. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function lnLimited(int256 realArg, int maxIterations) internal pure returns (int256) { if (realArg <= 0) { // Outside of acceptable domain revert(); } if (realArg == REAL_ONE) { // Handle this case specially because people will want exactly 0 and // not ~2^-39 ish. return 0; } // We know it's positive, so rescale it to be between [1 and 2) int256 realRescaled; int216 shift; (realRescaled, shift) = rescale(realArg); // Compute the argument to iterate on int256 realSeriesArg = div(realRescaled - REAL_ONE, realRescaled + REAL_ONE); // We will accumulate the result here int256 realSeriesResult = 0; for (int216 n = 0; n < maxIterations; n++) { // Compute term n of the series int256 realTerm = div(ipow(realSeriesArg, 2 * n + 1), toReal(2 * n + 1)); // And add it in realSeriesResult += realTerm; if (realTerm == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Double it to account for the factor of 2 outside the sum realSeriesResult = mul(realSeriesResult, REAL_TWO); // Now compute and return the overall result return mul(toReal(shift), REAL_LN_TWO) + realSeriesResult; } /** * Calculate a natural logarithm with a sensible maximum iteration count to * wait until convergence. Note that it is potentially possible to get an * un-converged value; lack of convergence does not throw. */ function ln(int256 realArg) internal pure returns (int256) { return lnLimited(realArg, 100); } /** * Calculate e^x. Uses the series given at * <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) { // We will accumulate the result here int256 realResult = 0; // We use this to save work computing terms int256 realTerm = REAL_ONE; for (int216 n = 0; n < maxIterations; n++) { // Add in the term realResult += realTerm; // Compute the next term realTerm = mul(realTerm, div(realArg, toReal(n + 1))); if (realTerm == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Return the result return realResult; } /** * Calculate e^x with a sensible maximum iteration count to wait until * convergence. Note that it is potentially possible to get an un-converged * value; lack of convergence does not throw. */ function exp(int256 realArg) internal pure returns (int256) { return expLimited(realArg, 100); } /** * Raise any number to any power, except for negative bases to fractional powers. */ function pow(int256 realBase, int256 realExponent) internal pure returns (int256) { if (realExponent == 0) { // Anything to the 0 is 1 return REAL_ONE; } if (realBase == 0) { if (realExponent < 0) { // Outside of domain! revert(); } // Otherwise it's 0 return 0; } if (fpart(realExponent) == 0) { // Anything (even a negative base) is super easy to do to an integer power. if (realExponent > 0) { // Positive integer power is easy return ipow(realBase, fromReal(realExponent)); } else { // Negative integer power is harder return div(REAL_ONE, ipow(realBase, fromReal(-realExponent))); } } if (realBase < 0) { // It's a negative base to a non-integer power. // In general pow(-x^y) is undefined, unless y is an int or some // weird rational-number-based relationship holds. revert(); } // If it's not a special case, actually do it. return exp(mul(realExponent, ln(realBase))); } /** * Compute the square root of a number. */ function sqrt(int256 realArg) internal pure returns (int256) { return pow(realArg, REAL_HALF); } /** * Compute the sin of a number to a certain number of Taylor series terms. */ function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) { // First bring the number into 0 to 2 pi // TODO: This will introduce an error for very large numbers, because the error in our Pi will compound. // But for actual reasonable angle values we should be fine. int256 realArg = _realArg; realArg = realArg % REAL_TWO_PI; int256 accumulator = REAL_ONE; // We sum from large to small iteration so that we can have higher powers in later terms for (int216 iteration = maxIterations - 1; iteration >= 0; iteration--) { accumulator = REAL_ONE - mul(div(mul(realArg, realArg), toReal((2 * iteration + 2) * (2 * iteration + 3))), accumulator); // We can't stop early; we need to make it to the first term. } return mul(realArg, accumulator); } /** * Calculate sin(x) with a sensible maximum iteration count to wait until * convergence. */ function sin(int256 realArg) internal pure returns (int256) { return sinLimited(realArg, 15); } /** * Calculate cos(x). */ function cos(int256 realArg) internal pure returns (int256) { return sin(realArg + REAL_HALF_PI); } /** * Calculate tan(x). May overflow for large results. May throw if tan(x) * would be infinite, or return an approximation, or overflow. */ function tan(int256 realArg) internal pure returns (int256) { return div(sin(realArg), cos(realArg)); } } // File: openzeppelin-solidity/contracts/ECRecovery.sol /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( "\x19Ethereum Signed Message:\n32", hash ); } } // File: contracts/libs/OrderStatisticTree.sol library OrderStatisticTree { struct Node { mapping (bool => uint) children; // a mapping of left(false) child and right(true) child nodes uint parent; // parent node bool side; // side of the node on the tree (left or right) uint height; //Height of this node uint count; //Number of tree nodes below this node (including this one) uint dupes; //Number of duplicates values for this node } struct Tree { // a mapping between node value(uint) to Node // the tree's root is always at node 0 ,which points to the "real" tree // as its right child.this is done to eliminate the need to update the tree // root in the case of rotation.(saving gas). mapping(uint => Node) nodes; } /** * @dev rank - find the rank of a value in the tree, * i.e. its index in the sorted list of elements of the tree * @param _tree the tree * @param _value the input value to find its rank. * @return smaller - the number of elements in the tree which their value is * less than the input value. */ function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) { if (_value != 0) { smaller = _tree.nodes[0].dupes; uint cur = _tree.nodes[0].children[true]; Node storage currentNode = _tree.nodes[cur]; while (true) { if (cur <= _value) { if (cur<_value) { smaller = smaller + 1+currentNode.dupes; } uint leftChild = currentNode.children[false]; if (leftChild!=0) { smaller = smaller + _tree.nodes[leftChild].count; } } if (cur == _value) { break; } cur = currentNode.children[cur<_value]; if (cur == 0) { break; } currentNode = _tree.nodes[cur]; } } } function count(Tree storage _tree) internal view returns (uint) { Node storage root = _tree.nodes[0]; Node memory child = _tree.nodes[root.children[true]]; return root.dupes+child.count; } function updateCount(Tree storage _tree,uint _value) private { Node storage n = _tree.nodes[_value]; n.count = 1+_tree.nodes[n.children[false]].count+_tree.nodes[n.children[true]].count+n.dupes; } function updateCounts(Tree storage _tree,uint _value) private { uint parent = _tree.nodes[_value].parent; while (parent!=0) { updateCount(_tree,parent); parent = _tree.nodes[parent].parent; } } function updateHeight(Tree storage _tree,uint _value) private { Node storage n = _tree.nodes[_value]; uint heightLeft = _tree.nodes[n.children[false]].height; uint heightRight = _tree.nodes[n.children[true]].height; if (heightLeft > heightRight) n.height = heightLeft+1; else n.height = heightRight+1; } function balanceFactor(Tree storage _tree,uint _value) private view returns (int bf) { Node storage n = _tree.nodes[_value]; return int(_tree.nodes[n.children[false]].height)-int(_tree.nodes[n.children[true]].height); } function rotate(Tree storage _tree,uint _value,bool dir) private { bool otherDir = !dir; Node storage n = _tree.nodes[_value]; bool side = n.side; uint parent = n.parent; uint valueNew = n.children[otherDir]; Node storage nNew = _tree.nodes[valueNew]; uint orphan = nNew.children[dir]; Node storage p = _tree.nodes[parent]; Node storage o = _tree.nodes[orphan]; p.children[side] = valueNew; nNew.side = side; nNew.parent = parent; nNew.children[dir] = _value; n.parent = valueNew; n.side = dir; n.children[otherDir] = orphan; o.parent = _value; o.side = otherDir; updateHeight(_tree,_value); updateHeight(_tree,valueNew); updateCount(_tree,_value); updateCount(_tree,valueNew); } function rebalanceInsert(Tree storage _tree,uint _nValue) private { updateHeight(_tree,_nValue); Node storage n = _tree.nodes[_nValue]; uint pValue = n.parent; if (pValue!=0) { int pBf = balanceFactor(_tree,pValue); bool side = n.side; int sign; if (side) sign = -1; else sign = 1; if (pBf == sign*2) { if (balanceFactor(_tree,_nValue) == (-1 * sign)) { rotate(_tree,_nValue,side); } rotate(_tree,pValue,!side); } else if (pBf != 0) { rebalanceInsert(_tree,pValue); } } } function rebalanceDelete(Tree storage _tree,uint _pValue,bool side) private { if (_pValue!=0) { updateHeight(_tree,_pValue); int pBf = balanceFactor(_tree,_pValue); int sign; if (side) sign = 1; else sign = -1; int bf = balanceFactor(_tree,_pValue); if (bf==(2*sign)) { Node storage p = _tree.nodes[_pValue]; uint sValue = p.children[!side]; int sBf = balanceFactor(_tree,sValue); if (sBf == (-1 * sign)) { rotate(_tree,sValue,!side); } rotate(_tree,_pValue,side); if (sBf!=0) { p = _tree.nodes[_pValue]; rebalanceDelete(_tree,p.parent,p.side); } } else if (pBf != sign) { p = _tree.nodes[_pValue]; rebalanceDelete(_tree,p.parent,p.side); } } } function fixParents(Tree storage _tree,uint parent,bool side) private { if (parent!=0) { updateCount(_tree,parent); updateCounts(_tree,parent); rebalanceDelete(_tree,parent,side); } } function insertHelper(Tree storage _tree,uint _pValue,bool _side,uint _value) private { Node storage root = _tree.nodes[_pValue]; uint cValue = root.children[_side]; if (cValue==0) { root.children[_side] = _value; Node storage child = _tree.nodes[_value]; child.parent = _pValue; child.side = _side; child.height = 1; child.count = 1; updateCounts(_tree,_value); rebalanceInsert(_tree,_value); } else if (cValue==_value) { _tree.nodes[cValue].dupes++; updateCount(_tree,_value); updateCounts(_tree,_value); } else { insertHelper(_tree,cValue,(_value >= cValue),_value); } } function insert(Tree storage _tree,uint _value) internal { if (_value==0) { _tree.nodes[_value].dupes++; } else { insertHelper(_tree,0,true,_value); } } function rightmostLeaf(Tree storage _tree,uint _value) private view returns (uint leaf) { uint child = _tree.nodes[_value].children[true]; if (child!=0) { return rightmostLeaf(_tree,child); } else { return _value; } } function zeroOut(Tree storage _tree,uint _value) private { Node storage n = _tree.nodes[_value]; n.parent = 0; n.side = false; n.children[false] = 0; n.children[true] = 0; n.count = 0; n.height = 0; n.dupes = 0; } function removeBranch(Tree storage _tree,uint _value,uint _left) private { uint ipn = rightmostLeaf(_tree,_left); Node storage i = _tree.nodes[ipn]; uint dupes = i.dupes; removeHelper(_tree,ipn); Node storage n = _tree.nodes[_value]; uint parent = n.parent; Node storage p = _tree.nodes[parent]; uint height = n.height; bool side = n.side; uint ncount = n.count; uint right = n.children[true]; uint left = n.children[false]; p.children[side] = ipn; i.parent = parent; i.side = side; i.count = ncount+dupes-n.dupes; i.height = height; i.dupes = dupes; if (left!=0) { i.children[false] = left; _tree.nodes[left].parent = ipn; } if (right!=0) { i.children[true] = right; _tree.nodes[right].parent = ipn; } zeroOut(_tree,_value); updateCounts(_tree,ipn); } function removeHelper(Tree storage _tree,uint _value) private { Node storage n = _tree.nodes[_value]; uint parent = n.parent; bool side = n.side; Node storage p = _tree.nodes[parent]; uint left = n.children[false]; uint right = n.children[true]; if ((left == 0) && (right == 0)) { p.children[side] = 0; zeroOut(_tree,_value); fixParents(_tree,parent,side); } else if ((left != 0) && (right != 0)) { removeBranch(_tree,_value,left); } else { uint child = left+right; Node storage c = _tree.nodes[child]; p.children[side] = child; c.parent = parent; c.side = side; zeroOut(_tree,_value); fixParents(_tree,parent,side); } } function remove(Tree storage _tree,uint _value) internal { Node storage n = _tree.nodes[_value]; if (_value==0) { if (n.dupes==0) { return; } } else { if (n.count==0) { return; } } if (n.dupes>0) { n.dupes--; if (_value!=0) { n.count--; } fixParents(_tree,n.parent,n.side); } else { removeHelper(_tree,_value); } } } // File: contracts/VotingMachines/GenesisProtocol.sol /** * @title GenesisProtocol implementation -an organization's voting machine scheme. */ contract GenesisProtocol is IntVoteInterface,UniversalScheme { using SafeMath for uint; using RealMath for int216; using RealMath for int256; using ECRecovery for bytes32; using OrderStatisticTree for OrderStatisticTree.Tree; enum ProposalState { None ,Closed, Executed, PreBoosted,Boosted,QuietEndingPeriod } enum ExecutionState { None, PreBoostedTimeOut, PreBoostedBarCrossed, BoostedTimeOut,BoostedBarCrossed } //Organization's parameters struct Parameters { uint preBoostedVoteRequiredPercentage; // the absolute vote percentages bar. uint preBoostedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint boostedVotePeriodLimit; //the time limit for a proposal to be in an relative voting mode. uint thresholdConstA;//constant A for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B)) uint thresholdConstB;//constant B for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B)) uint minimumStakingFee; //minimum staking fee allowed. uint quietEndingPeriod; //quite ending period uint proposingRepRewardConstA;//constant A for calculate proposer reward. proposerReward =(A*(RTotal) +B*(R+ - R-))/1000 uint proposingRepRewardConstB;//constant B for calculate proposing reward.proposerReward =(A*(RTotal) +B*(R+ - R-))/1000 uint stakerFeeRatioForVoters; // The “ratio of stake” to be paid to voters. // All stakers pay a portion of their stake to all voters, stakerFeeRatioForVoters * (s+ + s-). //All voters (pre and during boosting period) divide this portion in proportion to their reputation. uint votersReputationLossRatio;//Unsuccessful pre booster voters lose votersReputationLossRatio% of their reputation. uint votersGainRepRatioFromLostRep; //the percentages of the lost reputation which is divided by the successful pre boosted voters, //in proportion to their reputation. //The rest (100-votersGainRepRatioFromLostRep)% of lost reputation is divided between the successful wagers, //in proportion to their stake. uint daoBountyConst;//The DAO adds up a bounty for successful staker. //The bounty formula is: s * daoBountyConst, where s+ is the wager staked for the proposal, //and daoBountyConst is a constant factor that is configurable and changeable by the DAO given. // daoBountyConst should be greater than stakerFeeRatioForVoters and less than 2 * stakerFeeRatioForVoters. uint daoBountyLimit;//The daoBounty cannot be greater than daoBountyLimit. } struct Voter { uint vote; // YES(1) ,NO(2) uint reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint vote; // YES(1) ,NO(2) uint amount; // amount of staker's stake uint amountForBounty; // amount of staker's stake which will be use for bounty calculation } struct Proposal { address avatar; // the organization's avatar the proposal is target to. uint numOfChoices; ExecutableInterface executable; // will be executed if the proposal will pass uint votersStakes; uint submittedTime; uint boostedPhaseTime; //the time the proposal shift to relative mode. ProposalState state; uint winningVote; //the winning vote. address proposer; uint currentBoostedVotePeriodLimit; bytes32 paramsHash; uint daoBountyRemain; uint[2] totalStakes;// totalStakes[0] - (amount staked minus fee) - Total number of tokens staked which can be redeemable by stakers. // totalStakes[1] - (amount staked) - Total number of redeemable tokens. // vote reputation mapping(uint => uint ) votes; // vote reputation mapping(uint => uint ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint => uint ) stakes; // address staker mapping(address => Staker ) stakers; } event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState); event Stake(bytes32 indexed _proposalId, address indexed _avatar, address indexed _staker,uint _vote,uint _amount); event Redeem(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount); event RedeemDaoBounty(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount); event RedeemReputation(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount); mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes=>bool) stakeSignatures; //stake signatures uint constant public NUM_OF_CHOICES = 2; uint constant public NO = 2; uint constant public YES = 1; uint public proposalsCnt; // Total number of proposals mapping(address=>uint) orgBoostedProposalsCnt; StandardToken public stakingToken; mapping(address=>OrderStatisticTree.Tree) proposalsExpiredTimes; //proposals expired times /** * @dev Constructor */ constructor(StandardToken _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Check that the proposal is votable (open and not executed yet) */ modifier votable(bytes32 _proposalId) { require(_isVotable(_proposalId)); _; } /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _avatar an address to be sent as the payload to the _executable contract. * @param _executable This contract will be executed when vote is over. * @param _proposer address * @return proposal's id. */ function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer) external returns(bytes32) { // Check valid params and number of choices: require(_numOfChoices == NUM_OF_CHOICES); require(ExecutableInterface(_executable) != address(0)); //Check parameters existence. bytes32 paramsHash = getParametersFromController(Avatar(_avatar)); require(parameters[paramsHash].preBoostedVoteRequiredPercentage > 0); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt++; // Open proposal: Proposal memory proposal; proposal.numOfChoices = _numOfChoices; proposal.avatar = _avatar; proposal.executable = _executable; proposal.state = ProposalState.PreBoosted; // solium-disable-next-line security/no-block-members proposal.submittedTime = now; proposal.currentBoostedVotePeriodLimit = parameters[paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = NO; proposal.paramsHash = paramsHash; proposals[proposalId] = proposal; emit NewProposal(proposalId, _avatar, _numOfChoices, _proposer, paramsHash); return proposalId; } /** * @dev Cancel a proposal, only the owner can call this function and only if allowOwner flag is true. */ function cancelProposal(bytes32 ) external returns(bool) { //This is not allowed. return false; } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @return bool true - the proposal has been executed * false - otherwise. */ function stake(bytes32 _proposalId, uint _vote, uint _amount) external returns(bool) { return _stake(_proposalId,_vote,_amount,msg.sender); } // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce")); // web3.eth.sign prefix string public constant ETH_SIGN_PREFIX= "\x19Ethereum Signed Message:\n32"; /** * @dev stakeWithSignature function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @param _nonce nonce value ,it is part of the signature to ensure that a signature can be received only once. * @param _signatureType signature type 1 - for web3.eth.sign 2 - for eth_signTypedData according to EIP #712. * @param _signature - signed data by the staker * @return bool true - the proposal has been executed * false - otherwise. */ function stakeWithSignature( bytes32 _proposalId, uint _vote, uint _amount, uint _nonce, uint _signatureType, bytes _signature ) external returns(bool) { require(stakeSignatures[_signature] == false); // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce))) ); } else { delegationDigest = keccak256( abi.encodePacked( ETH_SIGN_PREFIX, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce))) ); } address staker = delegationDigest.recover(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker!=address(0)); stakeSignatures[_signature] = true; return _stake(_proposalId,_vote,_amount,staker); } /** * @dev voting function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @return bool true - the proposal has been executed * false - otherwise. */ function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool) { return internalVote(_proposalId, msg.sender, _vote, 0); } /** * @dev voting function with owner functionality (can vote on behalf of someone else) * @return bool true - the proposal has been executed * false - otherwise. */ function ownerVote(bytes32 , uint , address ) external returns(bool) { //This is not allowed. return false; } function voteWithSpecifiedAmounts(bytes32 _proposalId,uint _vote,uint _rep,uint) external votable(_proposalId) returns(bool) { return internalVote(_proposalId,msg.sender,_vote,_rep); } /** * @dev Cancel the vote of the msg.sender. * cancel vote is not allow in genesisProtocol so this function doing nothing. * This function is here in order to comply to the IntVoteInterface . */ function cancelVote(bytes32 _proposalId) external votable(_proposalId) { //this is not allowed return; } /** * @dev getNumberOfChoices returns the number of choices possible in this proposal * @param _proposalId the ID of the proposals * @return uint that contains number of choices */ function getNumberOfChoices(bytes32 _proposalId) external view returns(uint) { return proposals[_proposalId].numOfChoices; } /** * @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal * @param _proposalId the ID of the proposal * @param _voter the address of the voter * @return uint vote - the voters vote * uint reputation - amount of reputation committed by _voter to _proposalId */ function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) { return proposals[_proposalId].votes[_choice]; } /** * @dev isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function isVotable(bytes32 _proposalId) external view returns(bool) { return _isVotable(_proposalId); } /** * @dev proposalStatus return the total votes and stakes for a given proposal * @param _proposalId the ID of the proposal * @return uint preBoostedVotes YES * @return uint preBoostedVotes NO * @return uint stakersStakes * @return uint totalRedeemableStakes * @return uint total stakes YES * @return uint total stakes NO */ function proposalStatus(bytes32 _proposalId) external view returns(uint, uint, uint ,uint, uint ,uint) { return ( proposals[_proposalId].preBoostedVotes[YES], proposals[_proposalId].preBoostedVotes[NO], proposals[_proposalId].totalStakes[0], proposals[_proposalId].totalStakes[1], proposals[_proposalId].stakes[YES], proposals[_proposalId].stakes[NO] ); } /** * @dev proposalAvatar return the avatar for a given proposal * @param _proposalId the ID of the proposal * @return uint total reputation supply */ function proposalAvatar(bytes32 _proposalId) external view returns(address) { return (proposals[_proposalId].avatar); } /** * @dev scoreThresholdParams return the score threshold params for a given * organization. * @param _avatar the organization's avatar * @return uint thresholdConstA * @return uint thresholdConstB */ function scoreThresholdParams(address _avatar) external view returns(uint,uint) { bytes32 paramsHash = getParametersFromController(Avatar(_avatar)); Parameters memory params = parameters[paramsHash]; return (params.thresholdConstA,params.thresholdConstB); } /** * @dev getStaker return the vote and stake amount for a given proposal and staker * @param _proposalId the ID of the proposal * @param _staker staker address * @return uint vote * @return uint amount */ function getStaker(bytes32 _proposalId,address _staker) external view returns(uint,uint) { return (proposals[_proposalId].stakers[_staker].vote,proposals[_proposalId].stakers[_staker].amount); } /** * @dev state return the state for a given proposal * @param _proposalId the ID of the proposal * @return ProposalState proposal state */ function state(bytes32 _proposalId) external view returns(ProposalState) { return proposals[_proposalId].state; } /** * @dev winningVote return the winningVote for a given proposal * @param _proposalId the ID of the proposal * @return uint winningVote */ function winningVote(bytes32 _proposalId) external view returns(uint) { return proposals[_proposalId].winningVote; } /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool) { return false; } /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint min,uint max) { return (NUM_OF_CHOICES,NUM_OF_CHOICES); } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) { return _execute(_proposalId); } /** * @dev redeem a reward for a successful stake, vote or proposing. * The function use a beneficiary address as a parameter (and not msg.sender) to enable * users to redeem on behalf of someone else. * @param _proposalId the ID of the proposal * @param _beneficiary - the beneficiary address * @return rewards - * rewards[0] - stakerTokenAmount * rewards[1] - stakerReputationAmount * rewards[2] - voterTokenAmount * rewards[3] - voterReputationAmount * rewards[4] - proposerReputationAmount * @return reputation - redeem reputation */ function redeem(bytes32 _proposalId,address _beneficiary) public returns (uint[5] rewards) { Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed),"wrong proposal state"); Parameters memory params = parameters[proposal.paramsHash]; uint amount; uint reputation; uint lostReputation; if (proposal.winningVote == YES) { lostReputation = proposal.preBoostedVotes[NO]; } else { lostReputation = proposal.preBoostedVotes[YES]; } lostReputation = (lostReputation * params.votersReputationLossRatio)/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; if ((staker.amount>0) && (staker.vote == proposal.winningVote)) { uint totalWinningStakes = proposal.stakes[proposal.winningVote]; if (totalWinningStakes != 0) { rewards[0] = (staker.amount * proposal.totalStakes[0]) / totalWinningStakes; } if (proposal.state != ProposalState.Closed) { rewards[1] = (staker.amount * ( lostReputation - ((lostReputation * params.votersGainRepRatioFromLostRep)/100)))/proposal.stakes[proposal.winningVote]; } staker.amount = 0; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0 ) && (voter.preBoosted)) { uint preBoostedVotes = proposal.preBoostedVotes[YES] + proposal.preBoostedVotes[NO]; if (preBoostedVotes>0) { rewards[2] = ((proposal.votersStakes * voter.reputation) / preBoostedVotes); } if (proposal.state == ProposalState.Closed) { //give back reputation for the voter rewards[3] = ((voter.reputation * params.votersReputationLossRatio)/100); } else if (proposal.winningVote == voter.vote ) { rewards[3] = (((voter.reputation * params.votersReputationLossRatio)/100) + (((voter.reputation * lostReputation * params.votersGainRepRatioFromLostRep)/100)/preBoostedVotes)); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) { rewards[4] = (params.proposingRepRewardConstA.mul(proposal.votes[YES]+proposal.votes[NO]) + params.proposingRepRewardConstB.mul(proposal.votes[YES]-proposal.votes[NO]))/1000; proposal.proposer = 0; } amount = rewards[0] + rewards[2]; reputation = rewards[1] + rewards[3] + rewards[4]; if (amount != 0) { proposal.totalStakes[1] = proposal.totalStakes[1].sub(amount); require(stakingToken.transfer(_beneficiary, amount)); emit Redeem(_proposalId,proposal.avatar,_beneficiary,amount); } if (reputation != 0 ) { ControllerInterface(Avatar(proposal.avatar).owner()).mintReputation(reputation,_beneficiary,proposal.avatar); emit RedeemReputation(_proposalId,proposal.avatar,_beneficiary,reputation); } } /** * @dev redeemDaoBounty a reward for a successful stake, vote or proposing. * The function use a beneficiary address as a parameter (and not msg.sender) to enable * users to redeem on behalf of someone else. * @param _proposalId the ID of the proposal * @param _beneficiary - the beneficiary address * @return redeemedAmount - redeem token amount * @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the avatar ) */ function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed)); uint totalWinningStakes = proposal.stakes[proposal.winningVote]; if ( // solium-disable-next-line operator-whitespace (proposal.stakers[_beneficiary].amountForBounty>0)&& (proposal.stakers[_beneficiary].vote == proposal.winningVote)&& (proposal.winningVote == YES)&& (totalWinningStakes != 0)) { //as staker Parameters memory params = parameters[proposal.paramsHash]; uint beneficiaryLimit = (proposal.stakers[_beneficiary].amountForBounty.mul(params.daoBountyLimit)) / totalWinningStakes; potentialAmount = (params.daoBountyConst.mul(proposal.stakers[_beneficiary].amountForBounty))/100; if (potentialAmount > beneficiaryLimit) { potentialAmount = beneficiaryLimit; } } if ((potentialAmount != 0)&&(stakingToken.balanceOf(proposal.avatar) >= potentialAmount)) { proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount); require(ControllerInterface(Avatar(proposal.avatar).owner()).externalTokenTransfer(stakingToken,_beneficiary,potentialAmount,proposal.avatar)); proposal.stakers[_beneficiary].amountForBounty = 0; redeemedAmount = potentialAmount; emit RedeemDaoBounty(_proposalId,proposal.avatar,_beneficiary,redeemedAmount); } } /** * @dev shouldBoost check if a proposal should be shifted to boosted phase. * @param _proposalId the ID of the proposal * @return bool true or false. */ function shouldBoost(bytes32 _proposalId) public view returns(bool) { Proposal memory proposal = proposals[_proposalId]; return (_score(_proposalId) >= threshold(proposal.paramsHash,proposal.avatar)); } /** * @dev score return the proposal score * @param _proposalId the ID of the proposal * @return uint proposal score. */ function score(bytes32 _proposalId) public view returns(int) { return _score(_proposalId); } /** * @dev getBoostedProposalsCount return the number of boosted proposal for an organization * @param _avatar the organization avatar * @return uint number of boosted proposals */ function getBoostedProposalsCount(address _avatar) public view returns(uint) { uint expiredProposals; if (proposalsExpiredTimes[_avatar].count() != 0) { // solium-disable-next-line security/no-block-members expiredProposals = proposalsExpiredTimes[_avatar].rank(now); } return orgBoostedProposalsCnt[_avatar].sub(expiredProposals); } /** * @dev threshold return the organization's score threshold which required by * a proposal to shift to boosted state. * This threshold is dynamically set and it depend on the number of boosted proposal. * @param _avatar the organization avatar * @param _paramsHash the organization parameters hash * @return int organization's score threshold. */ function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) { uint boostedProposals = getBoostedProposalsCount(_avatar); int216 e = 2; Parameters memory params = parameters[_paramsHash]; require(params.thresholdConstB > 0,"should be a valid parameter hash"); int256 power = int216(boostedProposals).toReal().div(int216(params.thresholdConstB).toReal()); if (power.fromReal() > 100 ) { power = int216(100).toReal(); } int256 res = int216(params.thresholdConstA).toReal().mul(e.toReal().pow(power)); return res.fromReal(); } /** * @dev hash the parameters, save them if necessary, and return the hash value * @param _params a parameters array * _params[0] - _preBoostedVoteRequiredPercentage, * _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode. * _params[2] -_boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode. * _params[3] -_thresholdConstA * _params[4] -_thresholdConstB * _params[5] -_minimumStakingFee * _params[6] -_quietEndingPeriod * _params[7] -_proposingRepRewardConstA * _params[8] -_proposingRepRewardConstB * _params[9] -_stakerFeeRatioForVoters * _params[10] -_votersReputationLossRatio * _params[11] -_votersGainRepRatioFromLostRep * _params[12] - _daoBountyConst * _params[13] - _daoBountyLimit */ function setParameters( uint[14] _params //use array here due to stack too deep issue. ) public returns(bytes32) { require(_params[0] <= 100 && _params[0] > 0,"0 < preBoostedVoteRequiredPercentage <= 100"); require(_params[4] > 0 && _params[4] <= 100000000,"0 < thresholdConstB < 100000000 "); require(_params[3] <= 100000000 ether,"thresholdConstA <= 100000000 wei"); require(_params[9] <= 100,"stakerFeeRatioForVoters <= 100"); require(_params[10] <= 100,"votersReputationLossRatio <= 100"); require(_params[11] <= 100,"votersGainRepRatioFromLostRep <= 100"); require(_params[2] >= _params[6],"boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[7] <= 100000000,"proposingRepRewardConstA <= 100000000"); require(_params[8] <= 100000000,"proposingRepRewardConstB <= 100000000"); require(_params[12] <= (2 * _params[9]),"daoBountyConst <= 2 * stakerFeeRatioForVoters"); require(_params[12] >= _params[9],"daoBountyConst >= stakerFeeRatioForVoters"); bytes32 paramsHash = getParametersHash(_params); parameters[paramsHash] = Parameters({ preBoostedVoteRequiredPercentage: _params[0], preBoostedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], thresholdConstA:_params[3], thresholdConstB:_params[4], minimumStakingFee: _params[5], quietEndingPeriod: _params[6], proposingRepRewardConstA: _params[7], proposingRepRewardConstB:_params[8], stakerFeeRatioForVoters:_params[9], votersReputationLossRatio:_params[10], votersGainRepRatioFromLostRep:_params[11], daoBountyConst:_params[12], daoBountyLimit:_params[13] }); return paramsHash; } /** * @dev hashParameters returns a hash of the given parameters */ function getParametersHash( uint[14] _params) //use array here due to stack too deep issue. public pure returns(bytes32) { return keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10], _params[11], _params[12], _params[13])); } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint totalReputation = Avatar(proposal.avatar).nativeReputation().totalSupply(); uint executionBar = totalReputation * params.preBoostedVoteRequiredPercentage/100; ExecutionState executionState = ExecutionState.None; if (proposal.state == ProposalState.PreBoosted) { // solium-disable-next-line security/no-block-members if ((now - proposal.submittedTime) >= params.preBoostedVotePeriodLimit) { proposal.state = ProposalState.Closed; proposal.winningVote = NO; executionState = ExecutionState.PreBoostedTimeOut; } else if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. proposal.state = ProposalState.Executed; executionState = ExecutionState.PreBoostedBarCrossed; } else if ( shouldBoost(_proposalId)) { //change proposal mode to boosted mode. proposal.state = ProposalState.Boosted; // solium-disable-next-line security/no-block-members proposal.boostedPhaseTime = now; proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); orgBoostedProposalsCnt[proposal.avatar]++; } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solium-disable-next-line security/no-block-members if ((now - proposal.boostedPhaseTime) >= proposal.currentBoostedVotePeriodLimit) { proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1); proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } else if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1); proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedBarCrossed; } } if (executionState != ExecutionState.None) { if (proposal.winningVote == YES) { uint daoBountyRemain = (params.daoBountyConst.mul(proposal.stakes[proposal.winningVote]))/100; if (daoBountyRemain > params.daoBountyLimit) { daoBountyRemain = params.daoBountyLimit; } proposal.daoBountyRemain = daoBountyRemain; } emit ExecuteProposal(_proposalId, proposal.avatar, proposal.winningVote, totalReputation); emit GPExecuteProposal(_proposalId, executionState); (tmpProposal.executable).execute(_proposalId, tmpProposal.avatar, int(proposal.winningVote)); } return (executionState != ExecutionState.None); } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @param _staker the staker address * @return bool true - the proposal has been executed * false - otherwise. */ function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) { // 0 is not a valid vote. require(_vote <= NUM_OF_CHOICES && _vote > 0); require(_amount > 0); if (_execute(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if (proposal.state != ProposalState.PreBoosted) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint amount = _amount; Parameters memory params = parameters[proposal.paramsHash]; require(amount >= params.minimumStakingFee); require(stakingToken.transferFrom(_staker, address(this), amount)); proposal.totalStakes[1] = proposal.totalStakes[1].add(amount); //update totalRedeemableStakes staker.amount += amount; staker.amountForBounty = staker.amount; staker.vote = _vote; proposal.votersStakes += (params.stakerFeeRatioForVoters * amount)/100; proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]); amount = amount - ((params.stakerFeeRatioForVoters*amount)/100); proposal.totalStakes[0] = amount.add(proposal.totalStakes[0]); // Event: emit Stake(_proposalId, proposal.avatar, _staker, _vote, _amount); // execute the proposal if this vote was decisive: return _execute(_proposalId); } /** * @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead * @param _proposalId id of the proposal * @param _voter used in case the vote is cast for someone else * @param _vote a value between 0 to and the proposal's number of choices. * @param _rep how many reputation the voter would like to stake for this vote. * if _rep==0 so the voter full reputation will be use. * @return true in case of proposal execution otherwise false * throws if proposal is not open or if it has been executed * NB: executes the proposal if a decision has been reached */ function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) internal returns(bool) { // 0 is not a valid vote. require(_vote <= NUM_OF_CHOICES && _vote > 0,"0 < _vote <= 2"); if (_execute(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint reputation = Avatar(proposal.avatar).nativeReputation().reputationOf(_voter); require(reputation >= _rep); uint rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.add(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[NO] == proposal.votes[proposal.winningVote]) && proposal.winningVote == YES)) { // solium-disable-next-line security/no-block-members uint _now = now; if ((proposal.state == ProposalState.QuietEndingPeriod) || ((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) { //quietEndingPeriod proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } proposal.boostedPhaseTime = _now; proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:(proposal.state == ProposalState.PreBoosted) }); if (proposal.state == ProposalState.PreBoosted) { proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]); uint reputationDeposit = (params.votersReputationLossRatio * rep)/100; ControllerInterface(Avatar(proposal.avatar).owner()).burnReputation(reputationDeposit,_voter,proposal.avatar); } // Event: emit VoteProposal(_proposalId, proposal.avatar, _voter, _vote, rep); // execute the proposal if this vote was decisive: return _execute(_proposalId); } /** * @dev _score return the proposal score * For dual choice proposal S = (S+) - (S-) * @param _proposalId the ID of the proposal * @return int proposal score. */ function _score(bytes32 _proposalId) private view returns(int) { Proposal storage proposal = proposals[_proposalId]; return int(proposal.stakes[YES]) - int(proposal.stakes[NO]); } /** * @dev _isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function _isVotable(bytes32 _proposalId) private view returns(bool) { ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)||(pState == ProposalState.Boosted)||(pState == ProposalState.QuietEndingPeriod)); } }
* @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead @param _proposalId id of the proposal @param _voter used in case the vote is cast for someone else @param _vote a value between 0 to and the proposal's number of choices. @param _rep how many reputation the voter would like to stake for this vote. if _rep==0 so the voter full reputation will be use. @return true in case of proposal execution otherwise false throws if proposal is not open or if it has been executed NB: executes the proposal if a decision has been reached/ 0 is not a valid vote. If this voter has already voted, return false. solium-disable-next-line security/no-block-membersquietEndingPeriod
function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) internal returns(bool) { require(_vote <= NUM_OF_CHOICES && _vote > 0,"0 < _vote <= 2"); if (_execute(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; require(reputation >= _rep); uint rep = _rep; if (rep == 0) { rep = reputation; } if (proposal.voters[_voter].reputation != 0) { return false; } ((proposal.votes[NO] == proposal.votes[proposal.winningVote]) && proposal.winningVote == YES)) { uint _now = now; if ((proposal.state == ProposalState.QuietEndingPeriod) || ((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) { proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } proposal.boostedPhaseTime = _now; proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit); } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:(proposal.state == ProposalState.PreBoosted) }); if (proposal.state == ProposalState.PreBoosted) { proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]); uint reputationDeposit = (params.votersReputationLossRatio * rep)/100; ControllerInterface(Avatar(proposal.avatar).owner()).burnReputation(reputationDeposit,_voter,proposal.avatar); } }
1,299,333
[ 1, 19338, 364, 279, 14708, 16, 309, 326, 331, 20005, 1818, 331, 16474, 16, 3755, 326, 1142, 12501, 471, 444, 279, 394, 1245, 3560, 225, 389, 685, 8016, 548, 612, 434, 326, 14708, 225, 389, 90, 20005, 1399, 316, 648, 326, 12501, 353, 4812, 364, 18626, 469, 225, 389, 25911, 279, 460, 3086, 374, 358, 471, 326, 14708, 1807, 1300, 434, 7246, 18, 225, 389, 14462, 3661, 4906, 283, 458, 367, 326, 331, 20005, 4102, 3007, 358, 384, 911, 364, 333, 12501, 18, 540, 309, 225, 389, 14462, 631, 20, 1427, 326, 331, 20005, 1983, 283, 458, 367, 903, 506, 999, 18, 327, 638, 316, 648, 434, 14708, 4588, 3541, 629, 1216, 309, 14708, 353, 486, 1696, 578, 309, 518, 711, 2118, 7120, 20096, 30, 11997, 326, 14708, 309, 279, 14604, 711, 2118, 8675, 19, 374, 353, 486, 279, 923, 12501, 18, 971, 333, 331, 20005, 711, 1818, 331, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 2713, 19338, 12, 3890, 1578, 389, 685, 8016, 548, 16, 1758, 389, 90, 20005, 16, 2254, 389, 25911, 16, 2254, 389, 14462, 13, 2713, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 24899, 25911, 1648, 9443, 67, 3932, 67, 22213, 11774, 55, 597, 389, 25911, 405, 374, 10837, 20, 411, 389, 25911, 1648, 576, 8863, 203, 3639, 309, 261, 67, 8837, 24899, 685, 8016, 548, 3719, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 7012, 3778, 859, 273, 1472, 63, 685, 22536, 63, 67, 685, 8016, 548, 8009, 2010, 2310, 15533, 203, 3639, 19945, 2502, 14708, 273, 450, 22536, 63, 67, 685, 8016, 548, 15533, 203, 203, 3639, 2583, 12, 266, 458, 367, 1545, 389, 14462, 1769, 203, 3639, 2254, 2071, 273, 389, 14462, 31, 203, 3639, 309, 261, 14462, 422, 374, 13, 288, 203, 5411, 2071, 273, 283, 458, 367, 31, 203, 3639, 289, 203, 3639, 309, 261, 685, 8016, 18, 90, 352, 414, 63, 67, 90, 20005, 8009, 266, 458, 367, 480, 374, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 6647, 14015, 685, 8016, 18, 27800, 63, 3417, 65, 422, 14708, 18, 27800, 63, 685, 8016, 18, 8082, 2093, 19338, 5717, 597, 203, 2398, 14708, 18, 8082, 2093, 19338, 422, 1624, 3991, 3719, 203, 3639, 288, 203, 5411, 2254, 389, 3338, 273, 2037, 31, 203, 5411, 309, 14015, 685, 8016, 18, 2019, 422, 19945, 1119, 18, 16457, 25674, 5027, 13, 747, 203, 9079, 14015, 685, 8016, 18, 2019, 422, 19945, 1119, 18, 2 ]
./partial_match/1/0xc0DF2B83725296d23C0C409C0759F3955b9fCC3A/sources/DigitalaxRewards.sol
weekNumber => rewards
contract DigitalaxRewards { using SafeMath for uint256; MONA public rewardsToken; DigitalaxAccessControls public accessControls; DigialaxStaking public genesisStaking; DigialaxStaking public parentStaking; DigialaxStaking public lpStaking; uint256 constant pointMultiplier = 10e18; uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_WEEK = 7 * 24 * 60 * 60; mapping (uint256 => uint256) public weeklyRewardsPerSecond; mapping (address => mapping(uint256 => uint256)) public weeklyBonusPerSecond; uint256 public startTime; uint256 public lastRewardTime; uint256 public genesisRewardsPaid; uint256 public parentRewardsPaid; uint256 public lpRewardsPaid; struct Weights { uint256 genesisWtPoints; uint256 parentWtPoints; uint256 lpWeightPoints; } event RewardAdded(address indexed addr, uint256 reward); event RewardDistributed(address indexed addr, uint256 reward); event Recovered(address indexed token, uint256 amount); MONA _rewardsToken, DigitalaxAccessControls _accessControls, DigialaxStaking _genesisStaking, DigialaxStaking _parentStaking, DigialaxStaking _lpStaking, uint256 _startTime, uint256 _lastRewardTime, uint256 _genesisRewardsPaid, uint256 _parentRewardsPaid, uint256 _lpRewardsPaid ) public mapping (uint256 => Weights) public weeklyWeightPoints; constructor( { rewardsToken = _rewardsToken; accessControls = _accessControls; genesisStaking = _genesisStaking; parentStaking = _parentStaking; lpStaking = _lpStaking; startTime = _startTime; lastRewardTime = _lastRewardTime; genesisRewardsPaid = _genesisRewardsPaid; parentRewardsPaid = _parentRewardsPaid; lpRewardsPaid = _lpRewardsPaid; } function setStartTime( uint256 _startTime, uint256 _lastRewardTime ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setStartTime: Sender must be admin" ); startTime = _startTime; lastRewardTime = _lastRewardTime; } function setInitialPoints( uint256 week, uint256 gW, uint256 pW, uint256 mW ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setStartTime: Sender must be admin" ); Weights storage weights = weeklyWeightPoints[week]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } function setGenesisStaking( address _addr ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setGenesisStaking: Sender must be admin" ); require(_addr != address(parentStaking)); require(_addr != address(lpStaking)); genesisStaking = DigialaxStaking(_addr); } function setParentStaking( address _addr ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setParentStaking: Sender must be admin" ); require(_addr != address(genesisStaking)); require(_addr != address(lpStaking)); parentStaking = DigialaxStaking(_addr); } function setLPStaking( address _addr ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setLPStaking: Sender must be admin" ); require(_addr != address(parentStaking)); require(_addr != address(genesisStaking)); lpStaking = DigialaxStaking(_addr); } function setRewards( uint256[] memory rewardWeeks, uint256[] memory amounts ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setRewards: Sender must be admin" ); uint256 numRewards = rewardWeeks.length; for (uint256 i = 0; i < numRewards; i++) { uint256 week = rewardWeeks[i]; uint256 amount = amounts[i].mul(pointMultiplier) .div(SECONDS_PER_WEEK) .div(pointMultiplier); weeklyRewardsPerSecond[week] = amount; } } function setRewards( uint256[] memory rewardWeeks, uint256[] memory amounts ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setRewards: Sender must be admin" ); uint256 numRewards = rewardWeeks.length; for (uint256 i = 0; i < numRewards; i++) { uint256 week = rewardWeeks[i]; uint256 amount = amounts[i].mul(pointMultiplier) .div(SECONDS_PER_WEEK) .div(pointMultiplier); weeklyRewardsPerSecond[week] = amount; } } function bonusRewards( address pool, uint256[] memory rewardWeeks, uint256[] memory amounts ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setRewards: Sender must be admin" ); uint256 numRewards = rewardWeeks.length; for (uint256 i = 0; i < numRewards; i++) { uint256 week = rewardWeeks[i]; uint256 amount = amounts[i].mul(pointMultiplier) .div(SECONDS_PER_WEEK) .div(pointMultiplier); weeklyBonusPerSecond[pool][week] = amount; } } function bonusRewards( address pool, uint256[] memory rewardWeeks, uint256[] memory amounts ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.setRewards: Sender must be admin" ); uint256 numRewards = rewardWeeks.length; for (uint256 i = 0; i < numRewards; i++) { uint256 week = rewardWeeks[i]; uint256 amount = amounts[i].mul(pointMultiplier) .div(SECONDS_PER_WEEK) .div(pointMultiplier); weeklyBonusPerSecond[pool][week] = amount; } } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function updateRewards() external returns(bool) { if (block.timestamp <= lastRewardTime) { return false; } uint256 g_net = genesisStaking.stakedEthTotal(); uint256 p_net = parentStaking.stakedEthTotal(); uint256 m_net = lpStaking.stakedEthTotal(); if (g_net.add(p_net).add(m_net) == 0 || block.timestamp <= startTime) { lastRewardTime = block.timestamp; return false; } (uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net); _updateWeightingAcc(gW,pW,mW); _updateParentRewards(); _updateLPRewards(); return true; } function updateRewards() external returns(bool) { if (block.timestamp <= lastRewardTime) { return false; } uint256 g_net = genesisStaking.stakedEthTotal(); uint256 p_net = parentStaking.stakedEthTotal(); uint256 m_net = lpStaking.stakedEthTotal(); if (g_net.add(p_net).add(m_net) == 0 || block.timestamp <= startTime) { lastRewardTime = block.timestamp; return false; } (uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net); _updateWeightingAcc(gW,pW,mW); _updateParentRewards(); _updateLPRewards(); return true; } function updateRewards() external returns(bool) { if (block.timestamp <= lastRewardTime) { return false; } uint256 g_net = genesisStaking.stakedEthTotal(); uint256 p_net = parentStaking.stakedEthTotal(); uint256 m_net = lpStaking.stakedEthTotal(); if (g_net.add(p_net).add(m_net) == 0 || block.timestamp <= startTime) { lastRewardTime = block.timestamp; return false; } (uint256 gW, uint256 pW, uint256 mW) = _getReturnWeights(g_net, p_net, m_net); _updateWeightingAcc(gW,pW,mW); _updateParentRewards(); _updateLPRewards(); return true; } _updateGenesisRewards(); lastRewardTime = block.timestamp; function totalRewards() external view returns (uint256) { uint256 gRewards = genesisRewards(lastRewardTime, block.timestamp); uint256 pRewards = parentRewards(lastRewardTime, block.timestamp); uint256 lRewards = LPRewards(lastRewardTime, block.timestamp); return gRewards.add(pRewards).add(lRewards); } function getTotalContributions() external view returns(uint256) { return genesisStaking.stakedEthTotal() .add(parentStaking.stakedEthTotal()) .add(lpStaking.stakedEthTotal()); } function getCurrentRewardWeek() external view returns(uint256) { return diffDays(startTime, block.timestamp) / 7; } function totalRewardsPaid() external view returns(uint256) { return genesisRewardsPaid.add(parentRewardsPaid).add(lpRewardsPaid); } function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander)); return rewards; } function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander)); return rewards; } function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander)); return rewards; } function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from); function genesisRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].genesisWtPoints) .add(weeklyBonusPerSecond[address(genesisStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].genesisWtPoints)) .add(weeklyBonusPerSecond[address(genesisStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime)); function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander)); return rewards; } function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander)); return rewards; } function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander)); return rewards; } function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from); function parentRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].parentWtPoints) .add(weeklyBonusPerSecond[address(parentStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].parentWtPoints)) .add(weeklyBonusPerSecond[address(parentStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime)); function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander)); return rewards; } function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander)); return rewards; } function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander)); return rewards; } function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from); function LPRewards(uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], _to.sub(_from), weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(_to.sub(_from))); } rewards = _rewardsFromPoints(weeklyRewardsPerSecond[fromWeek], initialRemander, weeklyWeightPoints[fromWeek].lpWeightPoints) .add(weeklyBonusPerSecond[address(lpStaking)][fromWeek].mul(initialRemander)); for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[i], SECONDS_PER_WEEK, weeklyWeightPoints[i].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][i].mul(SECONDS_PER_WEEK)); } rewards = rewards.add(_rewardsFromPoints(weeklyRewardsPerSecond[toWeek], finalRemander, weeklyWeightPoints[toWeek].lpWeightPoints)) .add(weeklyBonusPerSecond[address(lpStaking)][toWeek].mul(finalRemander)); return rewards; } uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime)); function _updateGenesisRewards() internal returns(uint256 rewards) { rewards = genesisRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { genesisRewardsPaid = genesisRewardsPaid.add(rewards); require(rewardsToken.mint(address(genesisStaking), rewards)); } } function _updateGenesisRewards() internal returns(uint256 rewards) { rewards = genesisRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { genesisRewardsPaid = genesisRewardsPaid.add(rewards); require(rewardsToken.mint(address(genesisStaking), rewards)); } } function _updateParentRewards() internal returns(uint256 rewards) { rewards = parentRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { parentRewardsPaid = parentRewardsPaid.add(rewards); require(rewardsToken.mint(address(parentStaking), rewards)); } } function _updateParentRewards() internal returns(uint256 rewards) { rewards = parentRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { parentRewardsPaid = parentRewardsPaid.add(rewards); require(rewardsToken.mint(address(parentStaking), rewards)); } } function _updateLPRewards() internal returns(uint256 rewards) { rewards = LPRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { lpRewardsPaid = lpRewardsPaid.add(rewards); require(rewardsToken.mint(address(lpStaking), rewards)); } } function _updateLPRewards() internal returns(uint256 rewards) { rewards = LPRewards(lastRewardTime, block.timestamp); if ( rewards > 0 ) { lpRewardsPaid = lpRewardsPaid.add(rewards); require(rewardsToken.mint(address(lpStaking), rewards)); } } function _rewardsFromPoints( uint256 rate, uint256 duration, uint256 weight ) internal pure returns(uint256) { return rate.mul(duration) .mul(weight) .div(1e18) .div(pointMultiplier); } function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7; uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK)); if (weeklyWeightPoints[0].genesisWtPoints == 0 && weeklyWeightPoints[0].parentWtPoints == 0 && weeklyWeightPoints[0].lpWeightPoints == 0 ) { Weights storage weights = weeklyWeightPoints[0]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } if (lastRewardWeek < currentWeek ) { for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) { Weights storage weights = weeklyWeightPoints[i]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } return; } weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek); weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek); weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek); } function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7; uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK)); if (weeklyWeightPoints[0].genesisWtPoints == 0 && weeklyWeightPoints[0].parentWtPoints == 0 && weeklyWeightPoints[0].lpWeightPoints == 0 ) { Weights storage weights = weeklyWeightPoints[0]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } if (lastRewardWeek < currentWeek ) { for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) { Weights storage weights = weeklyWeightPoints[i]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } return; } weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek); weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek); weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek); } function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7; uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK)); if (weeklyWeightPoints[0].genesisWtPoints == 0 && weeklyWeightPoints[0].parentWtPoints == 0 && weeklyWeightPoints[0].lpWeightPoints == 0 ) { Weights storage weights = weeklyWeightPoints[0]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } if (lastRewardWeek < currentWeek ) { for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) { Weights storage weights = weeklyWeightPoints[i]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } return; } weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek); weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek); weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek); } function _updateWeightingAcc(uint256 gW, uint256 pW, uint256 mW) internal { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; uint256 lastRewardWeek = diffDays(startTime, lastRewardTime) / 7; uint256 startCurrentWeek = startTime.add(currentWeek.mul(SECONDS_PER_WEEK)); if (weeklyWeightPoints[0].genesisWtPoints == 0 && weeklyWeightPoints[0].parentWtPoints == 0 && weeklyWeightPoints[0].lpWeightPoints == 0 ) { Weights storage weights = weeklyWeightPoints[0]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } if (lastRewardWeek < currentWeek ) { for (uint256 i = lastRewardWeek+1; i <= currentWeek; i++) { Weights storage weights = weeklyWeightPoints[i]; weights.genesisWtPoints = gW; weights.parentWtPoints = pW; weights.lpWeightPoints = mW; } return; } weights.genesisWtPoints = _calcWeightPoints(weights.genesisWtPoints,gW,startCurrentWeek); weights.parentWtPoints = _calcWeightPoints(weights.parentWtPoints,pW,startCurrentWeek); weights.lpWeightPoints = _calcWeightPoints(weights.lpWeightPoints,mW,startCurrentWeek); } Weights storage weights = weeklyWeightPoints[currentWeek]; function _calcWeightPoints( uint256 prevWeight, uint256 newWeight, uint256 startCurrentWeek ) internal view returns(uint256) { uint256 previousWeighting = prevWeight.mul(lastRewardTime.sub(startCurrentWeek)); uint256 currentWeighting = newWeight.mul(block.timestamp.sub(lastRewardTime)); return previousWeighting.add(currentWeighting) .div(block.timestamp.sub(startCurrentWeek)); } function max(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a >= b ? a : b; } function _getReturnWeights( uint256 _g, uint256 _p, uint256 _m ) internal view returns(uint256,uint256,uint256) { uint256 eg = _g.mul(_getSqrtWeight(_g,_p,_m).div(1e18)); uint256 ep = _p.mul(_getSqrtWeight(_p,_m,_g).div(1e18)); uint256 em = _m.mul(_getSqrtWeight(_m,_g,_p).div(1e18)); uint256 norm = eg.add(ep).add(em); return (eg.mul(pointMultiplier).mul(1e18).div(norm), ep.mul(pointMultiplier).mul(1e18).div(norm), em.mul(pointMultiplier).mul(1e18).div(norm)); } function _getSqrtWeight( uint256 _a, uint256 _b, uint256 _c ) internal view returns( uint256 wA ) { if ( _a <= _b.add(_c) || _b.add(_c) == 0 ) { return 1e18; } uint256 A2 = max(_a.mul(1e18).div(max(_c,1e18)),1e18); uint256 A = A1.mul(A2).div(1e18); } function _getSqrtWeight( uint256 _a, uint256 _b, uint256 _c ) internal view returns( uint256 wA ) { if ( _a <= _b.add(_c) || _b.add(_c) == 0 ) { return 1e18; } uint256 A2 = max(_a.mul(1e18).div(max(_c,1e18)),1e18); uint256 A = A1.mul(A2).div(1e18); } uint256 A1 = max(_a.mul(1e18).div(max(_b,1e18)),1e18); wA = _sqrt(uint256(1e18).mul(1e18).div(A)).mul(1e9); function _sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } function _sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } function _sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } z = 1; } } } else if (y != 0) { function recoverERC20( address tokenAddress, uint256 tokenAmount ) external { require( accessControls.hasAdminRole(msg.sender), "DigitalaxRewards.recoverERC20: Sender must be admin" ); require( tokenAddress != address(rewardsToken), "Cannot withdraw the rewards token" ); IERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function getCurrentWeek() external view returns(uint256) { return diffDays(startTime, block.timestamp) / 7; } function getCurrentGenesisWtPoints() external view returns(uint256) { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; return weeklyWeightPoints[currentWeek].genesisWtPoints; } function getCurrentParentWtPoints() external view returns(uint256) { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; return weeklyWeightPoints[currentWeek].parentWtPoints; } function getCurrentLpWeightPoints() external view returns(uint256) { uint256 currentWeek = diffDays(startTime, block.timestamp) / 7; return weeklyWeightPoints[currentWeek].lpWeightPoints; } function getGenesisStakedEthTotal() public view returns(uint256) { return genesisStaking.stakedEthTotal(); } function getLpStakedEthTotal() public view returns(uint256) { return lpStaking.stakedEthTotal(); } function getParentStakedEthTotal() public view returns(uint256) { return parentStaking.stakedEthTotal(); } function getGenesisDailyAPY() external view returns (uint256) { uint256 stakedEth = getGenesisStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = genesisRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getGenesisDailyAPY() external view returns (uint256) { uint256 stakedEth = getGenesisStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = genesisRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getParentDailyAPY() external view returns (uint256) { uint256 stakedEth = getParentStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = parentRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getParentDailyAPY() external view returns (uint256) { uint256 stakedEth = getParentStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = parentRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getLpDailyAPY() external view returns (uint256) { uint256 stakedEth = getLpStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = LPRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getLpDailyAPY() external view returns (uint256) { uint256 stakedEth = getLpStakedEthTotal(); if ( stakedEth == 0 ) { return 0; } uint256 rewards = LPRewards(block.timestamp,block.timestamp + SECONDS_PER_DAY); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); return rewardsInEth.mul(36500).mul(1e18).div(stakedEth); } function getMonaPerEth() public view returns (uint256) { (uint256 wethReserve, uint256 tokenReserve) = getPairReserves(); return UniswapV2Library.quote(1e18, wethReserve, tokenReserve); } function getEthPerMona() public view returns (uint256) { (uint256 wethReserve, uint256 tokenReserve) = getPairReserves(); return UniswapV2Library.quote(1e18, tokenReserve, wethReserve); } function getPairReserves() internal view returns (uint256 wethReserves, uint256 tokenReserves) { (address token0,) = UniswapV2Library.sortTokens(address(lpStaking.WETH()), address(rewardsToken)); (uint256 reserve0, uint reserve1,) = IUniswapV2Pair(lpStaking.lpToken()).getReserves(); (wethReserves, tokenReserves) = token0 == address(rewardsToken) ? (reserve1, reserve0) : (reserve0, reserve1); } }
15,510,960
[ 1, 10741, 1854, 516, 283, 6397, 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, 16351, 11678, 7053, 651, 17631, 14727, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 30215, 37, 1071, 283, 6397, 1345, 31, 203, 565, 11678, 7053, 651, 16541, 87, 1071, 2006, 16795, 31, 203, 565, 11678, 649, 651, 510, 6159, 1071, 21906, 510, 6159, 31, 203, 565, 11678, 649, 651, 510, 6159, 1071, 982, 510, 6159, 31, 203, 565, 11678, 649, 651, 510, 6159, 1071, 12423, 510, 6159, 31, 203, 203, 565, 2254, 5034, 5381, 1634, 23365, 273, 1728, 73, 2643, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 10339, 273, 4248, 380, 4752, 380, 4752, 31, 203, 565, 2254, 5034, 5381, 17209, 67, 3194, 67, 20274, 273, 2371, 380, 4248, 380, 4752, 380, 4752, 31, 203, 377, 203, 565, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 1071, 4860, 715, 17631, 14727, 2173, 8211, 31, 203, 565, 2874, 261, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1071, 4860, 715, 38, 22889, 2173, 8211, 31, 203, 203, 565, 2254, 5034, 1071, 8657, 31, 203, 565, 2254, 5034, 1071, 1142, 17631, 1060, 950, 31, 203, 203, 565, 2254, 5034, 1071, 21906, 17631, 14727, 16507, 350, 31, 203, 565, 2254, 5034, 1071, 982, 17631, 14727, 16507, 350, 31, 203, 565, 2254, 5034, 1071, 12423, 17631, 14727, 16507, 350, 31, 203, 203, 203, 565, 1958, 15437, 87, 288, 203, 3639, 2254, 5034, 21906, 59, 88, 5636, 31, 203, 3639, 2254, 5034, 982, 59, 88, 5636, 31, 203, 3639, 2254, 5034, 12423, 6544, 5636, 31, 203, 565, 289, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //IERC721MultiClass interface import "./../interfaces/IERC721TransferFees.sol"; /** * @dev Abstract extension of ERC721TransferFees that attaches royalty fees */ abstract contract ERC721TransferFees is IERC721TransferFees { //10000 means 100.00% uint256 private constant TOTAL_ALLOWABLE_FEES = 10000; //mapping of `classId` to total fees (could be problematic if not synced) uint256 private _fees; //mapping of `recipient` to fee mapping(address => uint256) private _fee; //index mapping of `classId` to recipients (so we can loop the map) address[] private _recipients; /** * @dev Returns the fee of a `recipient` */ function feeOf(address recipient) public view override returns(uint256) { return _fee[recipient]; } /** * @dev Returns total fees */ function totalFees() public view override returns(uint256) { return _fees; } /** * @dev Sets a fee that will be collected during the exchange method */ function _allocateFee(address recipient, uint256 fee) internal virtual { require(fee > 0, "ERC721TransferFees: Fee should be more than 0"); //if no recipient if (_fee[recipient] == 0) { //add recipient _recipients.push(recipient); //map fee _fee[recipient] = fee; //add to total fee _fees += fee; //else there"s already an existing recipient } else { //remove old fee from total fee _fees -= _fee[recipient]; //map fee _fee[recipient] = fee; //add to total fee _fees += fee; } //safe check require( _fees <= TOTAL_ALLOWABLE_FEES, "ERC721TransferFees: Exceeds allowable fees" ); } /** * @dev Removes a fee */ function _deallocateFee(address recipient) internal virtual { //this is for the benefit of the sender so they //dont have to pay gas on things that dont matter require(_fee[recipient] != 0, "ERC721TransferFees: Recipient has no fees"); //deduct total fees _fees -= _fee[recipient]; //remove fees from the map delete _fee[recipient]; //Tricky logic to remove an element from an array... //if there are at least 2 elements in the array, if (_recipients.length > 1) { //find the recipient for (uint i = 0; i < _recipients.length; i++) { if(_recipients[i] == recipient) { //move the last element to the deleted element uint last = _recipients.length - 1; _recipients[i] = _recipients[last]; break; } } } //either way remove the last element _recipients.pop(); } /** * @dev Pays the amount to the recipients */ function _escrowFees(uint256 amount) internal virtual returns(uint256) { //placeholder for recipient in the loop address recipient; //release payments to recipients for (uint i = 0; i < _recipients.length; i++) { //get the recipient recipient = _recipients[i]; // (10 eth * 2000) / 10000 = payable(recipient).transfer( (amount * _fee[recipient]) / TOTAL_ALLOWABLE_FEES ); } //determine the remaining fee percent uint256 remainingFee = TOTAL_ALLOWABLE_FEES - _fees; //return the remainder amount return (amount * remainingFee) / TOTAL_ALLOWABLE_FEES; } }
* @dev Removes a fee/this is for the benefit of the sender so theydont have to pay gas on things that dont matterdeduct total feesremove fees from the mapTricky logic to remove an element from an array...if there are at least 2 elements in the array,find the recipientmove the last element to the deleted element
function _deallocateFee(address recipient) internal virtual { require(_fee[recipient] != 0, "ERC721TransferFees: Recipient has no fees"); _fees -= _fee[recipient]; delete _fee[recipient]; if (_recipients.length > 1) { for (uint i = 0; i < _recipients.length; i++) { if(_recipients[i] == recipient) { uint last = _recipients.length - 1; _recipients[i] = _recipients[last]; break; } } } }
5,373,146
[ 1, 6220, 279, 14036, 19, 2211, 353, 364, 326, 27641, 7216, 434, 326, 5793, 1427, 2898, 72, 1580, 1240, 358, 8843, 16189, 603, 9198, 716, 14046, 15177, 785, 853, 2078, 1656, 281, 4479, 1656, 281, 628, 326, 852, 1070, 13055, 4058, 358, 1206, 392, 930, 628, 392, 526, 2777, 430, 1915, 854, 622, 4520, 576, 2186, 316, 326, 526, 16, 4720, 326, 8027, 8501, 326, 1142, 930, 358, 326, 4282, 930, 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, 225, 445, 389, 323, 16247, 14667, 12, 2867, 8027, 13, 2713, 5024, 288, 203, 565, 2583, 24899, 21386, 63, 20367, 65, 480, 374, 16, 315, 654, 39, 27, 5340, 5912, 2954, 281, 30, 23550, 711, 1158, 1656, 281, 8863, 203, 565, 389, 3030, 281, 3947, 389, 21386, 63, 20367, 15533, 203, 565, 1430, 389, 21386, 63, 20367, 15533, 203, 565, 309, 261, 67, 27925, 18, 2469, 405, 404, 13, 288, 203, 1377, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 27925, 18, 2469, 31, 277, 27245, 288, 203, 3639, 309, 24899, 27925, 63, 77, 65, 422, 8027, 13, 288, 203, 1850, 2254, 1142, 273, 389, 27925, 18, 2469, 300, 404, 31, 203, 1850, 389, 27925, 63, 77, 65, 273, 389, 27925, 63, 2722, 15533, 203, 1850, 898, 31, 203, 3639, 289, 203, 1377, 289, 203, 565, 289, 203, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // 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 CAKEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCakePerShare` (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 { address lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CAKEs to distribute per block. uint256 lastRewardBlock; // Last block number that CAKEs distribution occurs. uint256 accCakePerShare; // Accumulated CAKEs per share, times 1e12. See below. } interface IPancakeStaking { // The CAKE TOKEN! function cake() external returns (address); // The SYRUP TOKEN! function syrup() external returns (address); // Dev address. function devaddr() external returns (address); // CAKE tokens created per block. function cakePerBlock() external returns (uint256); // Bonus muliplier for early cake makers. function BONUS_MULTIPLIER() external returns (uint256); // The migrator contract. It has a lot of power. Can only be set through governance (owner). function migrator() external returns (address); // Info of each pool. function poolInfo(uint256 _pid) external view returns (PoolInfo memory); // Info of each user that stakes LP tokens. function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); // Total allocation poitns. Must be the sum of all allocation points in all pools. function totalAllocPoint() external returns (uint256); // The block number when CAKE mining starts. function startBlock() external returns (uint256); function poolLength() external view returns (uint256); // 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, address _lpToken, bool _withUpdate ) external; // Update the given pool's CAKE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; // Set the migrator contract. Can only be called by the owner. function setMigrator(address _migrator) external; // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) external; // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); // View function to see pending CAKEs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256); // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() external; // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) external; // Deposit LP tokens to MasterChef for CAKE allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Stake CAKE tokens to MasterChef function enterStaking(uint256 _amount) external; // Withdraw CAKE tokens from STAKING. function leaveStaking(uint256 _amount) external; // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external; }
Address of LP token contract.
address lpToken;
5,442,795
[ 1, 1887, 434, 511, 52, 1147, 6835, 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 ]
[ 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, 1758, 12423, 1345, 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, -100 ]
pragma solidity ^0.4.13; library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } 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'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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @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]); // 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; } /** * @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 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @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); 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; 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); 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract APRInflationToken is StandardToken, Ownable { // Constants used in calculations uint256 constant RATE_DECIMALS = 7; uint256 constant HORIZON = 365 * 10; uint256 constant ONE_DAY = 86400; uint256 constant DAY_SCALE = 365 * 10 ** RATE_DECIMALS; uint256 constant START_RATE = 10 * 10 ** (RATE_DECIMALS - 2); uint256 constant END_RATE = 1 * 10 ** (RATE_DECIMALS - 2); uint256 constant ADJ_RATE = (START_RATE - END_RATE) / HORIZON; // Date control variables uint256 public startDate; uint256 public lastAdjust; // events -------------------------------------------------------------------- event APRMintAdjusted(uint256 _newSupply, uint256 _extraSupply, uint256 _daysPassed, uint256 _rate); // constructor function ------------------------------------------------------ /** * @dev Adjusts all the necessary calculations in constructor */ function APRInflationToken(uint _startDate) public { startDate = _startDate; lastAdjust = 0; } // external functions -------------------------------------------------------- /** * @dev allows anyone to adjust the year mint by calling aprMintAdjustment * which will calculate days since the latest adjustment and run all calculation * according N days skipped N days calculated * @return true */ function aprMintAdjustment() public returns (bool) { uint256 extraSupply; uint256 day; for (day = lastAdjust + 1; day <= _currentDay(); day++) { uint256 rate = _rateFromDay(day); extraSupply = totalSupply_.mul(rate).div(DAY_SCALE); totalSupply_ = totalSupply_.add(extraSupply); balances[owner] = balances[owner].add(extraSupply); // Adjusts the day of the latest calculation lastAdjust = day; APRMintAdjusted(totalSupply_, extraSupply, lastAdjust, rate); } return true; } function _safeSub(uint256 a, uint256 b) internal pure returns(uint256) { return b > a ? 0 : a.sub(b); } // internal functions -------------------------------------------------------- function _rateFromDay(uint256 day) internal pure returns(uint256) { if (day < 1) { return 0; } uint256 rate = _safeSub(START_RATE, (day.sub(1)).mul(ADJ_RATE)); return END_RATE > rate ? END_RATE : rate; } // Returns the amount of days since the start date // The calculations are made using the timestamp in seconds function _currentDay() internal view returns(uint256) { return now.sub(startDate).div(ONE_DAY); } } contract DelegateCallToken is APRInflationToken { string public name = 'DelegateCallToken'; string public symbol = 'DCT'; uint8 public decimals = 18; // one billion uint256 public constant INITIAL_SUPPLY = 1000000000; function DelegateCallToken(uint256 _startDate) public APRInflationToken(_startDate) { owner = msg.sender; totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals)); balances[owner] = totalSupply_; } }
* @dev Adjusts all the necessary calculations in constructor/
function APRInflationToken(uint _startDate) public { startDate = _startDate; lastAdjust = 0; }
11,725,311
[ 1, 10952, 87, 777, 326, 4573, 20882, 316, 3885, 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, 225, 445, 432, 8025, 27040, 20611, 12, 11890, 389, 1937, 1626, 13, 1071, 288, 203, 565, 12572, 273, 389, 1937, 1626, 31, 203, 565, 1142, 10952, 273, 374, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./gelato/PokeMe.sol"; import "./CreamLoanSaver.sol"; contract CreamLoanSaverService is CreamLoanSaver, Ownable { using EnumerableSet for EnumerableSet.Bytes32Set; mapping(address => bool) public whiteListedTokens; event ProtectionSubmitted(address indexed account, bytes32 indexed protectionId); event ProtectionCanceled(address indexed account, bytes32 indexed protectionId); constructor( address payable _pokeMe, address _cusdcAddress, address _gelato, IComptroller _comptroller, IUniswapV2Router02 _uniswapRouter, IPriceOracle _oracle ) CreamLoanSaver(_pokeMe, _cusdcAddress, _gelato, _comptroller, _uniswapRouter, _oracle) {} /// @notice submit loan protection to PokeMe /// crETH is not supported /// To work protection, caller needs to approve this contract using Collateral crToken beforehand function submitProtection( uint256 thresholdHealthFactor, uint256 wantedHealthFactor, CToken colToken, CToken debtToken, address _resolverAddress, bytes calldata _resolverData, bool _useTaskTreasuryFunds ) public { bytes32 protectionId = keccak256( abi.encode(msg.sender, thresholdHealthFactor, wantedHealthFactor, colToken, debtToken, _resolverData) ); require(_createdProtections[msg.sender].contains(protectionId) == false, "already-started-protection"); require( wantedHealthFactor > thresholdHealthFactor && thresholdHealthFactor > EXP_SCALE, "invalid-health-factor-input" ); require(colToken != debtToken, "collateral-debt-same"); require(whiteListedTokens[address(colToken)], "collateral-token-not-allowed"); require(whiteListedTokens[address(debtToken)], "debt-token-not-allowed"); _createdProtections[msg.sender].add(protectionId); _protectionData[protectionId] = ProtectionData({ thresholdHealthFactor: thresholdHealthFactor, wantedHealthFactor: wantedHealthFactor, colToken: colToken, debtToken: debtToken }); PokeMe(pokeMe).createTask( address(this), this.saveLoan.selector, _resolverAddress, _resolverData, _useTaskTreasuryFunds ); emit ProtectionSubmitted(msg.sender, protectionId); } function cancelProtection(bytes32 protectionId) public { require(_createdProtections[msg.sender].contains(protectionId), "protection-not-found"); _createdProtections[msg.sender].remove(protectionId); delete _protectionData[protectionId]; emit ProtectionCanceled(msg.sender, protectionId); } function addTokenToWhiteList(CToken cToken) public onlyOwner { whiteListedTokens[address(cToken)] = true; } function removeTokenFromWhiteList(CToken cToken) public onlyOwner { delete whiteListedTokens[address(cToken)]; } function setProtectionFeeBps(uint256 _protectionFeeBps) public onlyOwner { protectionFeeBps = _protectionFeeBps; } function setFlashFeeBps(uint256 _flashFeeBps) public onlyOwner { flashFeeBps = _flashFeeBps; } }
@notice submit loan protection to PokeMe crETH is not supported To work protection, caller needs to approve this contract using Collateral crToken beforehand
) public { bytes32 protectionId = keccak256( abi.encode(msg.sender, thresholdHealthFactor, wantedHealthFactor, colToken, debtToken, _resolverData) ); require(_createdProtections[msg.sender].contains(protectionId) == false, "already-started-protection"); require( wantedHealthFactor > thresholdHealthFactor && thresholdHealthFactor > EXP_SCALE, "invalid-health-factor-input" ); require(colToken != debtToken, "collateral-debt-same"); require(whiteListedTokens[address(colToken)], "collateral-token-not-allowed"); require(whiteListedTokens[address(debtToken)], "debt-token-not-allowed"); _createdProtections[msg.sender].add(protectionId); _protectionData[protectionId] = ProtectionData({ thresholdHealthFactor: thresholdHealthFactor, wantedHealthFactor: wantedHealthFactor, colToken: colToken, debtToken: debtToken }); PokeMe(pokeMe).createTask( address(this), this.saveLoan.selector, _resolverAddress, _resolverData, _useTaskTreasuryFunds ); emit ProtectionSubmitted(msg.sender, protectionId); }
5,474,524
[ 1, 9297, 28183, 17862, 358, 453, 3056, 4667, 4422, 1584, 44, 353, 486, 3260, 2974, 1440, 17862, 16, 4894, 4260, 358, 6617, 537, 333, 6835, 1450, 17596, 2045, 287, 4422, 1345, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 1071, 288, 203, 3639, 1731, 1578, 17862, 548, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 3576, 18, 15330, 16, 5573, 7802, 6837, 16, 15504, 7802, 6837, 16, 645, 1345, 16, 18202, 88, 1345, 16, 389, 14122, 751, 13, 203, 3639, 11272, 203, 203, 3639, 2583, 24899, 4824, 16938, 87, 63, 3576, 18, 15330, 8009, 12298, 12, 685, 9694, 548, 13, 422, 629, 16, 315, 17583, 17, 14561, 17, 685, 9694, 8863, 203, 3639, 2583, 12, 203, 5411, 15504, 7802, 6837, 405, 5573, 7802, 6837, 597, 5573, 7802, 6837, 405, 22615, 67, 19378, 16, 203, 5411, 315, 5387, 17, 13267, 17, 6812, 17, 2630, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 1293, 1345, 480, 18202, 88, 1345, 16, 315, 12910, 2045, 287, 17, 323, 23602, 17, 14307, 8863, 203, 3639, 2583, 12, 14739, 682, 329, 5157, 63, 2867, 12, 1293, 1345, 13, 6487, 315, 12910, 2045, 287, 17, 2316, 17, 902, 17, 8151, 8863, 203, 3639, 2583, 12, 14739, 682, 329, 5157, 63, 2867, 12, 323, 23602, 1345, 13, 6487, 315, 323, 23602, 17, 2316, 17, 902, 17, 8151, 8863, 203, 203, 3639, 389, 4824, 16938, 87, 63, 3576, 18, 15330, 8009, 1289, 12, 685, 9694, 548, 1769, 203, 3639, 389, 685, 9694, 751, 63, 685, 9694, 548, 65, 273, 1186, 9694, 751, 12590, 203, 5411, 5573, 7802, 6837, 30, 5573, 7802, 6837, 16, 203, 5411, 15504, 7802, 6837, 30, 15504, 7802, 6837, 16, 203, 5411, 645, 1345, 30, 645, 1345, 16, 203, 5411, 18202, 88, 1345, 2 ]
./full_match/97/0xa650d5fB7002a35d9370Efdad2a0888Ecc252E98/sources/contracts/UPController.sol
@notice Borrows UP token minting it
function borrowUP(uint256 _borrowAmount, address _to) public onlyRebalancer whenNotPaused { upBorrowed += _borrowAmount; UP(UP_TOKEN).mint(_to, _borrowAmount); emit SyntheticMint(msg.sender, _borrowAmount, upBorrowed); }
5,034,494
[ 1, 38, 280, 3870, 7376, 1147, 312, 474, 310, 518, 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, 225, 445, 29759, 3079, 12, 11890, 5034, 389, 70, 15318, 6275, 16, 1758, 389, 869, 13, 1071, 1338, 426, 18770, 1347, 1248, 28590, 288, 203, 565, 731, 38, 15318, 329, 1011, 389, 70, 15318, 6275, 31, 203, 565, 7376, 12, 3079, 67, 8412, 2934, 81, 474, 24899, 869, 16, 389, 70, 15318, 6275, 1769, 203, 565, 3626, 16091, 16466, 49, 474, 12, 3576, 18, 15330, 16, 389, 70, 15318, 6275, 16, 731, 38, 15318, 329, 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 ]
pragma solidity ^0.4.24; // File: node_modules\zeppelin-solidity\contracts\math\SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } // File: node_modules\zeppelin-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 / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 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 DetailedERC20 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 TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // 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 TokenPurchase( 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 to concatenate validations. * @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.safeTransfer(_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); } } // File: node_modules\zeppelin-solidity\contracts\ownership\Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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. * @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 OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: node_modules\zeppelin-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 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @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; } /** * @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); } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\distribution\FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BasicToken.sol /** * @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]; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * 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; } } // File: node_modules\zeppelin-solidity\contracts\crowdsale\emission\MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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 ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: node_modules\zeppelin-solidity\contracts\math\Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: node_modules\zeppelin-solidity\contracts\payment\Escrow.sol /** * @title Escrow * @dev Base escrow contract, holds funds destinated to a payee until they * withdraw them. The contract that uses the escrow as its payment method * should be its owner, and provide public methods redirecting to the escrow's * deposit and withdraw. */ contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param _payee The destination address of the funds. */ function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } /** * @dev Withdraw accumulated balance for a payee. * @param _payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } // File: node_modules\zeppelin-solidity\contracts\payment\ConditionalEscrow.sol /** * @title ConditionalEscrow * @dev Base abstract escrow to only allow withdrawal if a condition is met. */ contract ConditionalEscrow is Escrow { /** * @dev Returns whether an address is allowed to withdraw their funds. To be * implemented by derived contracts. * @param _payee The destination address of the funds. */ function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } // File: node_modules\zeppelin-solidity\contracts\payment\RefundEscrow.sol /** * @title RefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } /** * @dev Allows for refunds to take place, rejecting further deposits. */ function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @dev Withdraws the beneficiary's funds. */ function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } /** * @dev Returns whether refundees can withdraw their deposits (be refunded). */ function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } // File: contracts\ClinicAllRefundEscrow.sol /** * @title ClinicAllRefundEscrow * @dev Escrow that holds funds for a beneficiary, deposited from multiple parties. * The contract owner may close the deposit period, and allow for either withdrawal * by the beneficiary, or refunds to the depositors. */ contract ClinicAllRefundEscrow is RefundEscrow { using Math for uint256; struct RefundeeRecord { bool isRefunded; uint256 index; } mapping(address => RefundeeRecord) public refundees; address[] internal refundeesList; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; mapping(address => uint256) private beneficiaryDeposits; // Amount of wei deposited by beneficiary uint256 public beneficiaryDepositedAmount; // Amount of wei deposited by investors to CrowdSale uint256 public investorsDepositedToCrowdSaleAmount; /** * @dev Constructor. * @param _beneficiary The beneficiary of the deposits. */ constructor(address _beneficiary) RefundEscrow(_beneficiary) public { } function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } function beneficiaryDepositsOf(address _payee) public view returns (uint256) { return beneficiaryDeposits[_payee]; } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. */ function deposit(address _refundee) public payable { uint256 amount = msg.value; beneficiaryDeposits[_refundee] = beneficiaryDeposits[_refundee].add(amount); beneficiaryDepositedAmount = beneficiaryDepositedAmount.add(amount); } /** * @dev Stores funds that may later be refunded. * @param _refundee The address funds will be sent to if a refund occurs. * @param _value The amount of funds will be sent to if a refund occurs. */ function depositFunds(address _refundee, uint256 _value) public onlyOwner { require(state == State.Active, "Funds deposition is possible only in the Active state."); uint256 amount = _value; deposits[_refundee] = deposits[_refundee].add(amount); investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.add(amount); emit Deposited(_refundee, amount); RefundeeRecord storage _data = refundees[_refundee]; _data.isRefunded = false; if (_data.index == uint256(0)) { refundeesList.push(_refundee); _data.index = refundeesList.length.sub(1); } } /** * @dev Allows for the beneficiary to withdraw their funds, rejecting * further deposits. */ function close() public onlyOwner { super.close(); } function withdraw(address _payee) public onlyOwner { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.sub(payment); _payee.transfer(payment); emit Withdrawn(_payee, payment); _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal."); RefundeeRecord storage _data = refundees[_payee]; require(_data.isRefunded == false, "An investor should not be refunded."); deposits[_payee] = 0; _data.isRefunded = true; removeRefundeeByIndex(_data.index); } /** * @dev Remove refundee referenced index from the internal list * @param _indexToDelete An index in an array for deletion */ function removeRefundeeByIndex(uint256 _indexToDelete) private { if ((refundeesList.length > 0) && (_indexToDelete < refundeesList.length)) { uint256 _lastIndex = refundeesList.length.sub(1); refundeesList[_indexToDelete] = refundeesList[_lastIndex]; refundeesList.length--; } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return refundeesList.length; } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); uint256 _refundeesCount = refundeesList.length; require(_chunkLength >= _refundeesCount); require(_txFee > 0, "Transaction fee should be above zero."); require(_refundeesCount > 0, "List of investors should not be empty."); uint256 _weiRefunded = 0; require(address(this).balance > (_chunkLength.mul(_txFee)), "Account's ballance should allow to pay all tx fees."); address[] memory _refundeesListCopy = new address[](_chunkLength); uint256 i; for (i = 0; i < _chunkLength; i++) { address _refundee = refundeesList[i]; RefundeeRecord storage _data = refundees[_refundee]; if (_data.isRefunded == false) { if (depositsOf(_refundee) > _txFee) { uint256 _deposit = depositsOf(_refundee); if (_deposit > _txFee) { _weiRefunded = _weiRefunded.add(_deposit); uint256 _paymentWithoutTxFee = _deposit.sub(_txFee); _refundee.transfer(_paymentWithoutTxFee); emit Withdrawn(_refundee, _paymentWithoutTxFee); _data.isRefunded = true; _refundeesListCopy[i] = _refundee; } } } } for (i = 0; i < _chunkLength; i++) { if (address(0) != _refundeesListCopy[i]) { RefundeeRecord storage _dataCleanup = refundees[_refundeesListCopy[i]]; require(_dataCleanup.isRefunded == true, "Investors in this list should be refunded."); removeRefundeeByIndex(_dataCleanup.index); } } return (_weiRefunded, _refundeesListCopy); } /** * @dev Auto refund * @param _txFee The cost of executing refund code */ function withdrawEverything(uint256 _txFee) public onlyOwner returns (uint256, address[]) { require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state."); return withdrawChunk(_txFee, refundeesList.length); } /** * @dev Withdraws the part of beneficiary's funds. */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { require(_value <= address(this).balance, "Withdraw part can not be more than current balance"); beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } /** * @dev Withdraws all beneficiary's funds. */ function beneficiaryWithdrawAll() public onlyOwner { uint256 _value = address(this).balance; beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value); beneficiary.transfer(_value); } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\TokenDestructible.sol /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner public { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\BurnableToken.sol /** * @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); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\DetailedERC20.sol /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: node_modules\zeppelin-solidity\contracts\lifecycle\Pausable.sol /** * @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(); } } // File: node_modules\zeppelin-solidity\contracts\token\ERC20\PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts\TransferableToken.sol /** * @title TransferableToken * @dev Base contract which allows to implement transfer for token. */ contract TransferableToken is Ownable { event TransferOn(); event TransferOff(); bool public transferable = false; /** * @dev Modifier to make a function callable only when the contract is not transferable. */ modifier whenNotTransferable() { require(!transferable); _; } /** * @dev Modifier to make a function callable only when the contract is transferable. */ modifier whenTransferable() { require(transferable); _; } /** * @dev called by the owner to enable transfers */ function transferOn() onlyOwner whenNotTransferable public { transferable = true; emit TransferOn(); } /** * @dev called by the owner to disable transfers */ function transferOff() onlyOwner whenTransferable public { transferable = false; emit TransferOff(); } } // File: contracts\ClinicAllToken.sol contract ClinicAllToken is MintableToken, DetailedERC20, CappedToken, PausableToken, BurnableToken, TokenDestructible, TransferableToken { constructor ( string _name, string _symbol, uint8 _decimals, uint256 _cap ) DetailedERC20(_name, _symbol, _decimals) CappedToken(_cap) public { } /*/ * Refund event when ICO didn't pass soft cap and we refund ETH to investors + burn ERC-20 tokens from investors balances /*/ function burnAfterRefund(address _who) public onlyOwner { uint256 _value = balances[_who]; _burn(_who, _value); } /*/ * Allow transfers only if token is transferable /*/ function transfer( address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transfer(_to, _value); } /*/ * Allow transfers only if token is transferable /*/ function transferFrom( address _from, address _to, uint256 _value ) public whenTransferable returns (bool) { return super.transferFrom(_from, _to, _value); } function transferToPrivateInvestor( address _from, address _to, uint256 _value ) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function burnPrivateSale(address privateSaleWallet, uint256 _value) public onlyOwner { _burn(privateSaleWallet, _value); } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: node_modules\zeppelin-solidity\contracts\ownership\rbac\RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: contracts\Managed.sol /** * @title Managed * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Managed is Ownable, RBAC { string public constant ROLE_MANAGER = "manager"; /** * @dev Throws if operator is not whitelisted. */ modifier onlyManager() { checkRole(msg.sender, ROLE_MANAGER); _; } /** * @dev set an address as a manager * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function setManager(address _operator) public onlyOwner { addRole(_operator, ROLE_MANAGER); } /** * @dev delete an address as a manager * @param _operator address * @return true if the address was deleted from the whitelist, false if the address wasn't already in the whitelist */ function removeManager(address _operator) public onlyOwner { removeRole(_operator, ROLE_MANAGER); } } // File: contracts\Limited.sol /** * @title LimitedCrowdsale * @dev Crowdsale in which only limited number of tokens can be bought. */ contract Limited is Managed { using SafeMath for uint256; mapping(address => uint256) public limitsList; /** * @dev Reverts if beneficiary has no limit. Can be used when extending this contract. */ modifier isLimited(address _payee) { require(limitsList[_payee] > 0, "An investor is limited if it has a limit."); _; } /** * @dev Reverts if beneficiary want to buy more tickets than limit allows. Can be used when extending this contract. */ modifier doesNotExceedLimit(address _payee, uint256 _tokenAmount, uint256 _tokenBalance, uint256 kycLimitEliminator) { if(_tokenBalance.add(_tokenAmount) >= kycLimitEliminator) { require(_tokenBalance.add(_tokenAmount) <= getLimit(_payee), "An investor should not exceed its limit on buying."); } _; } /** * @dev Returns limits for _payee. * @param _payee Address to get token limits */ function getLimit(address _payee) public view returns (uint256) { return limitsList[_payee]; } /** * @dev Adds limits to addresses. * @param _payees Addresses to set limit * @param _limits Limit values to set to addresses */ function addAddressesLimits(address[] _payees, uint256[] _limits) public onlyManager { require(_payees.length == _limits.length, "Array sizes should be equal."); for (uint256 i = 0; i < _payees.length; i++) { addLimit(_payees[i], _limits[i]); } } /** * @dev Adds limit to address. * @param _payee Address to set limit * @param _limit Limit value to set to address */ function addLimit(address _payee, uint256 _limit) public onlyManager { limitsList[_payee] = _limit; } /** * @dev Removes single address-limit record. * @param _payee Address to be removed */ function removeLimit(address _payee) external onlyManager { limitsList[_payee] = 0; } } // File: node_modules\zeppelin-solidity\contracts\access\Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ManagedWhitelist.sol /** * @title ManagedWhitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract ManagedWhitelist is Managed, Whitelist { /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) public onlyManager { addRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) public onlyManager { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) public onlyManager { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: contracts\ClinicAllCrowdsale.sol /// @title ClinicAll crowdsale contract /// @dev ClinicAll crowdsale contract contract ClinicAllCrowdsale is Crowdsale, FinalizableCrowdsale, MintedCrowdsale, ManagedWhitelist, Limited { constructor ( uint256 _tokenLimitSupply, uint256 _rate, address _wallet, address _privateSaleWallet, ERC20 _token, uint256 _openingTime, uint256 _closingTime, uint256 _discountTokenAmount, uint256 _discountTokenPercent, uint256 _preSaleClosingTime, uint256 _softCapLimit, ClinicAllRefundEscrow _vault, uint256 _buyLimitSupplyMin, uint256 _buyLimitSupplyMax, uint256 _kycLimitEliminator ) Crowdsale(_rate, _wallet, _token) TimedCrowdsale(_openingTime, _closingTime) public { privateSaleWallet = _privateSaleWallet; tokenSupplyLimit = _tokenLimitSupply; discountTokenAmount = _discountTokenAmount; discountTokenPercent = _discountTokenPercent; preSaleClosingTime = _preSaleClosingTime; softCapLimit = _softCapLimit; vault = _vault; buyLimitSupplyMin = _buyLimitSupplyMin; buyLimitSupplyMax = _buyLimitSupplyMax; kycLimitEliminator = _kycLimitEliminator; } using SafeMath for uint256; // refund vault used to hold funds while crowdsale is running ClinicAllRefundEscrow public vault; /*/ * Properties, constants /*/ //address public walletPrivateSaler; // Limit of tokens for supply during ICO public sale uint256 public tokenSupplyLimit; // Limit of tokens with discount on current contract uint256 public discountTokenAmount; // Percent value for discount tokens uint256 public discountTokenPercent; // Time when we finish pre sale uint256 public preSaleClosingTime; // Minimum amount of funds to be raised in weis uint256 public softCapLimit; // Min buy limit for each investor uint256 public buyLimitSupplyMin; // Max buy limit for each investor uint256 public buyLimitSupplyMax; // KYC Limit Eliminator for small and big investors uint256 public kycLimitEliminator; // Address where private sale funds are collected address public privateSaleWallet; // Private sale tokens supply limit uint256 public privateSaleSupplyLimit; // Public functions /*/ * @dev CrowdSale manager is able to change rate value during ICO * @param _rate wei to CHT tokens exchange rate */ function updateRate(uint256 _rate) public onlyManager { require(_rate != 0, "Exchange rate should not be 0."); rate = _rate; } /*/ * @dev CrowdSale manager is able to change min and max buy limit for investors during ICO * @param _min Minimal amount of tokens that could be bought * @param _max Maximum amount of tokens that could be bought */ function updateBuyLimitRange(uint256 _min, uint256 _max) public onlyOwner { require(_min != 0, "Minimal buy limit should not be 0."); require(_max != 0, "Maximal buy limit should not be 0."); require(_max > _min, "Maximal buy limit should be greater than minimal buy limit."); buyLimitSupplyMin = _min; buyLimitSupplyMax = _max; } /*/ * @dev CrowdSale manager is able to change Kyc Limit Eliminator for investors during ICO * @param _value amount of tokens that should be as eliminator */ function updateKycLimitEliminator(uint256 _value) public onlyOwner { require(_value != 0, "Kyc Eliminator should not be 0."); kycLimitEliminator = _value; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 deposit = vault.depositsOf(msg.sender); vault.withdraw(msg.sender); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(msg.sender); } /** @dev Owner can claim full refund if a crowdsale is unsuccessful @param _txFee Transaction fee that will be deducted from an invested sum */ function claimRefundChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner { require(isFinalized, "Claim refunds is only possible if the ICO is finalized."); require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached."); uint256 _weiRefunded; address[] memory _refundeesList; (_weiRefunded, _refundeesList) = vault.withdrawChunk(_txFee, _chunkLength); weiRaised = weiRaised.sub(_weiRefunded); for (uint256 i = 0; i < _refundeesList.length; i++) { ClinicAllToken(token).burnAfterRefund(_refundeesList[i]); } } /** * @dev Get refundee list length */ function refundeesListLength() public onlyOwner view returns (uint256) { return vault.refundeesListLength(); } /** * @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) { return ((block.timestamp > closingTime) || tokenSupplyLimit <= token.totalSupply()); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return token.totalSupply() >= softCapLimit; } /** * @dev Checks rest of tokens supply. */ function supplyRest() public view returns (uint256) { return (tokenSupplyLimit.sub(token.totalSupply())); } //Private functions function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal doesNotExceedLimit(_beneficiary, _tokenAmount, token.balanceOf(_beneficiary), kycLimitEliminator) { super._processPurchase(_beneficiary, _tokenAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyIfWhitelisted(_beneficiary) isLimited(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); uint256 tokens = _getTokenAmount(_weiAmount); require(tokens.add(token.totalSupply()) <= tokenSupplyLimit, "Total amount fo sold tokens should not exceed the total supply limit."); require(tokens >= buyLimitSupplyMin, "An investor can buy an amount of tokens only above the minimal limit."); require(tokens.add(token.balanceOf(_beneficiary)) <= buyLimitSupplyMax, "An investor cannot buy tokens above the maximal limit."); } /** * @dev Te 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 with discount or not */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (isDiscount()) { return _getTokensWithDiscount(_weiAmount); } return _weiAmount.mul(rate); } /** * @dev Public method where ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens */ function getTokenAmount(uint256 _weiAmount) public view returns (uint256) { return _getTokenAmount(_weiAmount); } /** * @dev iternal method returns total tokens amount including discount */ function _getTokensWithDiscount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokens = 0; uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply()); uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount); if (restOfDiscountTokens < discountTokensMax) { uint256 discountTokens = restOfDiscountTokens; //get rest of WEI uint256 _rate = _getDiscountRate(); uint256 _discointWeiAmount = discountTokens.div(_rate); uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount); uint256 normalTokens = _restOfWeiAmount.mul(rate); tokens = discountTokens.add(normalTokens); } else { tokens = discountTokensMax; } return tokens; } /** * @dev iternal method returns discount tokens amount * @param _weiAmount An amount of ETH that should be converted to an amount of CHT tokens */ function _getDiscountTokenAmount(uint256 _weiAmount) internal view returns (uint256) { require(_weiAmount != 0, "It should be possible to buy tokens only by providing non zero ETH."); uint256 _rate = _getDiscountRate(); return _weiAmount.mul(_rate); } /** * @dev Returns the discount rate value */ function _getDiscountRate() internal view returns (uint256) { require(isDiscount(), "Getting discount rate should be possible only below the discount tokens limit."); return rate.add(rate.mul(discountTokenPercent).div(100)); } /** * @dev Returns the exchange rate value */ function getRate() public view returns (uint256) { if (isDiscount()) { return _getDiscountRate(); } return rate; } /** * @dev Returns the status if the ICO's private sale has closed or not */ function isDiscount() public view returns (bool) { return (preSaleClosingTime >= block.timestamp); } /** * @dev Internal method where owner transfers part of tokens to reserve */ function transferTokensToReserve(address _beneficiary) private { require(tokenSupplyLimit < CappedToken(token).cap(), "Token's supply limit should be less that token' cap limit."); // calculate token amount to be created uint256 _tokenCap = CappedToken(token).cap(); uint256 tokens = _tokenCap.sub(tokenSupplyLimit); _deliverTokens(_beneficiary, tokens); } /** * @dev Enable transfers of tokens between wallets */ function transferOn() public onlyOwner { ClinicAllToken(token).transferOn(); } /** * @dev Disable transfers of tokens between wallets */ function transferOff() public onlyOwner { ClinicAllToken(token).transferOff(); } /** * @dev Internal method where owner transfers part of tokens to reserve and finish minting */ function finalization() internal { if (goalReached()) { transferTokensToReserve(wallet); vault.close(); } else { vault.enableRefunds(); } MintableToken(token).finishMinting(); super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { super._forwardFunds(); vault.depositFunds(msg.sender, msg.value); } /** * @dev Throws if operator is not whitelisted. */ modifier onlyPrivateSaleWallet() { require(privateSaleWallet == msg.sender, "Wallet should be the same as private sale wallet."); _; } /** * @dev Public method where private sale manager can transfer tokens to private investors */ function transferToPrivateInvestor( address _beneficiary, uint256 _value ) public onlyPrivateSaleWallet onlyIfWhitelisted(_beneficiary) returns (bool) { ClinicAllToken(token).transferToPrivateInvestor(msg.sender, _beneficiary, _value); } /** * @dev Public method where private sale manager can transfer the rest of tokens form private sale wallet available to crowdsale */ function redeemPrivateSaleFunds() public onlyPrivateSaleWallet { uint256 _balance = ClinicAllToken(token).balanceOf(msg.sender); privateSaleSupplyLimit = privateSaleSupplyLimit.sub(_balance); ClinicAllToken(token).burnPrivateSale(msg.sender, _balance); } /** * @dev Internal method where private sale manager getting private sale limit amount of tokens * @param privateSaleSupplyAmount value of CHT tokens to add for private sale */ function allocatePrivateSaleFunds(uint256 privateSaleSupplyAmount) public onlyOwner { require(privateSaleSupplyLimit.add(privateSaleSupplyAmount) < tokenSupplyLimit, "Token's private sale supply limit should be less that token supply limit."); privateSaleSupplyLimit = privateSaleSupplyLimit.add(privateSaleSupplyAmount); _deliverTokens(privateSaleWallet, privateSaleSupplyAmount); } /** @dev Owner can withdraw part of funds during of ICO @param _value Transaction amoun that will be deducted from an vault sum */ function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner { vault.beneficiaryWithdrawChunk(_value); } /** @dev Owner can withdraw all funds during or after of ICO */ function beneficiaryWithdrawAll() public onlyOwner { vault.beneficiaryWithdrawAll(); } /** @dev Owner can do manual refund here if investore has "BAD" money @param _payee address of investor that needs to refund with next manual ETH sending */ function manualRefund(address _payee) public onlyOwner { uint256 deposit = vault.depositsOf(_payee); vault.manualRefund(_payee); weiRaised = weiRaised.sub(deposit); ClinicAllToken(token).burnAfterRefund(_payee); } }
* @dev Internal method where owner transfers part of tokens to reserve and finish minting/
function finalization() internal { if (goalReached()) { transferTokensToReserve(wallet); vault.close(); vault.enableRefunds(); } MintableToken(token).finishMinting(); super.finalization(); }
6,432,664
[ 1, 3061, 707, 1625, 3410, 29375, 1087, 434, 2430, 358, 20501, 471, 4076, 312, 474, 310, 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, 727, 1588, 1435, 2713, 288, 203, 565, 309, 261, 27354, 23646, 10756, 288, 203, 1377, 7412, 5157, 774, 607, 6527, 12, 19177, 1769, 203, 1377, 9229, 18, 4412, 5621, 203, 1377, 9229, 18, 7589, 1957, 19156, 5621, 203, 565, 289, 203, 565, 490, 474, 429, 1345, 12, 2316, 2934, 13749, 49, 474, 310, 5621, 203, 565, 2240, 18, 6385, 1588, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-07-08 */ pragma solidity ^0.4.11; /** * @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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) public balances; // *added public mapping (address => mapping (address => uint256)) public allowed; // *added public } contract BQCCToken is StandardToken, Pausable { string public constant name = "BQCC Token"; string public constant symbol = "BQCC"; uint8 public constant decimals = 6; uint256 public constant totalSupply = 1000000000000000; // Holds the amount and date of a given balance lock. struct BalanceLock { uint256 amount; uint256 unlockDate; } // A mapping of balance lock to a given address. mapping (address => BalanceLock) public balanceLocks; // An event to notify that _owner has locked a balance. event BalanceLocked(address indexed _owner, uint256 _oldLockedAmount, uint256 _newLockedAmount, uint256 _expiry); /** @dev Constructor for the contract. */ function BQCCToken() Pausable() { balances[msg.sender] = totalSupply; Transfer(0x0, msg.sender, totalSupply); } /** @dev Sets a token balance to be locked by the sender, on the condition * that the amount is equal or greater than the previous amount, or if the * previous lock time has expired. * @param _value The amount be locked. */ //设置锁仓 function lockBalance(address addr, uint256 _value,uint256 lockingDays) onlyOwner { // Check if the lock on previously locked tokens is still active. if (balanceLocks[addr].unlockDate > now) { // 未到可转账日期 // Only allow confirming the lock or adding to it. require(_value >= balanceLocks[addr].amount); } // Ensure that no more than the balance can be locked. require(balances[addr] >= _value); // convert days to seconds uint256 lockingPeriod = lockingDays*24*3600; // Lock tokens and notify. uint256 _expiry = now + lockingPeriod; BalanceLocked(addr, balanceLocks[addr].amount, _value, _expiry); balanceLocks[addr] = BalanceLock(_value, _expiry); } /** @dev Returns the balance that a given address has available for transfer. * @param _owner The address of the token owner. */ // 返回用户当前可用余额 function availableBalance(address _owner) constant returns(uint256) { if (balanceLocks[_owner].unlockDate < now) { return balances[_owner]; } else { assert(balances[_owner] >= balanceLocks[_owner].amount); return balances[_owner] - balanceLocks[_owner].amount; } } /** @dev Send `_value` token to `_to` from `msg.sender`, on the condition * that there are enough unlocked tokens in the `msg.sender` account. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. * @return Whether the transfer was successful or not. */ // function transfer(address _to, uint256 _value) whenNotPaused returns (bool success) { require(availableBalance(msg.sender) >= _value); return super.transfer(_to, _value); } /** @dev Send `_value` token to `_to` from `_from` on the condition * that there are enough unlocked tokens in the `_from` account. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool success) { require(availableBalance(_from) >= _value); return super.transferFrom(_from, _to, _value); } }
Holds the amount and date of a given balance lock.
contract BQCCToken is StandardToken, Pausable { string public constant name = "BQCC Token"; string public constant symbol = "BQCC"; uint8 public constant decimals = 6; uint256 public constant totalSupply = 1000000000000000; struct BalanceLock { uint256 amount; uint256 unlockDate; } uint256 _newLockedAmount, uint256 _expiry); mapping (address => BalanceLock) public balanceLocks; event BalanceLocked(address indexed _owner, uint256 _oldLockedAmount, function BQCCToken() Pausable() { balances[msg.sender] = totalSupply; Transfer(0x0, msg.sender, totalSupply); } function lockBalance(address addr, uint256 _value,uint256 lockingDays) onlyOwner { require(_value >= balanceLocks[addr].amount); } BalanceLocked(addr, balanceLocks[addr].amount, _value, _expiry); balanceLocks[addr] = BalanceLock(_value, _expiry); require(balances[addr] >= _value); uint256 lockingPeriod = lockingDays*24*3600; uint256 _expiry = now + lockingPeriod; }
2,445,830
[ 1, 20586, 87, 326, 3844, 471, 1509, 434, 279, 864, 11013, 2176, 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, 16351, 605, 53, 39, 1268, 969, 353, 8263, 1345, 16, 21800, 16665, 288, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 38, 53, 6743, 3155, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 38, 53, 6743, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 1666, 31, 203, 565, 2254, 5034, 1071, 5381, 2078, 3088, 1283, 273, 2130, 12648, 11706, 31, 203, 203, 565, 1958, 30918, 2531, 288, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 7186, 1626, 31, 203, 565, 289, 203, 203, 203, 565, 2254, 5034, 389, 2704, 8966, 6275, 16, 2254, 5034, 389, 22409, 1769, 203, 203, 565, 2874, 261, 2867, 516, 30918, 2531, 13, 1071, 11013, 19159, 31, 203, 565, 871, 30918, 8966, 12, 2867, 8808, 389, 8443, 16, 2254, 5034, 389, 1673, 8966, 6275, 16, 203, 565, 445, 605, 53, 39, 1268, 969, 1435, 203, 3639, 21800, 16665, 1435, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 3639, 12279, 12, 20, 92, 20, 16, 1234, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 2176, 13937, 12, 2867, 3091, 16, 2254, 5034, 389, 1132, 16, 11890, 5034, 18887, 9384, 13, 1338, 5541, 288, 203, 203, 5411, 2583, 24899, 1132, 1545, 11013, 19159, 63, 4793, 8009, 8949, 1769, 203, 3639, 289, 203, 3639, 30918, 8966, 12, 4793, 16, 11013, 19159, 63, 4793, 8009, 8949, 16, 389, 1132, 16, 389, 22409, 1769, 203, 3639, 11013, 19159, 63, 4793, 65, 273, 30918, 2531, 24899, 1132, 2 ]
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) { 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't hold 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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 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]); // SafeMath.sub will throw if there is not enough balance. 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 balance) { 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Owned { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; address internal ownerShip; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, address _realOwner ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; ownerShip = _realOwner; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(ownerShip, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } /** * @title TokenVault * @dev TokenVault is a token holder contract that will allow a * beneficiary to spend the tokens from some function of a specified ERC20 token */ contract TokenVault { using SafeERC20 for ERC20; // ERC20 token contract being held ERC20 public token; constructor(ERC20 _token) public { token = _token; } /** * @notice Allow the token itself to send tokens * using transferFrom(). */ function fillUpAllowance() public { uint256 amount = token.balanceOf(this); require(amount > 0); token.approve(token, amount); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { 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 { require(_value > 0); require(_value <= balances[msg.sender]); // 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 address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); } } contract NEWACE_Token is BurnableToken, Owned { string public constant name = "NEWACE TOKEN"; string public constant symbol = "ACE"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated ( 999 million ) uint256 public constant HARD_CAP = 999000000 * 10**uint256(decimals); /// This address will be used to distribute the team, advisors and reserve tokens address public saleTokensAddress; /// This vault is used to keep the Founders, Advisors and Partners tokens TokenVault public reserveTokensVault; /// Date when the vesting for regular users starts uint64 internal daySecond = 86400; uint64 internal lock90Days = 90; uint64 internal unlock100Days = 100; uint64 internal lock365Days = 365; /// Store the vesting contract addresses for each sale contributor mapping(address => address) public vestingOf; constructor(address _saleTokensAddress) public payable { require(_saleTokensAddress != address(0)); saleTokensAddress = _saleTokensAddress; /// Maximum tokens to be sold - 499.5 million uint256 saleTokens = 499500000; createTokensInt(saleTokens, saleTokensAddress); require(totalSupply_ <= HARD_CAP); } /// @dev Create a ReserveTokenVault function createReserveTokensVault() external onlyOwner { require(reserveTokensVault == address(0)); /// Reserve tokens - 499.5 million uint256 reserveTokens = 499500000; reserveTokensVault = createTokenVaultInt(reserveTokens); require(totalSupply_ <= HARD_CAP); } /// @dev Create a TokenVault and fill with the specified newly minted tokens function createTokenVaultInt(uint256 tokens) internal onlyOwner returns (TokenVault) { TokenVault tokenVault = new TokenVault(ERC20(this)); createTokensInt(tokens, tokenVault); tokenVault.fillUpAllowance(); return tokenVault; } // @dev create specified number of tokens and transfer to destination function createTokensInt(uint256 _tokens, address _destination) internal onlyOwner { uint256 tokens = _tokens * 10**uint256(decimals); totalSupply_ = totalSupply_.add(tokens); balances[_destination] = balances[_destination].add(tokens); emit Transfer(0x0, _destination, tokens); require(totalSupply_ <= HARD_CAP); } /// @dev vest Detail : second unit function vestTokensDetailInt( address _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt) external onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); } /// @dev vest StartAt : day unit function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); uint256 afterSec = _afterDay * daySecond; uint256 cliffSec = _cliffDay * daySecond; uint256 durationSec = _durationDay * daySecond; if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); } /// @dev vest function from now function vestTokensFromNowInt(address _beneficiary, uint256 _tokensAmountInt, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { vestTokensStartAtInt(_beneficiary, _tokensAmountInt, now, _afterDay, _cliffDay, _durationDay); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release function vestCmdNow1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, 0, unlock100Days); } /// @dev vest the sale contributor tokens for 100 days, 1% gradual release after 3 month later, no cliff function vestCmd3Month1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, lock90Days, 0, unlock100Days); } /// @dev vest the sale contributor tokens 100% release after 1 year function vestCmd1YearInstantInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner { vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, lock365Days, lock365Days); } /// @dev releases vested tokens for the caller's own address function releaseVestedTokens() external { releaseVestedTokensFor(msg.sender); } /// @dev releases vested tokens for the specified address. /// Can be called by anyone for any address. function releaseVestedTokensFor(address _owner) public { TokenVesting(vestingOf[_owner]).release(this); } /// @dev check the vested balance for an address function lockedBalanceOf(address _owner) public view returns (uint256) { return balances[vestingOf[_owner]]; } /// @dev check the locked but releaseable balance of an owner function releaseableBalanceOf(address _owner) public view returns (uint256) { if (vestingOf[_owner] == address(0) ) { return 0; } else { return TokenVesting(vestingOf[_owner]).releasableAmount(this); } } /// @dev revoke vested tokens for the specified address. /// Tokens already vested remain in the contract, the rest are returned to the owner. function revokeVestedTokensFor(address _owner) public onlyOwner { TokenVesting(vestingOf[_owner]).revoke(this); } /// @dev Create a ReserveTokenVault function makeReserveToVault() external onlyOwner { require(reserveTokensVault != address(0)); reserveTokensVault.fillUpAllowance(); } }
@dev releases vested tokens for the specified address. Can be called by anyone for any address.
function releaseVestedTokensFor(address _owner) public { TokenVesting(vestingOf[_owner]).release(this); }
618,588
[ 1, 28416, 331, 3149, 2430, 364, 326, 1269, 1758, 18, 4480, 506, 2566, 635, 1281, 476, 364, 1281, 1758, 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 ]
[ 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, 3992, 58, 3149, 5157, 1290, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 3155, 58, 10100, 12, 90, 10100, 951, 63, 67, 8443, 65, 2934, 9340, 12, 2211, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xA8ba1C2d4C1181F9a7C757fca04A446A346eEaBA/sources/DSpaceMarketplace.sol
"tm2" - Dv - REAL
payTos[2] = payTo(2, 0xF2571398b10a5b4bE1598A7927EA486151d02277, false, false, address(0));
876,591
[ 1, 6, 16925, 22, 6, 300, 463, 90, 300, 2438, 1013, 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, 3639, 8843, 56, 538, 63, 22, 65, 273, 8843, 774, 12, 22, 16, 374, 16275, 2947, 27, 3437, 10689, 70, 2163, 69, 25, 70, 24, 70, 41, 3600, 10689, 37, 7235, 5324, 41, 37, 24, 5292, 25807, 72, 3103, 22, 4700, 16, 629, 16, 629, 16, 1758, 12, 20, 10019, 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 ]
./full_match/56/0x42B1bbC3E386D3e66369a720Ff6B589C32308D73/sources/BEPOwnable.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. 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 BEPOwnable is BEPContext { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); pragma solidity ^0.8.0; constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
3,244,590
[ 1, 8924, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 9722, 2419, 91, 6914, 353, 9722, 52, 1042, 288, 203, 225, 1758, 3238, 389, 8443, 31, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 225, 3885, 1435, 288, 203, 565, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 565, 389, 8443, 273, 1234, 12021, 31, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 225, 289, 203, 203, 225, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 565, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 565, 389, 8443, 273, 1758, 12, 20, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 13866, 5460, 12565, 12, 2867, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // OZ contracts v4 import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // OZ contracts v4 contract INFLStake is AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; // bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); event Stake(address indexed wallet, uint256 amount, uint256 date); event Withdraw(address indexed wallet, uint256 amount, uint256 date); event Claimed(address indexed wallet, address indexed rewardToken, uint256 amount); event RewardTokenChanged(address indexed oldRewardToken, uint256 returnedAmount, address indexed newRewardToken); event LockTimePeriodChanged(uint48 lockTimePeriod); event StakeRewardFactorChanged(uint256 stakeRewardFactor); event StakeRewardEndTimeChanged(uint48 stakeRewardEndTime); event RewardsBurned(address indexed staker, uint256 amount); event ERC20TokensRemoved(address indexed tokenAddress, address indexed receiver, uint256 amount); uint48 public constant MAX_TIME = type(uint48).max; // = 2^48 - 1 struct User { uint48 stakeTime; uint48 unlockTime; uint160 stakeAmount; uint256 accumulatedRewards; } mapping(address => User) public userMap; uint256 public tokenTotalStaked; // sum of all staked tokens address public immutable stakingToken; // address of token which can be staked into this contract address public rewardToken; // address of reward token /** * Using block.timestamp instead of block.number for reward calculation * 1) Easier to handle for users * 2) Should result in same rewards across different chain with different block times * 3) "The current block timestamp must be strictly larger than the timestamp of the last block, ... * but the only guarantee is that it will be somewhere between the timestamps ... * of two consecutive blocks in the canonical chain." * https://docs.soliditylang.org/en/v0.7.6/cheatsheet.html?highlight=block.timestamp#global-variables */ uint48 public lockTimePeriod; // time in seconds a user has to wait after calling unlock until staked token can be withdrawn uint48 public stakeRewardEndTime; // unix time in seconds when the reward scheme will end uint256 public stakeRewardFactor; // time in seconds * amount of staked token to receive 1 reward token constructor(address _stakingToken, uint48 _lockTimePeriod) { require(_stakingToken != address(0), "stakingToken.address == 0"); require(_lockTimePeriod < 366 days, "lockTimePeriod >= 366 days"); stakingToken = _stakingToken; lockTimePeriod = _lockTimePeriod; // set some defaults stakeRewardFactor = 1000 * 1 days; // default : a user has to stake 1000 token for 1 day to receive 1 reward token stakeRewardEndTime = uint48(block.timestamp + 366 days); // default : reward scheme ends in 1 year _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * based on OpenZeppelin SafeCast v4.3 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/math/SafeCast.sol */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "value doesn't fit in 48 bits"); return uint48(value); } function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "value doesn't fit in 160 bits"); return uint160(value); } /** * External API functions */ function stakeTime(address _staker) external view returns (uint48 dateTime) { return userMap[_staker].stakeTime; } function stakeAmount(address _staker) external view returns (uint256 balance) { return userMap[_staker].stakeAmount; } // redundant with stakeAmount() for compatibility function balanceOf(address _staker) external view returns (uint256 balance) { return userMap[_staker].stakeAmount; } function userAccumulatedRewards(address _staker) external view returns (uint256 rewards) { return userMap[_staker].accumulatedRewards; } /** * @dev return unix epoch time when staked tokens will be unlocked * @dev return MAX_INT_UINT48 = 2**48-1 if user has no token staked * @dev this always allows an easy check with : require(block.timestamp > getUnlockTime(account)); * @return unlockTime unix epoch time in seconds */ function getUnlockTime(address _staker) public view returns (uint48 unlockTime) { return userMap[_staker].stakeAmount > 0 ? userMap[_staker].unlockTime : MAX_TIME; } /** * @return balance of reward tokens held by this contract */ function getRewardTokenBalance() public view returns (uint256 balance) { if (rewardToken == address(0)) return 0; balance = IERC20(rewardToken).balanceOf(address(this)); if (stakingToken == rewardToken) { balance -= tokenTotalStaked; } } // onlyOwner / DEFAULT_ADMIN_ROLE functions -------------------------------------------------- /** * @notice setting rewardToken to address(0) disables claim/mint * @notice if there was a reward token set before, return remaining tokens to msg.sender/admin * @param newRewardToken address */ function setRewardToken(address newRewardToken) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { address oldRewardToken = rewardToken; uint256 rewardBalance = getRewardTokenBalance(); // balance of oldRewardToken if (rewardBalance > 0) { IERC20(oldRewardToken).safeTransfer(msg.sender, rewardBalance); } rewardToken = newRewardToken; emit RewardTokenChanged(oldRewardToken, rewardBalance, newRewardToken); } /** * @notice set time a user has to wait after calling unlock until staked token can be withdrawn * @param _lockTimePeriod time in seconds */ function setLockTimePeriod(uint48 _lockTimePeriod) external onlyRole(DEFAULT_ADMIN_ROLE) { lockTimePeriod = _lockTimePeriod; emit LockTimePeriodChanged(_lockTimePeriod); } /** * @notice see calculateUserClaimableReward() docs * @dev requires that reward token has the same decimals as stake token * @param _stakeRewardFactor time in seconds * amount of staked token to receive 1 reward token */ function setStakeRewardFactor(uint256 _stakeRewardFactor) external onlyRole(DEFAULT_ADMIN_ROLE) { stakeRewardFactor = _stakeRewardFactor; emit StakeRewardFactorChanged(_stakeRewardFactor); } /** * @notice set block time when stake reward scheme will end * @param _stakeRewardEndTime unix time in seconds */ function setStakeRewardEndTime(uint48 _stakeRewardEndTime) external onlyRole(DEFAULT_ADMIN_ROLE) { require(stakeRewardEndTime > block.timestamp, "time has to be in the future"); stakeRewardEndTime = _stakeRewardEndTime; emit StakeRewardEndTimeChanged(_stakeRewardEndTime); } /** * ADMIN_ROLE has to set BURNER_ROLE * allows an external (lottery token sale) contract to substract rewards */ function burnRewards(address _staker, uint256 _amount) external onlyRole(BURNER_ROLE) { User storage user = _updateRewards(_staker); if (_amount < user.accumulatedRewards) { user.accumulatedRewards -= _amount; // safe } else { user.accumulatedRewards = 0; // burn at least all what's there } emit RewardsBurned(_staker, _amount); } /** msg.sender external view convenience functions *********************************/ function stakeAmount_msgSender() public view returns (uint256) { return userMap[msg.sender].stakeAmount; } function stakeTime_msgSender() external view returns (uint48) { return userMap[msg.sender].stakeTime; } function getUnlockTime_msgSender() external view returns (uint48 unlockTime) { return getUnlockTime(msg.sender); } function userClaimableRewards_msgSender() external view returns (uint256) { return userClaimableRewards(msg.sender); } function userAccumulatedRewards_msgSender() external view returns (uint256) { return userMap[msg.sender].accumulatedRewards; } function userTotalRewards_msgSender() external view returns (uint256) { return userTotalRewards(msg.sender); } function getEarnedRewardTokens_msgSender() external view returns (uint256) { return getEarnedRewardTokens(msg.sender); } /** public external view functions (also used internally) **************************/ /** * calculates unclaimed rewards * unclaimed rewards = expired time since last stake/unstake transaction * current staked amount * * We have to cover 6 cases here : * 1) block time < stake time < end time : should never happen => error * 2) block time < end time < stake time : should never happen => error * 3) end time < block time < stake time : should never happen => error * 4) end time < stake time < block time : staked after reward period is over => no rewards * 5) stake time < block time < end time : end time in the future * 6) stake time < end time < block time : end time in the past & staked before * @param _staker address * @return claimableRewards = timePeriod * stakeAmount */ function userClaimableRewards(address _staker) public view returns (uint256) { User storage user = userMap[_staker]; // case 1) 2) 3) // stake time in the future - should never happen - actually an (internal ?) error if (block.timestamp <= user.stakeTime) return 0; // case 4) // staked after reward period is over => no rewards // end time < stake time < block time if (stakeRewardEndTime <= user.stakeTime) return 0; uint256 timePeriod; // case 5 // we have not reached the end of the reward period // stake time < block time < end time if (block.timestamp <= stakeRewardEndTime) { timePeriod = block.timestamp - user.stakeTime; // covered by case 1) 2) 3) 'if' } else { // case 6 // user staked before end of reward period , but that is in the past now // stake time < end time < block time timePeriod = stakeRewardEndTime - user.stakeTime; // covered case 4) } return timePeriod * user.stakeAmount; } function userTotalRewards(address _staker) public view returns (uint256) { return userClaimableRewards(_staker) + userMap[_staker].accumulatedRewards; } function getEarnedRewardTokens(address _staker) public view returns (uint256 claimableRewardTokens) { if (address(rewardToken) == address(0) || stakeRewardFactor == 0) { return 0; } else { return userTotalRewards(_staker) / stakeRewardFactor; // safe } } /** * @dev whenver the staked balance changes do ... * * @dev calculate userClaimableRewards = previous staked amount * (current time - last stake time) * @dev add userClaimableRewards to userAccumulatedRewards * @dev reset userClaimableRewards to 0 by setting stakeTime to current time * @dev not used as doing it inline, local, within a function consumes less gas * * @return user reference pointer for further processing */ function _updateRewards(address _staker) internal returns (User storage user) { // calculate reward credits using previous staking amount and previous time period // add new reward credits to already accumulated reward credits user = userMap[_staker]; user.accumulatedRewards += userClaimableRewards(_staker); // update stake Time to current time (start new reward period) // will also reset userClaimableRewards() user.stakeTime = toUint48(block.timestamp); } /** * add stake token to staking pool * @dev requires the token to be approved for transfer * @dev we assume that (our) stake token is not malicious, so no special checks * @param _amount of token to be staked */ function _stake(uint256 _amount) internal returns (uint256) { require(_amount > 0, "stake amount must be > 0"); require(IERC20(stakingToken).balanceOf(msg.sender) > _amount, " you do not possess enough tokens to stake"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user user.stakeAmount = toUint160(user.stakeAmount + _amount); tokenTotalStaked += _amount; user.unlockTime = toUint48(block.timestamp + lockTimePeriod); // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount, toUint48(block.timestamp)); // = user.stakeTime return _amount; } /** * withdraw staked token, ... * do not withdraw rewards token (it might not be worth the gas) * @return amount of tokens sent to user's account */ function _withdraw(uint256 amount) internal returns (uint256) { require(amount > 0, "amount to withdraw not > 0"); require(block.timestamp > getUnlockTime(msg.sender), "staked tokens are still locked"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user require(amount <= user.stakeAmount, "withdraw amount > staked amount"); user.stakeAmount -= toUint160(amount); tokenTotalStaked -= amount; // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount, toUint48(block.timestamp)); // = user.stakeTime return amount; } /** * claim reward tokens for accumulated reward credits * ... but do not unstake staked token */ function _claim() internal returns (uint256) { require(rewardToken != address(0), "no reward token contract"); uint256 earnedRewardTokens = getEarnedRewardTokens(msg.sender); require(earnedRewardTokens > 0, "no tokens to claim"); // like _updateRewards() , but reset all rewards to 0 User storage user = userMap[msg.sender]; user.accumulatedRewards = 0; user.stakeTime = toUint48(block.timestamp); // will reset userClaimableRewards to 0 // user.stakeAmount = unchanged require(earnedRewardTokens <= getRewardTokenBalance(), "not enough reward tokens"); // redundant but dedicated error message IERC20(rewardToken).safeTransfer(msg.sender, earnedRewardTokens); emit Claimed(msg.sender, rewardToken, earnedRewardTokens); return earnedRewardTokens; } function stake(uint256 _amount) external nonReentrant returns (uint256) { return _stake(_amount); } function claim() external nonReentrant returns (uint256) { return _claim(); } function withdraw(uint256 amount) external nonReentrant returns (uint256) { return _withdraw(amount); } function withdrawAll() external nonReentrant returns (uint256) { return _withdraw(stakeAmount_msgSender()); } /** * Do not accept accidently sent ETH : * If neither a receive Ether nor a payable fallback function is present, * the contract cannot receive Ether through regular transactions and throws an exception. * https://docs.soliditylang.org/en/v0.8.7/contracts.html#receive-ether-function */ /** * @notice withdraw accidently sent ERC20 tokens * @param _tokenAddress address of token to withdraw */ function removeOtherERC20Tokens(address _tokenAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_tokenAddress != address(stakingToken), "can not withdraw staking token"); uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).safeTransfer(msg.sender, balance); emit ERC20TokensRemoved(_tokenAddress, msg.sender, balance); } }
* add stake token to staking pool @dev requires the token to be approved for transfer @dev we assume that (our) stake token is not malicious, so no special checks @param _amount of token to be staked/ using SafeERC20 for IERC20 => will revert in case of error
function _stake(uint256 _amount) internal returns (uint256) { require(_amount > 0, "stake amount must be > 0"); require(IERC20(stakingToken).balanceOf(msg.sender) > _amount, " you do not possess enough tokens to stake"); user.stakeAmount = toUint160(user.stakeAmount + _amount); tokenTotalStaked += _amount; user.unlockTime = toUint48(block.timestamp + lockTimePeriod); IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount); return _amount; }
14,041,696
[ 1, 1289, 384, 911, 1147, 358, 384, 6159, 2845, 225, 4991, 326, 1147, 358, 506, 20412, 364, 7412, 225, 732, 6750, 716, 261, 477, 13, 384, 911, 1147, 353, 486, 27431, 28728, 16, 1427, 1158, 4582, 4271, 225, 389, 8949, 434, 1147, 358, 506, 384, 9477, 19, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 516, 903, 15226, 316, 648, 434, 555, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 334, 911, 12, 11890, 5034, 389, 8949, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 334, 911, 3844, 1297, 506, 405, 374, 8863, 203, 3639, 203, 540, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 334, 6159, 1345, 2934, 12296, 951, 12, 3576, 18, 15330, 13, 405, 389, 8949, 16, 315, 1846, 741, 486, 949, 23828, 7304, 2430, 358, 384, 911, 8863, 203, 3639, 203, 203, 3639, 729, 18, 334, 911, 6275, 273, 358, 5487, 16874, 12, 1355, 18, 334, 911, 6275, 397, 389, 8949, 1769, 203, 3639, 1147, 5269, 510, 9477, 1011, 389, 8949, 31, 203, 203, 3639, 729, 18, 26226, 950, 273, 358, 5487, 8875, 12, 2629, 18, 5508, 397, 2176, 26540, 1769, 203, 203, 3639, 467, 654, 39, 3462, 12, 334, 6159, 1345, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 203, 3639, 327, 389, 8949, 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 ]
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.10; import "ds-test/test.sol"; import "./Vm.sol"; import "../ChainClaim.sol"; contract ExampleImplementation is ChainClaim { // Deployer will be set as issuer of claim codes constructor(address issuerAddr, string memory name) payable ChainClaim(issuerAddr, name) {} function _isValidIssuerSig( address issuedAddress, uint8 v, bytes32 r, bytes32 s ) external view returns (bool) { return isValidIssuerSig(issuedAddress, v, r, s); } function _isValidClaimantSig( address issuedAddress, address destinationAddress, uint8 v, bytes32 r, bytes32 s ) external view returns (bool) { return isValidClaimantSig(issuedAddress, destinationAddress, v, r, s); } function _genDataHash(address chainedAddress) external view returns (bytes32) { return genDataHash(chainedAddress); } function takeBalance( address issuedAddress, uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s ) external { bool validClaim = claim(issuedAddress, msg.sender, v, r, s); require(validClaim, "Invalid claim"); payable(msg.sender).transfer(address(this).balance); } } contract ChainClaimTestSetup { Vm vm = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); string name = "some name"; // predetermined address for pregenerated test claim code signing address exAddress = 0xb07dAd0000000000000000000000000000000001; ExampleImplementation target = ExampleImplementation(exAddress); address issuerAddress = 0x0f6A79A579658E401E0B81c6dde1F2cd51d97176; uint256 issuerPkey = 0xad54bdeade5537fb0a553190159783e45d02d316a992db05cbed606d3ca36b39; address claimCodeAddress = 0xB2DDDD291289EfF4715F6e84CdB3D845a93037A6; uint256 claimCodePkey = 0x55b7b79aa0a71a634d00343ecb270adc0105d11566c7fcafa9381272d8d26554; uint8 claimCodeV; bytes32 claimCodeR; bytes32 claimCodeS; function setUp() public { ExampleImplementation deployedEx = new ExampleImplementation( issuerAddress, name ); vm.etch(exAddress, address(deployedEx).code); (claimCodeV, claimCodeR, claimCodeS) = vm.sign( issuerPkey, target._genDataHash(claimCodeAddress) ); } } contract ChainClaimTest is ChainClaimTestSetup, DSTest { receive() external payable {} function testIsValidIssuerSig() public { bool valid = target._isValidIssuerSig( claimCodeAddress, claimCodeV, claimCodeR, claimCodeS ); assertTrue(valid); } function testIsInvalidIssuerSig() public { bool valid; valid = target._isValidIssuerSig( claimCodeAddress, claimCodeV, claimCodeR, bytes32(uint256(claimCodeS) + 1) ); assertTrue(!valid); valid = target._isValidIssuerSig( claimCodeAddress, claimCodeV, bytes32(uint256(claimCodeR) + 1), claimCodeS ); assertTrue(!valid); valid = target._isValidIssuerSig( claimCodeAddress, claimCodeV + 1, claimCodeR, claimCodeS ); assertTrue(!valid); valid = target._isValidIssuerSig( address(0), claimCodeV, claimCodeR, claimCodeS ); assertTrue(!valid); } function testIsValidClaimantSig() public { address someAddress = 0xB07DAd0000000000000000000000000000000002; bytes32 hash = target._genDataHash(someAddress); (uint8 v, bytes32 r, bytes32 s) = vm.sign(claimCodePkey, hash); bool valid = target._isValidClaimantSig( claimCodeAddress, someAddress, v, r, s ); assertTrue(valid); } function testIsInvalidClaimantSig() public { address someAddress = 0xB07DAd0000000000000000000000000000000002; bytes32 hash = target._genDataHash(someAddress); (uint8 v, bytes32 r, bytes32 s) = vm.sign(claimCodePkey, hash); bool valid; valid = target._isValidClaimantSig( claimCodeAddress, someAddress, v, r, bytes32(uint256(s) + 1) ); assertTrue(!valid); vm.expectRevert("ECDSA: invalid signature"); valid = target._isValidClaimantSig( claimCodeAddress, someAddress, v, bytes32(uint256(r) + 2), s ); assertTrue(!valid); vm.expectRevert("ECDSA: invalid signature 'v' value"); valid = target._isValidClaimantSig( claimCodeAddress, someAddress, v - 1, r, s ); assertTrue(!valid); valid = target._isValidClaimantSig(address(0), someAddress, v, r, s); assertTrue(!valid); valid = target._isValidClaimantSig(claimCodeAddress, address(0), v, r, s); assertTrue(!valid); } function testClaim() public { vm.deal(address(target), 1 ether); vm.deal(address(this), 0); bytes32 hash = target._genDataHash(address(this)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(claimCodePkey, hash); vm.expectRevert( abi.encodePacked(bytes4(keccak256("ErrorInvalidIssuerSignature()"))) ); target.takeBalance( address(0), [claimCodeV, v], [claimCodeR, r], [claimCodeS, s] ); vm.expectRevert( abi.encodePacked(bytes4(keccak256("ErrorInvalidIssuerSignature()"))) ); target.takeBalance( claimCodeAddress, [claimCodeV, v], [claimCodeR, r], [bytes32(uint256(claimCodeS) + 1), s] ); vm.expectRevert( abi.encodePacked(bytes4(keccak256("ErrorInvalidClaimantSignature()"))) ); target.takeBalance( claimCodeAddress, [claimCodeV, v], [claimCodeR, r], [claimCodeS, bytes32(uint256(s) + 1)] ); target.takeBalance( claimCodeAddress, [claimCodeV, v], [claimCodeR, r], [claimCodeS, s] ); assertEq(address(target).balance, 0, "target balance not 0"); assertEq(address(this).balance, 1 ether, "this balance not 1 ether"); vm.expectRevert(abi.encodePacked(bytes4(keccak256("ErrorUsedClaim()")))); target.takeBalance( claimCodeAddress, [claimCodeV, v], [claimCodeR, r], [claimCodeS, s] ); } }
predetermined address for pregenerated test claim code signing
contract ChainClaimTestSetup { Vm vm = Vm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); string name = "some name"; address exAddress = 0xb07dAd0000000000000000000000000000000001; ExampleImplementation target = ExampleImplementation(exAddress); address issuerAddress = 0x0f6A79A579658E401E0B81c6dde1F2cd51d97176; uint256 issuerPkey = 0xad54bdeade5537fb0a553190159783e45d02d316a992db05cbed606d3ca36b39; address claimCodeAddress = 0xB2DDDD291289EfF4715F6e84CdB3D845a93037A6; uint256 claimCodePkey = 0x55b7b79aa0a71a634d00343ecb270adc0105d11566c7fcafa9381272d8d26554; uint8 claimCodeV; bytes32 claimCodeR; bytes32 claimCodeS; function setUp() public { ExampleImplementation deployedEx = new ExampleImplementation( issuerAddress, name ); vm.etch(exAddress, address(deployedEx).code); (claimCodeV, claimCodeR, claimCodeS) = vm.sign( issuerPkey, target._genDataHash(claimCodeAddress) ); } }
12,729,233
[ 1, 6510, 4443, 329, 1758, 364, 2299, 7489, 1842, 7516, 981, 10611, 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, 7824, 9762, 4709, 7365, 288, 203, 225, 776, 81, 4268, 273, 776, 81, 12, 20, 92, 27, 2163, 10580, 5908, 7228, 507, 12416, 69, 3672, 26, 5558, 74, 42, 5520, 6675, 40, 9470, 74, 9599, 42, 25, 70, 21, 5698, 2138, 40, 1769, 203, 225, 533, 508, 273, 315, 19068, 508, 14432, 203, 225, 1758, 431, 1887, 273, 374, 6114, 8642, 72, 1871, 12648, 12648, 12648, 12648, 1611, 31, 203, 225, 5090, 13621, 1018, 273, 5090, 13621, 12, 338, 1887, 1769, 203, 203, 225, 1758, 9715, 1887, 273, 374, 92, 20, 74, 26, 37, 7235, 37, 25, 7235, 26, 8204, 41, 27002, 41, 20, 38, 11861, 71, 26, 72, 323, 21, 42, 22, 4315, 10593, 72, 10580, 28493, 31, 203, 225, 2254, 5034, 9715, 52, 856, 273, 203, 565, 374, 92, 361, 6564, 70, 323, 2486, 2539, 6418, 19192, 20, 69, 2539, 23, 3657, 1611, 6162, 8285, 23, 73, 7950, 72, 3103, 72, 23, 2313, 69, 2733, 22, 1966, 6260, 71, 2992, 4848, 26, 72, 23, 5353, 5718, 70, 5520, 31, 203, 203, 225, 1758, 7516, 1085, 1887, 273, 374, 20029, 22, 5698, 5698, 5540, 2138, 6675, 41, 74, 42, 9462, 3600, 42, 26, 73, 5193, 19728, 38, 23, 40, 5193, 25, 69, 11180, 4630, 27, 37, 26, 31, 203, 225, 2254, 5034, 7516, 1085, 52, 856, 273, 203, 565, 374, 92, 2539, 70, 27, 70, 7235, 7598, 20, 69, 11212, 69, 4449, 24, 72, 713, 5026, 23, 557, 70, 5324, 20, 361, 71, 1611, 6260, 72, 2499, 4313, 26, 71, 27, 74, 2 ]
./full_match/11155111/0x2c062707892eb463B22B4FFb3beB1cD69626eae2/sources/src/layercake/LayerCakeBandwidthManager.sol
Require that the added bandwidth is divisible by BANDWIDTH_DEPOSIT_DENOMINATOR without a remainder
require(_bandwidthAmount % bandwidthDepositDenominator == 0, "AB2");
3,812,488
[ 1, 8115, 716, 326, 3096, 20508, 353, 3739, 18932, 635, 605, 4307, 10023, 67, 1639, 28284, 67, 13296, 1872, 706, 3575, 2887, 279, 10022, 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, 3639, 2583, 24899, 29750, 6275, 738, 20508, 758, 1724, 8517, 26721, 422, 374, 16, 315, 2090, 22, 8863, 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/1/0x8CD834258d000166769733Dfb5fB6fD6E43dB4e7/sources/contracts/KH87/PixelPioneerBase.sol
* @notice Total number of tokens that currently exist./
function totalTokensExist() external view override returns (uint256) { return _totalSupply(); }
4,861,742
[ 1, 5269, 1300, 434, 2430, 716, 4551, 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, 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, 2078, 5157, 4786, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 5621, 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, -100 ]
pragma solidity ^0.4.15; import 'zeppelin-solidity/contracts/token/MintableToken.sol'; /// @title The token for the Home Ethereum's acommodation platform. The totalSupply /// of tokens gets incremented when tokens are bought /// @author Merunas Grincalaitis contract HomeToken is MintableToken { // Name of the token string public name; // Symbol of the token string public symbol; // The amount of decimals for that token uint8 public decimals; /// @notice Constructor to generate the HomeToken. The `totalSupply` of tokens /// gets incremented whenever someone buys tokens on the crowdsale /// @param _name The name of the token /// @param _symbol The symbol of the token /// @param _decimals The decimals of the token /// @param initialSupply The initial amount of tokens created that will go to /// the creator of the token and will be the `totalSupply` because it's a `MintableToken` function HomeToken(string _name, string _symbol, uint8 _decimals, uint initialSupply) { require(bytes(_name).length > 0); require(bytes(_symbol).length > 0); require(_decimals > 0); require(initialSupply > 0); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = initialSupply; // The creator of the token gets the initial supply balances[msg.sender] = initialSupply; } }
@title The token for the Home Ethereum's acommodation platform. The totalSupply of tokens gets incremented when tokens are bought @author Merunas Grincalaitis Name of the token Symbol of the token The amount of decimals for that token
contract HomeToken is MintableToken { string public name; string public symbol; uint8 public decimals; function HomeToken(string _name, string _symbol, uint8 _decimals, uint initialSupply) { require(bytes(_name).length > 0); require(bytes(_symbol).length > 0); require(_decimals > 0); require(initialSupply > 0); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = initialSupply; balances[msg.sender] = initialSupply; } }
7,231,739
[ 1, 1986, 1147, 364, 326, 21321, 512, 18664, 379, 1807, 279, 832, 1711, 367, 4072, 18, 1021, 2078, 3088, 1283, 434, 2430, 5571, 28859, 1347, 2430, 854, 800, 9540, 225, 14940, 318, 345, 611, 86, 267, 771, 1540, 291, 1770, 434, 326, 1147, 8565, 434, 326, 1147, 1021, 3844, 434, 15105, 364, 716, 1147, 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, 21321, 1345, 353, 490, 474, 429, 1345, 288, 203, 203, 282, 533, 1071, 508, 31, 203, 203, 282, 533, 1071, 3273, 31, 203, 203, 282, 2254, 28, 1071, 15105, 31, 203, 203, 282, 445, 21321, 1345, 12, 1080, 389, 529, 16, 533, 389, 7175, 16, 2254, 28, 389, 31734, 16, 2254, 2172, 3088, 1283, 13, 288, 203, 1377, 2583, 12, 3890, 24899, 529, 2934, 2469, 405, 374, 1769, 203, 1377, 2583, 12, 3890, 24899, 7175, 2934, 2469, 405, 374, 1769, 203, 1377, 2583, 24899, 31734, 405, 374, 1769, 203, 1377, 2583, 12, 6769, 3088, 1283, 405, 374, 1769, 203, 203, 1377, 508, 273, 389, 529, 31, 203, 1377, 3273, 273, 389, 7175, 31, 203, 1377, 15105, 273, 389, 31734, 31, 203, 1377, 2078, 3088, 1283, 273, 2172, 3088, 1283, 31, 203, 203, 1377, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2172, 3088, 1283, 31, 203, 282, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-12-22 */ //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.10; contract RTTv2AutoSwap { IPancakeRouter02 router; constructor () { router = IPancakeRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //uniswapv2 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D } receive() external payable { buyTokens(msg.value, msg.sender); } function getBuyPath() internal pure returns (address[] memory) { address[] memory path = new address[](2); //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 weth path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c wbnb path[1] = 0xbaFCe797ea7F84a84F39870799883Ad066d3feb7; //0xF41082C4CB71FB4628a9b17214B2624e0e2048a9 RTTv2 Bep20 return path; //0xbafce797ea7f84a84f39870799883ad066d3feb7 RTTv2 erc20 } function buyTokens(uint amt, address to) internal { router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amt}( 0, getBuyPath(), to, block.timestamp ); } } pragma solidity >=0.6.2; interface IPancakeRouter01 { 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); } // File: contracts\interfaces\IPancakeRouter02.sol pragma solidity >=0.6.2; interface IPancakeRouter02 is IPancakeRouter01 { 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; }
0xbafce797ea7f84a84f39870799883ad066d3feb7 RTTv2 erc20
return path;
8,050,542
[ 1, 20, 6114, 1727, 311, 7235, 27, 24852, 27, 74, 5193, 69, 5193, 74, 5520, 28, 7301, 27, 2733, 5482, 23, 361, 20, 6028, 72, 23, 3030, 70, 27, 225, 534, 1470, 90, 22, 6445, 71, 3462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 327, 589, 31, 4766, 6647, 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, -100 ]
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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 pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract ERC20Basic { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 { uint256 public totalSupply; bool public transfersEnabled; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping (address => uint256) balances; /** * Protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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 onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // 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; } /** * @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 constant returns (uint256 balance) { return balances[_owner]; } } 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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @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; 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) public 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) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } 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; address public ownerTwo; event OwnerChanged(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner || msg.sender == ownerTwo); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function changeOwnerTwo(address _newOwner) onlyOwner public { require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); ownerTwo = _newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { string public constant name = "FOOOZ"; string public constant symbol = "FOOOZ"; uint8 public constant decimals = 18; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished; modifier canMint() { require(!mintingFinished); _; } /** * @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, address _owner) canMint internal returns (bool) { balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Mint(_to, _amount); Transfer(_owner, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint internal returns (bool) { mintingFinished = true; MintFinished(); return true; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(this.balance); return; } MintableToken token = MintableToken(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); Transfer(_token, owner, balance); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable { using SafeMath for uint256; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; uint256 public tokenAllocated; uint256 public hardWeiCap = 119000 * (10 ** 18); function Crowdsale( address _wallet ) public { require(_wallet != address(0)); wallet = _wallet; } } contract FooozCrowdsale is Ownable, Crowdsale, MintableToken { using SafeMath for uint256; enum State {Active, Closed} State public state; mapping (address => uint256) public deposited; uint256 public constant INITIAL_SUPPLY = 613333328 * (10 ** uint256(decimals)); uint256 public fundForSale = 466133330 * (10 ** uint256(decimals)); address public addressFundDevelopers = 0x326B7740e5E806fc731200A3ea92f588a86568A3; address public addressFundBounty = 0xE585b723bDc6324dD55cf614fa83f61A88D5b3D8; address public addressFundBonus = 0x1f318fE745bEE511a72A8AB2b704a5F285587335; address public addressFundInvestment = 0x80A0BE0Ab330E48dE8E37277b838b9eB0Bb3bb6f; address public addressFundAdministration = 0xFe3905B9Bd7C0c4164873180dfE0ee85FbFe9F19; uint256[] public discount = [50, 25, 20, 15, 10, 5]; uint256 public weiMinSalePreIco = 1190 * 10 ** 15; uint256 public weiMinSaleIco = 29 * 10 ** 15; uint256 priceToken = 3362; // $0.25 = 1 token => $1,000 = 1.19 ETH => //4,000 token = 1.19 ETH => 1 ETH = 4,000/1.19 = 3362 token uint256 public countInvestor; uint256 public currentAfterIcoPeriod; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event HardCapReached(); event Finalized(); function FooozCrowdsale (address _owner, address _ownerTwo) public Crowdsale(_owner) { require(_owner != address(0)); require(_ownerTwo != address(0)); owner = _owner; ownerTwo = _ownerTwo; //owner = msg.sender; //for test's transfersEnabled = true; mintingFinished = false; state = State.Active; totalSupply = INITIAL_SUPPLY; mintForOwner(owner); } modifier inState(State _state) { require(state == _state); _; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function setPriceToken(uint256 _newPrice) public onlyOwner { require(_newPrice > 0); priceToken = _newPrice; } // low level token purchase function function buyTokens(address _investor) public inState(State.Active) payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; //currentDate = 1526342400; //for test's (Tue, 15 May 2018 00:00:00 GMT) uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; if(currentPeriod < 6){ amountOfTokens = _weiAmount.mul(priceToken).mul(discount[currentPeriod] + 100).div(100); } if(currentPeriod == 0 && _weiAmount < weiMinSalePreIco){ amountOfTokens = 0; } if(0 < currentPeriod && currentPeriod < 6 && _weiAmount < weiMinSaleIco){ amountOfTokens = 0; } return amountOfTokens; } /** * Pre-ICO sale starts on 31 of March, ends on 06 April 2018 * 1st. Stage starts 07 of April , ends on 16 of April , 2018 * 2nd. Stage starts 17 of April , ends on 26 of April , 2018 * 3rd. Stage starts 27 of April , ends on 06 of May , 2018 * 4th. Stage starts 07 of May, ends on 16 of May , 2018 * 4th. Stage starts 17 of May, ends on 31 of May , 2018 */ function getPeriod(uint256 _currentDate) public pure returns (uint) { //1522454400 - March, 31, 2018 00:00:00 && 1523059199 - April, 06, 2018 23:59:59 if( 1522454400 <= _currentDate && _currentDate <= 1523059199){ return 0; } //1523059200 - April, 07, 2018 00:00:00 && 1523923199 - April, 16, 2018 23:59:59 if( 1523059200 <= _currentDate && _currentDate <= 1523923199){ return 1; } //1523923200 - April, 17, 2018 00:00:00 && 1524787199 - April, 26, 2018 23:59:59 if( 1523923200 <= _currentDate && _currentDate <= 1524787199){ return 2; } //1524787200 - April, 27, 2018 00:00:00 && 1525651199 - May, 06, 2018 23:59:59 if( 1524787200 <= _currentDate && _currentDate <= 1525651199){ return 3; } //1525651200 - May, 07, 2018 00:00:00 && 1526515199 - May, 16, 2018 23:59:59 if( 1525651200 <= _currentDate && _currentDate <= 1526515199){ return 4; } //1526515200 - May, 17, 2018 00:00:00 && 1527811199 - May, 31, 2018 23:59:59 if( 1526515200 <= _currentDate && _currentDate <= 1527811199){ return 5; } return 10; } function getAfterIcoPeriod(uint256 _currentDate) public pure returns (uint) { uint256 endIco = 1527811199; // May, 31, 2018 23:59:59 if( endIco < _currentDate && _currentDate <= endIco + 2 years){ return 100; } if( endIco + 2 years < _currentDate && _currentDate <= endIco + 4 years){ return 200; } if( endIco + 4 years < _currentDate && _currentDate <= endIco + 6 years){ return 300; } if( endIco + 6 years < _currentDate && _currentDate <= endIco + 8 years){ return 400; } return 0; } function mintAfterIcoPeriod() public returns (bool result) { uint256 totalCost = tokenAllocated.div(priceToken); uint256 fivePercent = 0; uint256 currentDate = now; //currentDate = 1564704000; //for test Aug, 02, 2019 bool changePeriod = false; uint256 nonSoldToken = totalSupply.sub(tokenAllocated); uint256 mintTokens = 0; result = false; if (currentAfterIcoPeriod < getAfterIcoPeriod(currentDate)){ currentAfterIcoPeriod = currentAfterIcoPeriod.add(getAfterIcoPeriod(currentDate)); changePeriod = true; } if(totalCost.mul(100).div(weiRaised) < 200 || changePeriod){ mintTokens = nonSoldToken.div(4); // 25% fivePercent = mintTokens.div(20); // 5% balances[addressFundBonus] = balances[addressFundBonus].add(fivePercent.mul(2)); balances[addressFundBounty] = balances[addressFundBounty].add(fivePercent); balances[addressFundInvestment] = balances[addressFundInvestment].add(fivePercent.mul(10)); balances[addressFundAdministration] = balances[addressFundAdministration].add(fivePercent); //balances[ownerTwo] = balances[ownerTwo].add(fivePercent.mul(6)); balances[owner] = balances[owner].sub(fivePercent.mul(14)); // - 70% tokenAllocated = tokenAllocated.add(fivePercent.mul(14)); result = true; } } function deposit(address investor) internal { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function mintForOwner(address _wallet) internal returns (bool result) { result = false; uint256 fundBounty = 24533333 * (10 ** uint256(decimals)); uint256 fundDevelopers = 122666665 * (10 ** uint256(decimals)); require(_wallet != address(0)); balances[addressFundDevelopers] = balances[addressFundDevelopers].add(fundDevelopers); balances[addressFundBounty] = balances[addressFundBounty].add(fundBounty); tokenAllocated = tokenAllocated.add(fundDevelopers).add(fundBounty); balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY).sub(tokenAllocated); result = true; } function getDeposited(address _investor) public view returns (uint256){ return deposited[_investor]; } function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (tokenAllocated.add(addTokens) > fundForSale) { TokenLimitReached(tokenAllocated, addTokens); return 0; } if (weiRaised.add(_weiAmount) > hardWeiCap) { HardCapReached(); return 0; } return addTokens; } function finalize() public onlyOwner inState(State.Active) returns (bool result) { result = false; state = State.Closed; wallet.transfer(this.balance); finishMinting(); Finalized(); result = true; } }
$0.25 = 1 token => $1,000 = 1.19 ETH =>
uint256 priceToken = 3362;
9,898,361
[ 1, 8, 20, 18, 2947, 273, 404, 1147, 516, 271, 21, 16, 3784, 273, 404, 18, 3657, 512, 2455, 516, 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, 2254, 5034, 6205, 1345, 273, 890, 5718, 22, 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 ]
./full_match/137/0x231e1Cb3bDf264aEFaE62Ee007aEB81FB7FF64e2/sources/project:/contracts/safe.sol
Struct for NFT type
contract Safe is ERC721URIStorage, Ownable { pragma solidity ^0.8.0; struct NFTType { string ipfsHash; uint256 minPrice; } NFTType[] public nftTypes; mapping(address => bool) public whitelistedMarketplaces; mapping(uint256 => uint256) public transferTimestamps; mapping(uint256 => string) public ipfsHashes; mapping(address => uint256) public addressNonces; mapping(uint256 => bool) public freeMintedTypes; address public signer; address public vault; uint256 public tokenIds = 0; event NFTTypeAdded(string ipfsHash, uint256 minPrice); event MarketplaceWhitelisted(address marketplace); event MarketplaceRemovedFromWhitelist(address marketplace); event MetadataUpdated(uint256 tokenId, string newIpfsHash); constructor(address _vault, address _signer) ERC721("Aniborgs", "Aniborgs") { vault = _vault; signer = _signer; } function claim() public onlyOwner { } (bool success, ) = payable(vault).call{value: address(this).balance}(""); }
4,668,081
[ 1, 3823, 364, 423, 4464, 618, 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, 16351, 14060, 353, 4232, 39, 27, 5340, 3098, 3245, 16, 14223, 6914, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 423, 4464, 559, 288, 203, 3639, 533, 2359, 2556, 2310, 31, 203, 3639, 2254, 5034, 1131, 5147, 31, 203, 565, 289, 203, 203, 565, 423, 4464, 559, 8526, 1071, 290, 1222, 2016, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 26944, 3882, 278, 11350, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 7412, 23761, 31, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 2359, 2556, 14455, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1758, 3989, 764, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 13, 1071, 4843, 49, 474, 329, 2016, 31, 203, 203, 565, 1758, 1071, 10363, 31, 203, 565, 1758, 1071, 9229, 31, 203, 565, 2254, 5034, 1071, 1147, 2673, 273, 374, 31, 203, 203, 565, 871, 423, 4464, 559, 8602, 12, 1080, 2359, 2556, 2310, 16, 2254, 5034, 1131, 5147, 1769, 203, 565, 871, 6622, 24577, 18927, 329, 12, 2867, 29917, 1769, 203, 565, 871, 6622, 24577, 10026, 1265, 18927, 12, 2867, 29917, 1769, 203, 565, 871, 6912, 7381, 12, 11890, 5034, 1147, 548, 16, 533, 394, 5273, 2556, 2310, 1769, 203, 203, 565, 3885, 12, 2867, 389, 26983, 16, 1758, 389, 2977, 264, 13, 4232, 39, 27, 5340, 2932, 979, 495, 280, 564, 3113, 315, 979, 495, 280, 564, 7923, 288, 203, 3639, 9229, 273, 389, 26983, 2 ]
./full_match/80001/0x9C26Ec65b0a74C7516097182728D231D95545e6f/sources/contracts/TalentToken.sol
amount available to be minted timestamp at which minting reached MAX_SUPPLY talent's wallet
{ bytes32 public constant ROLE_TALENT = keccak256("TALENT"); bytes32 public constant ROLE_MINTER = keccak256("MINTER"); uint256 public constant MAX_SUPPLY = 1000000 ether; uint256 public override(ITalentToken) mintingAvailability; uint256 public override(ITalentToken) mintingFinishedAt; address public override(ITalentToken) talent; function initialize( string memory _name, string memory _symbol, uint256 _initialSupply, address _talent, address _minter, address _admin contract TalentToken is ) public initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC20_init_unchained(_name, _symbol); __AccessControl_init_unchained(); talent = _talent; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(ROLE_TALENT, _talent); _setupRole(ROLE_MINTER, _minter); _setRoleAdmin(ROLE_TALENT, ROLE_TALENT); _mint(_talent, _initialSupply); mintingAvailability = MAX_SUPPLY - _initialSupply; } {} function _authorizeUpgrade(address newImplementation) internal override(UUPSUpgradeable) onlyRole(DEFAULT_ADMIN_ROLE) function mint(address _to, uint256 _amount) public override(ITalentToken) onlyRole(ROLE_MINTER) { require(mintingAvailability >= _amount, "_amount exceeds minting availability"); mintingAvailability -= _amount; if (mintingAvailability == 0) { mintingFinishedAt = block.timestamp; } _mint(_to, _amount); } function _authorizeUpgrade(address newImplementation) internal override(UUPSUpgradeable) onlyRole(DEFAULT_ADMIN_ROLE) function mint(address _to, uint256 _amount) public override(ITalentToken) onlyRole(ROLE_MINTER) { require(mintingAvailability >= _amount, "_amount exceeds minting availability"); mintingAvailability -= _amount; if (mintingAvailability == 0) { mintingFinishedAt = block.timestamp; } _mint(_to, _amount); } function burn(address _from, uint256 _amount) public override(ITalentToken) onlyRole(ROLE_MINTER) { if (mintingAvailability > 0) { mintingAvailability += _amount; } _burn(_from, _amount); } function burn(address _from, uint256 _amount) public override(ITalentToken) onlyRole(ROLE_MINTER) { if (mintingAvailability > 0) { mintingAvailability += _amount; } _burn(_from, _amount); } function transferTalentWallet(address _newTalent) public { talent = _newTalent; grantRole(ROLE_TALENT, _newTalent); revokeRole(ROLE_TALENT, msg.sender); } function supportsInterface(bytes4 interfaceId) public view override(ERC165Upgradeable, AccessControlUpgradeable, ERC1363Upgradeable) returns (bool) { return interfaceId == type(IERC20Upgradeable).interfaceId || interfaceId == type(IERC1363Upgradeable).interfaceId || super.supportsInterface(interfaceId); } }
5,560,567
[ 1, 8949, 2319, 358, 506, 312, 474, 329, 2858, 622, 1492, 312, 474, 310, 8675, 4552, 67, 13272, 23893, 268, 287, 319, 1807, 9230, 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, 95, 203, 565, 1731, 1578, 1071, 5381, 22005, 67, 9833, 900, 1784, 273, 417, 24410, 581, 5034, 2932, 9833, 900, 1784, 8863, 203, 203, 565, 1731, 1578, 1071, 5381, 22005, 67, 6236, 2560, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 8863, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 13272, 23893, 273, 15088, 225, 2437, 31, 203, 203, 565, 2254, 5034, 1071, 3849, 12, 1285, 287, 319, 1345, 13, 312, 474, 310, 10427, 31, 203, 203, 565, 2254, 5034, 1071, 3849, 12, 1285, 287, 319, 1345, 13, 312, 474, 310, 10577, 861, 31, 203, 203, 565, 1758, 1071, 3849, 12, 1285, 287, 319, 1345, 13, 268, 287, 319, 31, 203, 203, 565, 445, 4046, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 5034, 389, 6769, 3088, 1283, 16, 203, 3639, 1758, 389, 88, 287, 319, 16, 203, 3639, 1758, 389, 1154, 387, 16, 203, 3639, 1758, 389, 3666, 203, 16351, 399, 287, 319, 1345, 353, 203, 565, 262, 1071, 12562, 288, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 654, 39, 28275, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 654, 39, 3462, 67, 2738, 67, 4384, 8707, 24899, 529, 16, 389, 7175, 1769, 203, 3639, 1001, 16541, 67, 2738, 67, 4384, 8707, 5621, 203, 203, 3639, 268, 287, 319, 273, 389, 88, 287, 319, 31, 203, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3666, 1769, 203, 3639, 389, 8401, 2 ]
./full_match/80001/0x7D76Ec6d3181c759760FdDA90187fcCBF2cc9b30/sources/contracts/starter.sol
Rewards per hour per token deposited in wei.
uint256 private rewardsPerHour = 20833000000000000000000;
868,420
[ 1, 17631, 14727, 1534, 6126, 1534, 1147, 443, 1724, 329, 316, 732, 77, 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 ]
[ 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, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 4200, 28, 3707, 12648, 2787, 9449, 31, 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 ]
./full_match/11155111/0xf1f1885bA386d1AD8941579b317fFaC7fA86EB7B/sources/project_/contracts/agreements/ConstantFlowAgreementV1.sol
@dev IConstantFlowAgreementV1.getFlowOperatorDataByID implementation
function getFlowOperatorDataByID( ISuperfluidToken token, bytes32 flowOperatorId ) external view override returns(uint8 permissions, int96 flowRateAllowance) { (, FlowOperatorData memory flowOperatorData) = _getFlowOperatorData(token, flowOperatorId); permissions = flowOperatorData.permissions; flowRateAllowance = flowOperatorData.flowRateAllowance; }
3,797,124
[ 1, 45, 6902, 5249, 17420, 58, 21, 18, 588, 5249, 5592, 751, 13331, 4471, 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, 2812, 821, 5592, 751, 13331, 12, 203, 3639, 467, 8051, 2242, 1911, 1345, 1147, 16, 203, 3639, 1731, 1578, 4693, 5592, 548, 203, 565, 262, 203, 3639, 3903, 1476, 3849, 203, 3639, 1135, 12, 11890, 28, 4371, 16, 509, 10525, 4693, 4727, 7009, 1359, 13, 203, 565, 288, 203, 3639, 261, 16, 9473, 5592, 751, 3778, 4693, 5592, 751, 13, 273, 389, 588, 5249, 5592, 751, 12, 2316, 16, 4693, 5592, 548, 1769, 203, 3639, 4371, 273, 4693, 5592, 751, 18, 9612, 31, 203, 3639, 4693, 4727, 7009, 1359, 273, 4693, 5592, 751, 18, 2426, 4727, 7009, 1359, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../reserve/GoodReserveCDai.sol"; import "../Interfaces.sol"; import "../utils/DSMath.sol"; import "../utils/DAOUpgradeableContract.sol"; /** * @title GoodFundManager contract that transfer interest from the staking contract * to the reserve contract and transfer the return mintable tokens to the staking * contract * cDAI support only */ contract GoodFundManager is DAOUpgradeableContract, DSMath { // timestamp that indicates last time that interests collected uint256 public lastCollectedInterest; //just for UI to easily find last event uint256 public lastCollectedInterestBlock; // Gas cost for mint ubi+bridge ubi+mint rewards uint256 public gasCostExceptInterestCollect; // Gas cost for minting GD for keeper uint256 public gdMintGasCost; // how much time since last collectInterest should pass in order to cancel gas cost multiplier requirement for next collectInterest uint256 public collectInterestTimeThreshold; // to allow keeper to collect interest, total interest collected should be interestMultiplier*gas costs uint8 public interestMultiplier; //min amount of days between interest collection uint8 public minCollectInterestIntervalDays; //address of the active staking contracts address[] public activeContracts; event GasCostSet(uint256 newGasCost); event CollectInterestTimeThresholdSet( uint256 newCollectInterestTimeThreshold ); event InterestMultiplierSet(uint8 newInterestMultiplier); event GasCostExceptInterestCollectSet( uint256 newGasCostExceptInterestCollect ); event StakingRewardSet( uint32 _rewardsPerBlock, address _stakingAddress, uint32 _blockStart, uint32 _blockEnd, bool _isBlackListed ); //Structure that hold reward information and if its blacklicksted or not for particular staking Contract struct Reward { uint32 blockReward; //in G$ uint64 blockStart; // # of the start block to distribute rewards uint64 blockEnd; // # of the end block to distribute rewards bool isBlackListed; // If staking contract is blacklisted or not } struct InterestInfo { address contractAddress; // staking contract address which interest will be collected uint256 interestBalance; // Interest amount that staking contract has uint256 collectedInterestSoFar; // Collected interest amount so far including this contract uint256 gasCostSoFar; // Spent gas amount so far including this contract uint256 maxGasAmountSoFar; // Max gas amount that can spend to collect this interest according to interest amount bool maxGasLargerOrEqualRequired; // Bool that indicates if max gas amount larger or equal to actual gas needed } // Rewards per block for particular Staking contract mapping(address => Reward) public rewardsForStakingContract; // Emits when `transferInterest` transfers // funds to the staking contract and to // the bridge event FundsTransferred( // The caller address address indexed caller, // The staking contract address //address indexed staking, // The reserve contract address address reserve, //addresses of the staking contracts address[] stakings, // Amount of cDai that was transferred // from the staking contract to the // reserve contract uint256 cDAIinterestEarned, // The number of tokens that have been minted // by the reserve to the staking contract //uint256 gdInterest, // The number of tokens that have been minted // by the reserve to the bridge which in his // turn should transfer those funds to the // sidechain uint256 gdUBI, // Amount of GD to be minted as reward //to the keeper which collect interests uint256 gdReward ); event StakingRewardMinted( address stakingContract, address staker, uint256 gdReward ); /** * @dev Constructor * @param _ns The address of the name Service */ function initialize(INameService _ns) public virtual initializer { setDAO(_ns); gdMintGasCost = 250000; // While testing highest amount was 240k so put 250k to be safe collectInterestTimeThreshold = 60 days; interestMultiplier = 4; gasCostExceptInterestCollect = 850000; //while testing highest amount was 800k so put 850k to be safe minCollectInterestIntervalDays = 7; } /** * @dev Set gas cost to mint GD rewards for keeper * @param _gasAmount amount of gas it costs for minting gd reward */ function setGasCost(uint256 _gasAmount) public { _onlyAvatar(); gdMintGasCost = _gasAmount; emit GasCostSet(_gasAmount); } /** * @dev Set collectInterestTimeThreshold to determine how much time should pass after collectInterest called * after which we ignore the interest>=multiplier*gas costs limit * @param _timeThreshold new threshold in seconds */ function setCollectInterestTimeThreshold(uint256 _timeThreshold) public { _onlyAvatar(); collectInterestTimeThreshold = _timeThreshold; emit CollectInterestTimeThresholdSet(_timeThreshold); } /** * @dev Set multiplier to determine how much times larger should be collected interest than spent gas when collectInterestTimeThreshold did not pass */ function setInterestMultiplier(uint8 _newMultiplier) public { _onlyAvatar(); interestMultiplier = _newMultiplier; emit InterestMultiplierSet(_newMultiplier); } /** * @dev Set Gas cost for required transactions after collecting interest in collectInterest function * we need this to know if caller has enough gas left to keep collecting interest * @dev _gasAmount The gas amount that needed for transactions */ function setGasCostExceptInterestCollect(uint256 _gasAmount) public { _onlyAvatar(); gasCostExceptInterestCollect = _gasAmount; emit GasCostExceptInterestCollectSet(_gasAmount); } /** * @dev Sets the Reward for particular Staking contract * @param _rewardsPerBlock reward for per block * @param _stakingAddress address of the staking contract * @param _blockStart block number for start reward distrubution * @param _blockEnd block number for end reward distrubition * @param _isBlackListed set staking contract blacklisted or not to prevent minting */ function setStakingReward( uint32 _rewardsPerBlock, address _stakingAddress, uint32 _blockStart, uint32 _blockEnd, bool _isBlackListed ) public { _onlyAvatar(); //we dont allow to undo blacklisting as it will mess up rewards accounting. //staking contracts are assumed immutable and thus non fixable require( (_isBlackListed || !rewardsForStakingContract[_stakingAddress].isBlackListed), "can't undo blacklisting" ); Reward memory reward = Reward( _rewardsPerBlock, _blockStart > 0 ? _blockStart : uint32(block.number), _blockEnd > 0 ? _blockEnd : 0xFFFFFFFF, _isBlackListed ); rewardsForStakingContract[_stakingAddress] = reward; bool exist; uint8 i; for (i = 0; i < activeContracts.length; i++) { if (activeContracts[i] == _stakingAddress) { exist = true; break; } } if (exist && (_isBlackListed || _rewardsPerBlock == 0)) { activeContracts[i] = activeContracts[activeContracts.length - 1]; activeContracts.pop(); } else if (!exist && !(_isBlackListed || _rewardsPerBlock == 0)) { activeContracts.push(_stakingAddress); } emit StakingRewardSet( _rewardsPerBlock, _stakingAddress, _blockStart, _blockEnd, _isBlackListed ); } /** * @dev Collects UBI interest in iToken from a given staking contract and transfers * that interest to the reserve contract. Then transfers the given gd which * received from the reserve contract back to the staking contract and to the * bridge, which locks the funds and then the GD tokens are been minted to the * given address on the sidechain * @param _stakingContracts from which contracts to collect interest * @param _forceAndWaiverRewards if set to true, it will collect interest even if not passed thershold, but will not reward caller with gas refund + reward */ function collectInterest( address[] calldata _stakingContracts, bool _forceAndWaiverRewards ) external { uint256 initialGas = gasleft(); uint256 gdUBI; uint256 interestInCdai; address reserveAddress; { // require( // block.timestamp >= lastCollectedInterest + minCollectedInterestIntervalDays * days, // "collectInterest: collect interval not passed" // ); //prevent stack too deep cERC20 iToken = cERC20(nameService.getAddress("CDAI")); ERC20 daiToken = ERC20(nameService.getAddress("DAI")); reserveAddress = nameService.getAddress("RESERVE"); // DAI balance of the reserve contract uint256 currentBalance = daiToken.balanceOf(reserveAddress); uint256 startingCDAIBalance = iToken.balanceOf(reserveAddress); for (uint256 i = _stakingContracts.length - 1; i >= 0; i--) { // elements are sorted by balances from lowest to highest if (_stakingContracts[i] != address(0x0)) { IGoodStaking(_stakingContracts[i]).collectUBIInterest(reserveAddress); } if (i == 0) break; // when active contracts length is 1 then gives error } // Finds the actual transferred DAI uint256 daiToConvert = daiToken.balanceOf(reserveAddress) - currentBalance; // Mints gd while the interest amount is equal to the transferred amount (gdUBI, interestInCdai) = GoodReserveCDai(reserveAddress).mintUBI( daiToConvert, startingCDAIBalance, iToken ); IGoodDollar token = IGoodDollar(nameService.getAddress("GOODDOLLAR")); if (gdUBI > 0) { //transfer ubi to avatar on sidechain via bridge require( token.transferAndCall( nameService.getAddress("BRIDGE_CONTRACT"), gdUBI, abi.encodePacked(nameService.getAddress("UBI_RECIPIENT")) ), "ubi bridge transfer failed" ); } } uint256 gdRewardToMint; if (_forceAndWaiverRewards == false) { uint256 totalUsedGas = ((initialGas - gasleft() + gdMintGasCost) * 110) / 100; // We will return as reward 1.1x of used gas in GD gdRewardToMint = getGasPriceInGD(totalUsedGas); GoodReserveCDai(reserveAddress).mintRewardFromRR( nameService.getAddress("CDAI"), msg.sender, gdRewardToMint ); uint256 gasPriceIncDAI = getGasPriceIncDAIorDAI( initialGas - gasleft(), false ); if ( block.timestamp >= lastCollectedInterest + collectInterestTimeThreshold ) { require( interestInCdai >= gasPriceIncDAI, "Collected interest value should be larger than spent gas costs" ); // This require is necessary to keeper can not abuse this function } else { require( interestInCdai >= interestMultiplier * gasPriceIncDAI, "Collected interest value should be interestMultiplier x gas costs" ); } } emit FundsTransferred( msg.sender, reserveAddress, _stakingContracts, interestInCdai, gdUBI, gdRewardToMint ); lastCollectedInterest = block.timestamp; lastCollectedInterestBlock = block.number; } /** * @dev Function that get interest informations of staking contracts in the sorted array by highest interest to lowest interest amount * @return array of interestInfo struct */ function calcSortedContracts() public view returns (InterestInfo[] memory) { address[] memory addresses = new address[](activeContracts.length); uint256[] memory balances = new uint256[](activeContracts.length); InterestInfo[] memory interestInfos = new InterestInfo[]( activeContracts.length ); uint256 tempInterest; int256 i; for (i = 0; i < int256(activeContracts.length); i++) { (, , , , tempInterest) = IGoodStaking(activeContracts[uint256(i)]) .currentGains(false, true); if (tempInterest != 0) { addresses[uint256(i)] = activeContracts[uint256(i)]; balances[uint256(i)] = tempInterest; } } uint256 usedGasAmount = gasCostExceptInterestCollect; quick(balances, addresses); // sort the values according to interest balance uint256 gasCost; uint256 possibleCollected; uint256 maxGasAmount; for (i = int256(activeContracts.length) - 1; i >= 0; i--) { // elements are sorted by balances from lowest to highest if (addresses[uint256(i)] != address(0x0)) { gasCost = IGoodStaking(addresses[uint256(i)]) .getGasCostForInterestTransfer(); // collects the interest from the staking contract and transfer it directly to the reserve contract //`collectUBIInterest` returns (iTokengains, tokengains, precission loss, donation ratio) possibleCollected += balances[uint256(i)]; usedGasAmount += gasCost; maxGasAmount = block.timestamp >= lastCollectedInterest + collectInterestTimeThreshold ? (possibleCollected * 1e10) / getGasPriceIncDAIorDAI(1, true) : (possibleCollected * 1e10) / (interestMultiplier * getGasPriceIncDAIorDAI(1, true)); interestInfos[uint256(i)] = InterestInfo({ contractAddress: addresses[uint256(i)], interestBalance: balances[uint256(i)], collectedInterestSoFar: possibleCollected, gasCostSoFar: usedGasAmount, maxGasAmountSoFar: maxGasAmount, maxGasLargerOrEqualRequired: maxGasAmount >= usedGasAmount }); } else { break; // if addresses are null after this element then break because we initialize array in size activecontracts but if their interest balance is zero then we dont put it in this array } } return interestInfos; } /** * @dev Mint to users reward tokens which they earned by staking contract * @param _token reserve token (currently can be just cDAI) * @param _user user to get rewards */ function mintReward(address _token, address _user) public { Reward memory staking = rewardsForStakingContract[address(msg.sender)]; require(staking.blockStart > 0, "Staking contract not registered"); uint256 amount = IGoodStaking(address(msg.sender)).rewardsMinted( _user, staking.blockReward, staking.blockStart, staking.blockEnd ); if (amount > 0 && staking.isBlackListed == false) { GoodReserveCDai(nameService.getAddress("RESERVE")).mintRewardFromRR( _token, _user, amount ); emit StakingRewardMinted(msg.sender, _user, amount); } } /// quick sort function quick(uint256[] memory data, address[] memory addresses) internal pure { if (data.length > 1) { quickPart(data, addresses, 0, data.length - 1); } } /** @dev quicksort algorithm to sort array */ function quickPart( uint256[] memory data, address[] memory addresses, uint256 low, uint256 high ) internal pure { if (low < high) { uint256 pivotVal = data[(low + high) / 2]; uint256 low1 = low; uint256 high1 = high; for (;;) { while (data[low1] < pivotVal) low1++; while (data[high1] > pivotVal) high1--; if (low1 >= high1) break; (data[low1], data[high1]) = (data[high1], data[low1]); (addresses[low1], addresses[high1]) = ( addresses[high1], addresses[low1] ); low1++; high1--; } if (low < high1) quickPart(data, addresses, low, high1); high1++; if (high1 < high) quickPart(data, addresses, high1, high); } } /** @dev Helper function to get gasPrice in GWEI then change it to cDAI/DAI @param _gasAmount gas amount to get its value @param _inDAI indicates if result should return in DAI @return Price of the gas in DAI/cDAI */ function getGasPriceIncDAIorDAI(uint256 _gasAmount, bool _inDAI) public view returns (uint256) { AggregatorV3Interface gasPriceOracle = AggregatorV3Interface( nameService.getAddress("GAS_PRICE_ORACLE") ); int256 gasPrice = gasPriceOracle.latestAnswer(); // returns gas price in 0 decimal as GWEI so 1eth / 1e9 eth AggregatorV3Interface daiETHOracle = AggregatorV3Interface( nameService.getAddress("DAI_ETH_ORACLE") ); int256 daiInETH = daiETHOracle.latestAnswer(); // returns DAI price in ETH uint256 result = ((uint256(gasPrice) * 1e18) / uint256(daiInETH)); // Gasprice in GWEI and daiInETH is 18 decimals so we multiply gasprice with 1e18 in order to get result in 18 decimals if (_inDAI) return result * _gasAmount; result = (((result / 1e10) * 1e28) / cERC20(nameService.getAddress("CDAI")).exchangeRateStored()) * _gasAmount; // based on https://compound.finance/docs#protocol-math return result; } /** @dev Helper function to get gasPrice in G$, used to calculate the rewards for collectInterest KEEPER @param _gasAmount gas amount to get its value @return Price of the gas in G$ */ function getGasPriceInGD(uint256 _gasAmount) public view returns (uint256) { uint256 priceInCdai = getGasPriceIncDAIorDAI(_gasAmount, false); uint256 gdPriceIncDAI = GoodReserveCDai(nameService.getAddress("RESERVE")) .currentPrice(); return ((priceInCdai * 1e27) / gdPriceIncDAI) / 1e25; // rdiv returns result in 27 decimals since GD$ in 2 decimals then divide 1e25 } function getActiveContractsCount() public view returns (uint256) { return activeContracts.length; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../utils/DAOUpgradeableContract.sol"; import "../utils/NameService.sol"; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; import "./GoodMarketMaker.sol"; interface ContributionCalc { function calculateContribution( GoodMarketMaker _marketMaker, GoodReserveCDai _reserve, address _contributer, ERC20 _token, uint256 _gdAmount ) external view returns (uint256); function setContributionRatio(uint256 _nom, uint256 _denom) external; } /** @title Reserve based on cDAI and dynamic reserve ratio market maker */ contract GoodReserveCDai is DAOUpgradeableContract, ERC20PresetMinterPauserUpgradeable, GlobalConstraintInterface { bytes32 public constant RESERVE_MINTER_ROLE = keccak256("RESERVE_MINTER_ROLE"); /// @dev G$ minting cap; uint256 public cap; // The last block number which // `mintUBI` has been executed in uint256 public lastMinted; address public daiAddress; address public cDaiAddress; /// @dev merkleroot for GDX airdrop bytes32 public gdxAirdrop; /// @dev mark if user claimed his GDX mapping(address => bool) public isClaimedGDX; // Emits when new GD tokens minted event UBIMinted( //epoch of UBI uint256 indexed day, //the token paid as interest address indexed interestToken, //wei amount of interest paid in interestToken uint256 interestReceived, // Amount of GD tokens that was // added to the supply as a result // of `mintInterest` uint256 gdInterestMinted, // Amount of GD tokens that was // added to the supply as a result // of `mintExpansion` uint256 gdExpansionMinted, // Amount of GD tokens that was // minted to the `ubiCollector` uint256 gdUbiTransferred ); // Emits when GD tokens are purchased event TokenPurchased( // The initiate of the action address indexed caller, // The convertible token address // which the GD tokens were // purchased with address indexed inputToken, // Reserve tokens amount uint256 inputAmount, // Actual return after the // conversion uint256 actualReturn, // Address of the receiver of tokens address indexed receiverAddress ); // Emits when GD tokens are sold event TokenSold( // The initiate of the action address indexed caller, // The convertible token address // which the GD tokens were // sold to address indexed outputToken, // GD tokens amount uint256 gdAmount, // The amount of GD tokens that // was contributed during the // conversion uint256 contributionAmount, // Actual return after the // conversion uint256 actualReturn, // Address of the receiver of tokens address indexed receiverAddress ); function initialize(INameService _ns, bytes32 _gdxAirdrop) public virtual initializer { __ERC20PresetMinterPauser_init("GDX", "G$X"); setDAO(_ns); //fixed cdai/dai setAddresses(); //gdx roles renounceRole(MINTER_ROLE, _msgSender()); renounceRole(PAUSER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, address(avatar)); //mint access through reserve _setupRole(RESERVE_MINTER_ROLE, address(avatar)); //only Avatar can manage minters cap = 22 * 1e14; //22 trillion G$ cents gdxAirdrop = _gdxAirdrop; } /// @dev GDX decimals function decimals() public pure override returns (uint8) { return 2; } function setAddresses() public { daiAddress = nameService.getAddress("DAI"); cDaiAddress = nameService.getAddress("CDAI"); // Approve transfer to cDAI contract ERC20(daiAddress).approve(cDaiAddress, type(uint256).max); } /** * @dev get current MarketMaker from name service * The address of the market maker contract * which makes the calculations and holds * the token and accounts info (should be owned by the reserve) */ function getMarketMaker() public view returns (GoodMarketMaker) { return GoodMarketMaker(nameService.getAddress("MARKET_MAKER")); } /** * @dev Converts cDai tokens to GD tokens and updates the bonding curve params. * `buy` occurs only if the GD return is above the given minimum. It is possible * to buy only with cDAI and when the contract is set to active. MUST call to * cDAI `approve` prior this action to allow this contract to accomplish the * conversion. * @param _tokenAmount The amount of cDAI tokens that should be converted to GD tokens * @param _minReturn The minimum allowed return in GD tokens * @param _targetAddress address of g$ and gdx recipient if different than msg.sender * @return (gdReturn) How much GD tokens were transferred */ function buy( uint256 _tokenAmount, uint256 _minReturn, address _targetAddress ) external returns (uint256) { ERC20 buyWith = ERC20(cDaiAddress); uint256 gdReturn = getMarketMaker().buy(buyWith, _tokenAmount); _targetAddress = _targetAddress == address(0x0) ? msg.sender : _targetAddress; address exchangeHelper = nameService.getAddress("EXCHANGE_HELPER"); if (msg.sender != exchangeHelper) require( buyWith.transferFrom(msg.sender, address(this), _tokenAmount) == true, "transferFrom failed, make sure you approved input token transfer" ); require( gdReturn >= _minReturn, "GD return must be above the minReturn" ); _mintGoodDollars(_targetAddress, gdReturn, true); //mint GDX _mintGDX(_targetAddress, gdReturn); if (msg.sender != exchangeHelper) emit TokenPurchased( msg.sender, cDaiAddress, _tokenAmount, gdReturn, _targetAddress ); return gdReturn; } /** * @dev Mint rewards for staking contracts in G$ and update RR * requires minting permissions which is enforced by _mintGoodDollars * @param _to Receipent address for rewards * @param _amount G$ amount to mint for rewards */ function mintRewardFromRR( address _token, address _to, uint256 _amount ) public { getMarketMaker().mintFromReserveRatio(ERC20(_token), _amount); _mintGoodDollars(_to, _amount, false); //mint GDX _mintGDX(_to, _amount); } /** * @dev sell helper function burns GD tokens and update the bonding curve params. * `sell` occurs only if the token return is above the given minimum. Notice that * there is a contribution amount from the given GD that remains in the reserve. * @param _gdAmount The amount of GD tokens that should be converted to cDAI tokens * @param _minReturn The minimum allowed `sellTo` tokens return * @param _target address of the receiver of cDAI when sell G$ * @param _seller address of the seller when using helper contract * @return (tokenReturn, contribution) (cDAI received, G$ exit contribution) */ function sell( uint256 _gdAmount, uint256 _minReturn, address _target, address _seller ) external returns (uint256, uint256) { GoodMarketMaker mm = getMarketMaker(); if (msg.sender != nameService.getAddress("EXCHANGE_HELPER")) { IGoodDollar(nameService.getAddress("GOODDOLLAR")).burnFrom( msg.sender, _gdAmount ); _seller = msg.sender; } _target = _target == address(0x0) ? msg.sender : _target; //discount on exit contribution based on gdx uint256 gdx = balanceOf(_seller); uint256 discount = gdx <= _gdAmount ? gdx : _gdAmount; //burn gdx used for discount _burn(_seller, discount); uint256 contributionAmount = 0; uint256 gdAmountTemp = _gdAmount; // to prevent stack too deep errors if (discount < gdAmountTemp) contributionAmount = ContributionCalc( nameService.getAddress("CONTRIBUTION_CALCULATION") ).calculateContribution( mm, this, _seller, ERC20(cDaiAddress), gdAmountTemp - discount ); uint256 tokenReturn = mm.sellWithContribution( ERC20(cDaiAddress), gdAmountTemp, contributionAmount ); require( tokenReturn >= _minReturn, "Token return must be above the minReturn" ); cERC20(cDaiAddress).transfer(_target, tokenReturn); if (_seller == msg.sender) emit TokenSold( msg.sender, cDaiAddress, _gdAmount, contributionAmount, tokenReturn, _target ); return (tokenReturn, contributionAmount); } function currentPrice() public view returns (uint256) { return getMarketMaker().currentPrice(ERC20(cDaiAddress)); } function currentPriceDAI() public view returns (uint256) { cERC20 cDai = cERC20(cDaiAddress); return (((currentPrice() * 1e10) * cDai.exchangeRateStored()) / 1e28); // based on https://compound.finance/docs#protocol-math } /** * @dev helper to mint G$s * @param _to the recipient of newly minted G$s * @param _gdToMint how much G$ to mint * @param _internalCall skip minting role validation for internal calls, used when "buying G$" to "allow" buyer to mint G$ in exchange for his cDAI */ function _mintGoodDollars( address _to, uint256 _gdToMint, bool _internalCall ) internal { //enforce minting rules require( _internalCall || _msgSender() == nameService.getAddress("FUND_MANAGER") || hasRole(RESERVE_MINTER_ROLE, _msgSender()), "GoodReserve: not a minter" ); require( IGoodDollar(nameService.getAddress("GOODDOLLAR")).totalSupply() + _gdToMint <= cap, "GoodReserve: cap enforced" ); IGoodDollar(nameService.getAddress("GOODDOLLAR")).mint(_to, _gdToMint); } /// @dev helper to mint GDX to make _mint more verbose function _mintGDX(address _to, uint256 _gdx) internal { _mint(_to, _gdx); } /** * @dev only FundManager or other with mint G$ permission can call this to trigger minting. * Reserve sends UBI + interest to FundManager. * @param _daiToConvert DAI amount to convert cDAI * @param _startingCDAIBalance Initial cDAI balance before staking collect process start * @param _interestToken The token that was transfered to the reserve * @return gdUBI,interestInCdai how much GD UBI was minted and how much cDAI collected from staking contracts */ function mintUBI( uint256 _daiToConvert, uint256 _startingCDAIBalance, ERC20 _interestToken ) public returns (uint256, uint256) { cERC20(cDaiAddress).mint(_daiToConvert); uint256 interestInCdai = _interestToken.balanceOf(address(this)) - _startingCDAIBalance; uint256 gdInterestToMint = getMarketMaker().mintInterest( _interestToken, interestInCdai ); uint256 gdExpansionToMint = getMarketMaker().mintExpansion( _interestToken ); uint256 gdUBI = gdInterestToMint + gdExpansionToMint; //this enforces who can call the public mintUBI method. only an address with permissions at reserve of RESERVE_MINTER_ROLE _mintGoodDollars(nameService.getAddress("FUND_MANAGER"), gdUBI, false); lastMinted = block.number; emit UBIMinted( lastMinted, address(_interestToken), interestInCdai, gdInterestToMint, gdExpansionToMint, gdUBI ); return (gdUBI, interestInCdai); } /** * @dev Allows the DAO to change the daily expansion rate * it is calculated by _nom/_denom with e27 precision. Emits * `ReserveRatioUpdated` event after the ratio has changed. * Only Avatar can call this method. * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public { _onlyAvatar(); getMarketMaker().setReserveRatioDailyExpansion(_nom, _denom); } /** * @dev Remove minting rights after it has transferred the cDAI funds to `_avatar` * Only the Avatar can execute this method */ function end() public { _onlyAvatar(); // remaining cDAI tokens in the current reserve contract recover(ERC20(cDaiAddress)); //restore minting to avatar, so he can re-delegate it IGoodDollar gd = IGoodDollar(nameService.getAddress("GOODDOLLAR")); if (gd.isMinter(address(avatar)) == false) gd.addMinter(address(avatar)); IGoodDollar(nameService.getAddress("GOODDOLLAR")).renounceMinter(); } /** * @dev method to recover any stuck erc20 tokens (ie compound COMP) * @param _token the ERC20 token to recover */ function recover(ERC20 _token) public { _onlyAvatar(); require( _token.transfer(address(avatar), _token.balanceOf(address(this))), "recover transfer failed" ); } /** * @notice prove user balance in a specific blockchain state hash * @dev "rootState" is a special state that can be supplied once, and actually mints reputation on the current blockchain * @param _user the user to prove his balance * @param _gdx the balance we are prooving * @param _proof array of byte32 with proof data (currently merkle tree path) * @return true if proof is valid */ function claimGDX( address _user, uint256 _gdx, bytes32[] memory _proof ) public returns (bool) { require(isClaimedGDX[_user] == false, "already claimed gdx"); bytes32 leafHash = keccak256(abi.encode(_user, _gdx)); bool isProofValid = MerkleProofUpgradeable.verify( _proof, gdxAirdrop, leafHash ); require(isProofValid, "invalid merkle proof"); _mintGDX(_user, _gdx); isClaimedGDX[_user] = true; return true; } // implement minting constraints through the GlobalConstraintInterface interface. prevent any minting not through reserve function pre( address _scheme, bytes32 _hash, bytes32 _method ) public pure override returns (bool) { _scheme; _hash; _method; if (_method == "mintTokens") return false; return true; } function when() public pure override returns (CallPhase) { return CallPhase.Pre; } } // SPDX-License-Identifier: MIT import { DataTypes } from "./utils/DataTypes.sol"; pragma solidity >=0.8.0; pragma experimental ABIEncoderV2; interface ERC20 { function balanceOf(address addr) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function decimals() external view returns (uint8); function mint(address to, uint256 mintAmount) external returns (uint256); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); event Transfer(address indexed from, address indexed to, uint256 amount); event Transfer( address indexed from, address indexed to, uint256 amount, bytes data ); } interface cERC20 is ERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 mintAmount) external returns (uint256); function redeem(uint256 mintAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } interface IGoodDollar is ERC20 { function getFees(uint256 value) external view returns (uint256, bool); function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function renounceMinter() external; function addMinter(address minter) external; function isMinter(address minter) external view returns (bool); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool); function formula() external view returns (address); } interface IERC2917 is ERC20 { /// @dev This emit when interests amount per block is changed by the owner of the contract. /// It emits with the old interests amount and the new interests amount. event InterestRatePerBlockChanged(uint256 oldValue, uint256 newValue); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityIncreased(address indexed user, uint256 value); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event ProductivityDecreased(address indexed user, uint256 value); /// @dev Return the current contract's interests rate per block. /// @return The amount of interests currently producing per each block. function interestsPerBlock() external view returns (uint256); /// @notice Change the current contract's interests rate. /// @dev Note the best practice will be restrict the gross product provider's contract address to call this. /// @return The true/fase to notice that the value has successfully changed or not, when it succeed, it will emite the InterestRatePerBlockChanged event. function changeInterestRatePerBlock(uint256 value) external returns (bool); /// @notice It will get the productivity of given user. /// @dev it will return 0 if user has no productivity proved in the contract. /// @return user's productivity and overall productivity. function getProductivity(address user) external view returns (uint256, uint256); /// @notice increase a user's productivity. /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. /// @return true to confirm that the productivity added success. function increaseProductivity(address user, uint256 value) external returns (bool); /// @notice decrease a user's productivity. /// @dev Note the best practice will be restrict the callee to prove of productivity's contract address. /// @return true to confirm that the productivity removed success. function decreaseProductivity(address user, uint256 value) external returns (bool); /// @notice take() will return the interests that callee will get at current block height. /// @dev it will always calculated by block.number, so it will change when block height changes. /// @return amount of the interests that user are able to mint() at current block height. function take() external view returns (uint256); /// @notice similar to take(), but with the block height joined to calculate return. /// @dev for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests. /// @return amount of interests and the block height. function takeWithBlock() external view returns (uint256, uint256); /// @notice mint the avaiable interests to callee. /// @dev once it mint, the amount of interests will transfer to callee's address. /// @return the amount of interests minted. function mint() external returns (uint256); } interface Staking { struct Staker { // The staked DAI amount uint256 stakedDAI; // The latest block number which the // staker has staked tokens uint256 lastStake; } function stakeDAI(uint256 amount) external; function withdrawStake() external; function stakers(address staker) external view returns (Staker memory); } interface Uniswap { function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function WETH() external pure returns (address); function factory() external pure returns (address); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountOut( uint256 amountI, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountsOut(uint256 amountIn, address[] memory path) external pure returns (uint256[] memory amounts); } interface UniswapFactory { function getPair(address tokenA, address tokenB) external view returns (address); } interface UniswapPair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); } interface Reserve { function buy( address _buyWith, uint256 _tokenAmount, uint256 _minReturn ) external returns (uint256); } interface IIdentity { function isWhitelisted(address user) external view returns (bool); function addWhitelistedWithDID(address account, string memory did) external; function removeWhitelisted(address account) external; function addIdentityAdmin(address account) external returns (bool); function setAvatar(address _avatar) external; function isIdentityAdmin(address account) external view returns (bool); function owner() external view returns (address); event WhitelistedAdded(address user); } interface IUBIScheme { function currentDay() external view returns (uint256); function periodStart() external view returns (uint256); function hasClaimed(address claimer) external view returns (bool); } interface IFirstClaimPool { function awardUser(address user) external returns (uint256); function claimAmount() external view returns (uint256); } interface ProxyAdmin { function getProxyImplementation(address proxy) external view returns (address); function getProxyAdmin(address proxy) external view returns (address); function upgrade(address proxy, address implementation) external; function owner() external view returns (address); function transferOwnership(address newOwner) external; } /** * @dev Interface for chainlink oracles to obtain price datas */ interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestAnswer() external view returns (int256); } /** @dev interface for AAVE lending Pool */ interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); } interface IDonationStaking { function stakeDonations() external payable; } interface INameService { function getAddress(string memory _name) external view returns (address); } interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); } interface IGoodStaking { function collectUBIInterest(address recipient) external returns ( uint256, uint256, uint256 ); function iToken() external view returns (address); function currentGains( bool _returnTokenBalanceInUSD, bool _returnTokenGainsInUSD ) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function getRewardEarned(address user) external view returns (uint256); function getGasCostForInterestTransfer() external view returns (uint256); function rewardsMinted( address user, uint256 rewardsPerBlock, uint256 blockStart, uint256 blockEnd ) external returns (uint256); } interface IHasRouter { function getRouter() external view returns (Uniswap); } interface IAdminWallet { function addAdmins(address payable[] memory _admins) external; function removeAdmins(address[] memory _admins) external; function owner() external view returns (address); function transferOwnership(address _owner) external; } // SPDX-License-Identifier: MIT /// math.sol -- mixin for inline numerical wizardry // 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/>. pragma solidity >=0.8.0; contract DSMath { function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * y) / 10**27; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * (10**27)) / y; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./DAOContract.sol"; /** @title Simple contract that adds upgradability to DAOContract */ contract DAOUpgradeableContract is Initializable, UUPSUpgradeable, DAOContract { function _authorizeUpgrade(address) internal virtual override { _onlyAvatar(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../extensions/ERC20BurnableUpgradeable.sol"; import "../extensions/ERC20PausableUpgradeable.sol"; import "../../../access/AccessControlEnumerableUpgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable { function initialize(string memory name, string memory symbol) public virtual initializer { __ERC20PresetMinterPauser_init(name, symbol); } 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}. */ function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20PresetMinterPauser_init_unchained(name, symbol); } function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer { _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(ERC20Upgradeable, ERC20PausableUpgradeable) { super._beforeTokenTransfer(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @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; } } // 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 "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "../DAOStackInterfaces.sol"; /** @title Simple name to address resolver */ contract NameService is Initializable, UUPSUpgradeable { mapping(bytes32 => address) public addresses; Controller public dao; event AddressChanged(string name ,address addr); function initialize( Controller _dao, bytes32[] memory _nameHashes, address[] memory _addresses ) public virtual initializer { dao = _dao; for (uint256 i = 0; i < _nameHashes.length; i++) { addresses[_nameHashes[i]] = _addresses[i]; } addresses[keccak256(bytes("CONTROLLER"))] = address(_dao); addresses[keccak256(bytes("AVATAR"))] = address(_dao.avatar()); } function _authorizeUpgrade(address) internal override { _onlyAvatar(); } function _onlyAvatar() internal view { require( address(dao.avatar()) == msg.sender, "only avatar can call this method" ); } function setAddress(string memory name, address addr) external { _onlyAvatar(); addresses[keccak256(bytes(name))] = addr; emit AddressChanged(name, addr); } function setAddresses(bytes32[] calldata hash, address[] calldata addrs) external { _onlyAvatar(); for (uint256 i = 0; i < hash.length; i++) { addresses[hash[i]] = addrs[i]; } } function getAddress(string memory name) external view returns (address) { return addresses[keccak256(bytes(name))]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface Avatar { function nativeToken() external view returns (address); function nativeReputation() external view returns (address); function owner() external view returns (address); } interface Controller { event RegisterScheme(address indexed _sender, address indexed _scheme); event UnregisterScheme(address indexed _sender, address indexed _scheme); function genericCall( address _contract, bytes calldata _data, address _avatar, uint256 _value ) external returns (bool, bytes memory); function avatar() external view returns (address); function unregisterScheme(address _scheme, address _avatar) external returns (bool); function unregisterSelf(address _avatar) external returns (bool); function registerScheme( address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar ) external returns (bool); function isSchemeRegistered(address _scheme, address _avatar) external view returns (bool); function getSchemePermissions(address _scheme, address _avatar) external view returns (bytes4); function addGlobalConstraint( address _constraint, bytes32 _paramHash, address _avatar ) external returns (bool); function mintTokens( uint256 _amount, address _beneficiary, address _avatar ) external returns (bool); function externalTokenTransfer( address _token, address _recipient, uint256 _amount, address _avatar ) external returns (bool); function sendEther( uint256 _amountInWei, address payable _to, address _avatar ) external returns (bool); } interface GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function pre( address _scheme, bytes32 _params, bytes32 _method ) external returns (bool); /** * @dev when return if this globalConstraints is pre, post or both. * @return CallPhase enum indication Pre, Post or PreAndPost. */ function when() external returns (CallPhase); } interface ReputationInterface { function balanceOf(address _user) external view returns (uint256); function balanceOfAt(address _user, uint256 _blockNumber) external view returns (uint256); function getVotes(address _user) external view returns (uint256); function getVotesAt( address _user, bool _global, uint256 _blockNumber ) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupplyAt(uint256 _blockNumber) external view returns (uint256); function delegateOf(address _user) external returns (address); } interface SchemeRegistrar { function proposeScheme( Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) external returns (bytes32); event NewSchemeProposal( address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); } interface IntVoteInterface { event NewProposal( bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event ExecuteProposal( bytes32 indexed _proposalId, address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VoteProposal( bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CancelProposal( bytes32 indexed _proposalId, address indexed _organization ); event CancelVoting( bytes32 indexed _proposalId, address indexed _organization, address indexed _voter ); /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _proposalParameters defines the parameters of the voting machine used for this proposal * @param _proposer address * @param _organization address - if this address is zero the msg.sender will be used as the organization address. * @return proposal's id. */ function propose( uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns (bytes32); function vote( bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns (bool); function cancelVote(bytes32 _proposalId) external; function getNumberOfChoices(bytes32 _proposalId) external view returns (uint256); function isVotable(bytes32 _proposalId) external view returns (bool); /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns (uint256); /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns (bool); /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns (uint256 min, uint256 max); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../utils/DSMath.sol"; import "../utils/BancorFormula.sol"; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; import "../utils/DAOUpgradeableContract.sol"; /** @title Dynamic reserve ratio market maker */ contract GoodMarketMaker is DAOUpgradeableContract, DSMath { // Entity that holds a reserve token struct ReserveToken { // Determines the reserve token balance // that the reserve contract holds uint256 reserveSupply; // Determines the current ratio between // the reserve token and the GD token uint32 reserveRatio; // How many GD tokens have been minted // against that reserve token uint256 gdSupply; //last time reserve ratio was expanded uint256 lastExpansion; } // The map which holds the reserve token entities mapping(address => ReserveToken) public reserveTokens; // Emits when a change has occurred in a // reserve balance, i.e. buy / sell will // change the balance event BalancesUpdated( // The account who initiated the action address indexed caller, // The address of the reserve token address indexed reserveToken, // The incoming amount uint256 amount, // The return value uint256 returnAmount, // The updated total supply uint256 totalSupply, // The updated reserve balance uint256 reserveBalance ); // Emits when the ratio changed. The caller should be the Avatar by definition event ReserveRatioUpdated(address indexed caller, uint256 nom, uint256 denom); // Defines the daily change in the reserve ratio in RAY precision. // In the current release, only global ratio expansion is supported. // That will be a part of each reserve token entity in the future. uint256 public reserveRatioDailyExpansion; //goodDollar token decimals uint256 decimals; /** * @dev Constructor * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function initialize( INameService _ns, uint256 _nom, uint256 _denom ) public virtual initializer { reserveRatioDailyExpansion = (_nom * 1e27) / _denom; decimals = 2; setDAO(_ns); } function _onlyActiveToken(ERC20 _token) internal view { ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > 0, "Reserve token not initialized"); } function _onlyReserveOrAvatar() internal view { require( nameService.getAddress("RESERVE") == msg.sender || nameService.getAddress("AVATAR") == msg.sender, "GoodMarketMaker: not Reserve or Avatar" ); } function getBancor() public view returns (BancorFormula) { return BancorFormula(nameService.getAddress("BANCOR_FORMULA")); } /** * @dev Allows the DAO to change the daily expansion rate * it is calculated by _nom/_denom with e27 precision. Emits * `ReserveRatioUpdated` event after the ratio has changed. * Only Avatar can call this method. * @param _nom The numerator to calculate the global `reserveRatioDailyExpansion` from * @param _denom The denominator to calculate the global `reserveRatioDailyExpansion` from */ function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public { _onlyReserveOrAvatar(); require(_denom > 0, "denominator must be above 0"); reserveRatioDailyExpansion = (_nom * 1e27) / _denom; require(reserveRatioDailyExpansion < 1e27, "Invalid nom or denom value"); emit ReserveRatioUpdated(msg.sender, _nom, _denom); } // NOTICE: In the current release, if there is a wish to add another reserve token, // `end` method in the reserve contract should be called first. Then, the DAO have // to deploy a new reserve contract that will own the market maker. A scheme for // updating the new reserve must be deployed too. /** * @dev Initialize a reserve token entity with the given parameters * @param _token The reserve token * @param _gdSupply Initial supply of GD to set the price * @param _tokenSupply Initial supply of reserve token to set the price * @param _reserveRatio The starting reserve ratio */ function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio ) public { _onlyReserveOrAvatar(); reserveTokens[address(_token)] = ReserveToken({ gdSupply: _gdSupply, reserveSupply: _tokenSupply, reserveRatio: _reserveRatio, lastExpansion: block.timestamp }); } /** * @dev Calculates how much to decrease the reserve ratio for _token by * the `reserveRatioDailyExpansion` * @param _token The reserve token to calculate the reserve ratio for * @return The new reserve ratio */ function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 ratio = uint256(reserveToken.reserveRatio); if (ratio == 0) { ratio = 1e6; } ratio *= 1e21; //expand to e27 precision uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) / 1 days; for (uint256 i = 0; i < daysPassed; i++) { ratio = (ratio * reserveRatioDailyExpansion) / 1e27; } return uint32(ratio / 1e21); // return to e6 precision } /** * @dev Decreases the reserve ratio for _token by the `reserveRatioDailyExpansion` * @param _token The token to change the reserve ratio for * @return The new reserve ratio */ function expandReserveRatio(ERC20 _token) public returns (uint32) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } reserveToken.reserveRatio = calculateNewReserveRatio(_token); //set last expansion to begining of expansion day reserveToken.lastExpansion = block.timestamp - ((block.timestamp - reserveToken.lastExpansion) % 1 days); return reserveToken.reserveRatio; } /** * @dev Calculates the buy return in GD according to the given _tokenAmount * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return Number of GD that should be given in exchange as calculated by the bonding curve */ function buyReturn(ERC20 _token, uint256 _tokenAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculatePurchaseReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _tokenAmount ); } /** * @dev Calculates the sell return in _token according to the given _gdAmount * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @return Number of tokens that should be given in exchange as calculated by the bonding curve */ function sellReturn(ERC20 _token, uint256 _gdAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _gdAmount ); } /** * @dev Updates the _token bonding curve params. Emits `BalancesUpdated` with the * new reserve token information. * @param _token The reserve token buying with * @param _tokenAmount The amount of reserve token buying with * @return (gdReturn) Number of GD that will be given in exchange as calculated by the bonding curve */ function buy(ERC20 _token, uint256 _tokenAmount) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 gdReturn = buyReturn(_token, _tokenAmount); ReserveToken storage rtoken = reserveTokens[address(_token)]; rtoken.gdSupply += gdReturn; rtoken.reserveSupply += _tokenAmount; emit BalancesUpdated( msg.sender, address(_token), _tokenAmount, gdReturn, rtoken.gdSupply, rtoken.reserveSupply ); return gdReturn; } /** * @dev Updates the bonding curve params. Decrease RR to in order to mint gd in the amount of provided * new RR = Reserve supply / ((gd supply + gd mint amount) * price) * @param _gdAmount Amount of gd to add reserveParams * @param _token The reserve token which is currently active */ function mintFromReserveRatio(ERC20 _token, uint256 _gdAmount) public { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision ReserveToken storage rtoken = reserveTokens[address(_token)]; uint256 priceBeforeGdSupplyChange = currentPrice(_token); rtoken.gdSupply += _gdAmount; rtoken.reserveRatio = uint32( ((rtoken.reserveSupply * 1e27) / (rtoken.gdSupply * priceBeforeGdSupplyChange)) / 10**reserveDecimalsDiff ); // Divide it decimal diff to bring it proper decimal } /** * @dev Calculates the sell return with contribution in _token and update the bonding curve params. * Emits `BalancesUpdated` with the new reserve token information. * @param _token The desired reserve token to have * @param _gdAmount The amount of GD that are sold * @param _contributionGdAmount The number of GD tokens that will not be traded for the reserve token * @return Number of tokens that will be given in exchange as calculated by the bonding curve */ function sellWithContribution( ERC20 _token, uint256 _gdAmount, uint256 _contributionGdAmount ) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); require( _gdAmount >= _contributionGdAmount, "GD amount is lower than the contribution amount" ); ReserveToken storage rtoken = reserveTokens[address(_token)]; require( rtoken.gdSupply >= _gdAmount, "GD amount is higher than the total supply" ); // Deduces the convertible amount of GD tokens by the given contribution amount uint256 amountAfterContribution = _gdAmount - _contributionGdAmount; // The return value after the deduction uint256 tokenReturn = sellReturn(_token, amountAfterContribution); rtoken.gdSupply -= _gdAmount; rtoken.reserveSupply -= tokenReturn; emit BalancesUpdated( msg.sender, address(_token), _contributionGdAmount, tokenReturn, rtoken.gdSupply, rtoken.reserveSupply ); return tokenReturn; } /** * @dev Current price of GD in `token`. currently only cDAI is supported. * @param _token The desired reserve token to have * @return price of GD */ function currentPrice(ERC20 _token) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, (10**decimals) ); } //TODO: need real calculation and tests /** * @dev Calculates how much G$ to mint based on added token supply (from interest) * and on current reserve ratio, in order to keep G$ price the same at the bonding curve * formula to calculate the gd to mint: gd to mint = * addreservebalance * (gdsupply / (reservebalance * reserveratio)) * @param _token the reserve token * @param _addTokenSupply amount of token added to supply * @return how much to mint in order to keep price in bonding curve the same */ function calculateMintInterest(ERC20 _token, uint256 _addTokenSupply) public view returns (uint256) { uint256 decimalsDiff = uint256(27) - decimals; //resulting amount is in RAY precision //we divide by decimalsdiff to get precision in GD (2 decimals) return ((_addTokenSupply * 1e27) / currentPrice(_token)) / (10**decimalsDiff); } /** * @dev Updates bonding curve based on _addTokenSupply and new minted amount * @param _token The reserve token * @param _addTokenSupply Amount of token added to supply * @return How much to mint in order to keep price in bonding curve the same */ function mintInterest(ERC20 _token, uint256 _addTokenSupply) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); if (_addTokenSupply == 0) { return 0; } uint256 toMint = calculateMintInterest(_token, _addTokenSupply); ReserveToken storage reserveToken = reserveTokens[address(_token)]; reserveToken.gdSupply += toMint; reserveToken.reserveSupply += _addTokenSupply; return toMint; } /** * @dev Calculate how much G$ to mint based on expansion change (new reserve * ratio), in order to keep G$ price the same at the bonding curve. the * formula to calculate the gd to mint: gd to mint = * (reservebalance / (newreserveratio * currentprice)) - gdsupply * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function calculateMintExpansion(ERC20 _token) public view returns (uint256) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint32 newReserveRatio = calculateNewReserveRatio(_token); // new reserve ratio uint256 reserveDecimalsDiff = uint256(27) - _token.decimals(); // //result is in RAY precision uint256 denom = (uint256(newReserveRatio) * 1e21 * currentPrice(_token) * (10**reserveDecimalsDiff)) / 1e27; // (newreserveratio * currentprice) in RAY precision uint256 gdDecimalsDiff = uint256(27) - decimals; uint256 toMint = ((reserveToken.reserveSupply * (10**reserveDecimalsDiff) * 1e27) / denom) / (10**gdDecimalsDiff); // reservebalance in RAY precision // return to gd precision return toMint - reserveToken.gdSupply; } /** * @dev Updates bonding curve based on expansion change and new minted amount * @param _token The reserve token * @return How much to mint in order to keep price in bonding curve the same */ function mintExpansion(ERC20 _token) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 toMint = calculateMintExpansion(_token); reserveTokens[address(_token)].gdSupply += toMint; expandReserveRatio(_token); return toMint; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.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 Contracts guidelines: functions revert * instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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 virtual 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 virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(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 += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(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 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 {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @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 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @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"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // 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 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 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 "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); } // 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 "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // 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; if (lastIndex != toDeleteIndex) { 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] = valueIndex; // Replace lastvalue's index to valueIndex } // 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) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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(uint160(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(uint160(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(uint160(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(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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 Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // 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; /** * @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; 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 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 "../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; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; /** @title Simple contract that keeps DAO contracts registery */ contract DAOContract { Controller public dao; address public avatar; INameService public nameService; function _onlyAvatar() internal view { require( address(dao.avatar()) == msg.sender, "only avatar can call this method" ); } function setDAO(INameService _ns) internal { nameService = _ns; updateAvatar(); } function updateAvatar() public { dao = Controller(nameService.getAddress("CONTROLLER")); avatar = dao.avatar(); } function nativeToken() public view returns (IGoodDollar) { return IGoodDollar(nameService.getAddress("GOODDOLLAR")); } uint256[50] private gap; } // 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; /** * @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.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; /** * @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; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } enum InterestRateMode { NONE, STABLE, VARIABLE } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; contract BancorFormula { using SafeMathUpgradeable for uint256; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; // Auto-generated via 'PrintIntScalingFactors.py' uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; // Auto-generated via 'PrintLn2ScalingFactors.py' uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; // Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; // Auto-generated via 'PrintLambertFactors.py' uint256 private constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86; uint256 private constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306; uint256 private constant LAMBERT_POS2_MAXVAL = 0x01af16ac6c59de6f8d5d6f63c1482a7c80; uint256 private constant LAMBERT_POS3_MAXVAL = 0x6b22d43e72c326539cceeef8bb48f255ff; // Auto-generated via 'PrintWeightFactors.py' uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9; // Auto-generated via 'PrintMaxExpArray.py' uint256[128] private maxExpArray; function initMaxExpArray() private { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } // Auto-generated via 'PrintLambertArray.py' uint256[128] private lambertArray; function initLambertArray() private { lambertArray[0] = 0x60e393c68d20b1bd09deaabc0373b9c5; lambertArray[1] = 0x5f8f46e4854120989ed94719fb4c2011; lambertArray[2] = 0x5e479ebb9129fb1b7e72a648f992b606; lambertArray[3] = 0x5d0bd23fe42dfedde2e9586be12b85fe; lambertArray[4] = 0x5bdb29ddee979308ddfca81aeeb8095a; lambertArray[5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad; lambertArray[6] = 0x5998b31359a55d48724c65cf09001221; lambertArray[7] = 0x5885bcad2b322dfc43e8860f9c018cf5; lambertArray[8] = 0x577b97aa1fe222bb452fdf111b1f0be2; lambertArray[9] = 0x5679cb5e3575632e5baa27e2b949f704; lambertArray[10] = 0x557fe8241b3a31c83c732f1cdff4a1c5; lambertArray[11] = 0x548d868026504875d6e59bbe95fc2a6b; lambertArray[12] = 0x53a2465ce347cf34d05a867c17dd3088; lambertArray[13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc; lambertArray[14] = 0x51dfcb453c07f8da817606e7885f7c3e; lambertArray[15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce; lambertArray[16] = 0x5035f241d6eae0cd7bacba119993de7b; lambertArray[17] = 0x4f698fe90d5b53d532171e1210164c66; lambertArray[18] = 0x4ea288ca297a0e6a09a0eee240e16c85; lambertArray[19] = 0x4de0a13fdcf5d4213fc398ba6e3becde; lambertArray[20] = 0x4d23a145eef91fec06b06140804c4808; lambertArray[21] = 0x4c6b5430d4c1ee5526473db4ae0f11de; lambertArray[22] = 0x4bb7886c240562eba11f4963a53b4240; lambertArray[23] = 0x4b080f3f1cb491d2d521e0ea4583521e; lambertArray[24] = 0x4a5cbc96a05589cb4d86be1db3168364; lambertArray[25] = 0x49b566d40243517658d78c33162d6ece; lambertArray[26] = 0x4911e6a02e5507a30f947383fd9a3276; lambertArray[27] = 0x487216c2b31be4adc41db8a8d5cc0c88; lambertArray[28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc; lambertArray[29] = 0x473cfce4871a2c40bc4f9e1c32b955d0; lambertArray[30] = 0x46a771ca578ab878485810e285e31c67; lambertArray[31] = 0x4615149718aed4c258c373dc676aa72d; lambertArray[32] = 0x4585c8b3f8fe489c6e1833ca47871384; lambertArray[33] = 0x44f972f174e41e5efb7e9d63c29ce735; lambertArray[34] = 0x446ff970ba86d8b00beb05ecebf3c4dc; lambertArray[35] = 0x43e9438ec88971812d6f198b5ccaad96; lambertArray[36] = 0x436539d11ff7bea657aeddb394e809ef; lambertArray[37] = 0x42e3c5d3e5a913401d86f66db5d81c2c; lambertArray[38] = 0x4264d2395303070ea726cbe98df62174; lambertArray[39] = 0x41e84a9a593bb7194c3a6349ecae4eea; lambertArray[40] = 0x416e1b785d13eba07a08f3f18876a5ab; lambertArray[41] = 0x40f6322ff389d423ba9dd7e7e7b7e809; lambertArray[42] = 0x40807cec8a466880ecf4184545d240a4; lambertArray[43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f; lambertArray[44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1; lambertArray[45] = 0x3f2bee253fd84594f54bcaafac383a13; lambertArray[46] = 0x3ebe654e95208bb9210c575c081c5958; lambertArray[47] = 0x3e52c1fc5665635b78ce1f05ad53c086; lambertArray[48] = 0x3de8f65ac388101ddf718a6f5c1eff65; lambertArray[49] = 0x3d80f522d59bd0b328ca012df4cd2d49; lambertArray[50] = 0x3d1ab193129ea72b23648a161163a85a; lambertArray[51] = 0x3cb61f68d32576c135b95cfb53f76d75; lambertArray[52] = 0x3c5332d9f1aae851a3619e77e4cc8473; lambertArray[53] = 0x3bf1e08edbe2aa109e1525f65759ef73; lambertArray[54] = 0x3b921d9cff13fa2c197746a3dfc4918f; lambertArray[55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4; lambertArray[56] = 0x3ad71c1c77e34fa32a9f184967eccbf6; lambertArray[57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a; lambertArray[58] = 0x3a21dec7e76369783a68a0c6385a1c57; lambertArray[59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3; lambertArray[60] = 0x39721bad3dc85d1240ff0190e0adaac3; lambertArray[61] = 0x391c324344d3248f0469eb28dd3d77e0; lambertArray[62] = 0x38c78df7e3c796279fb4ff84394ab3da; lambertArray[63] = 0x387426ea4638ae9aae08049d3554c20a; lambertArray[64] = 0x3821f57dbd2763256c1a99bbd2051378; lambertArray[65] = 0x37d0f256cb46a8c92ff62fbbef289698; lambertArray[66] = 0x37811658591ffc7abdd1feaf3cef9b73; lambertArray[67] = 0x37325aa10e9e82f7df0f380f7997154b; lambertArray[68] = 0x36e4b888cfb408d873b9a80d439311c6; lambertArray[69] = 0x3698299e59f4bb9de645fc9b08c64cca; lambertArray[70] = 0x364ca7a5012cb603023b57dd3ebfd50d; lambertArray[71] = 0x36022c928915b778ab1b06aaee7e61d4; lambertArray[72] = 0x35b8b28d1a73dc27500ffe35559cc028; lambertArray[73] = 0x357033e951fe250ec5eb4e60955132d7; lambertArray[74] = 0x3528ab2867934e3a21b5412e4c4f8881; lambertArray[75] = 0x34e212f66c55057f9676c80094a61d59; lambertArray[76] = 0x349c66289e5b3c4b540c24f42fa4b9bb; lambertArray[77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7; lambertArray[78] = 0x3413bad2e712288b924b5882b5b369bf; lambertArray[79] = 0x33d0b2b56286510ef730e213f71f12e9; lambertArray[80] = 0x338e82ce00e2496262c64457535ba1a1; lambertArray[81] = 0x334d26a96b373bb7c2f8ea1827f27a92; lambertArray[82] = 0x330c99f4f4211469e00b3e18c31475ea; lambertArray[83] = 0x32ccd87d6486094999c7d5e6f33237d8; lambertArray[84] = 0x328dde2dd617b6665a2e8556f250c1af; lambertArray[85] = 0x324fa70e9adc270f8262755af5a99af9; lambertArray[86] = 0x32122f443110611ca51040f41fa6e1e3; lambertArray[87] = 0x31d5730e42c0831482f0f1485c4263d8; lambertArray[88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1; lambertArray[89] = 0x315e1ee0a68ff46bb43ec2b85032e876; lambertArray[90] = 0x31237fe7bc4deacf6775b9efa1a145f8; lambertArray[91] = 0x30e98e7f1cc5a356e44627a6972ea2ff; lambertArray[92] = 0x30b04760b8917ec74205a3002650ec05; lambertArray[93] = 0x3077a75c803468e9132ce0cf3224241d; lambertArray[94] = 0x303fab57a6a275c36f19cda9bace667a; lambertArray[95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0; lambertArray[96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0; lambertArray[97] = 0x2f9b7169808c324b5852fd3d54ba9714; lambertArray[98] = 0x2f65e7e711cf4b064eea9c08cbdad574; lambertArray[99] = 0x2f30f405093042ddff8a251b6bf6d103; lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574; lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb; lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851; lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5; lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2; lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10; lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31; lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83; lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a; lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f; lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10; lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c; lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5; lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727; lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535; lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3; lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18; lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c; lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb; lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92; lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7; lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675; lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f; lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b; lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8; lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d; lambertArray[126] = 0x2a57741b18cde618717792b4faa216db; lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a; } /** * @dev should be executed after construction (too large for the constructor) */ function init() public { initMaxExpArray(); initLambertArray(); } /** * @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token), * calculates the target amount for a given conversion (in the main token) * * Formula: * return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1) * * @param _supply liquid token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of reserve tokens to get the target amount for * * @return target */ function purchaseTargetAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); // special case for 0 deposit amount if (_amount == 0) return 0; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power( baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT ); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a token supply, reserve balance, weight and a sell amount (in the main token), * calculates the target amount for a given conversion (in the reserve token) * * Formula: * return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight)) * * @param _supply liquid token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of liquid tokens to get the target amount for * * @return reserve token amount */ function saleTargetAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 sell amount if (_amount == 0) return 0; // special case for selling the entire supply if (_amount == _supply) return _reserveBalance; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _reserveBalance.mul(_amount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given two reserve balances/weights and a sell amount (in the first reserve token), * calculates the target amount for a conversion from the source reserve token to the target reserve token * * Formula: * return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight)) * * @param _sourceReserveBalance source reserve balance * @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000) * @param _targetReserveBalance target reserve balance * @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000) * @param _amount source reserve amount * * @return target reserve amount */ function crossReserveTargetAmount( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { // validate input require( _sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); require( _sourceReserveWeight > 0 && _sourceReserveWeight <= MAX_WEIGHT && _targetReserveWeight > 0 && _targetReserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" ); // special case for equal weights if (_sourceReserveWeight == _targetReserveWeight) return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _sourceReserveBalance.add(_amount); (result, precision) = power( baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight ); uint256 temp1 = _targetReserveBalance.mul(result); uint256 temp2 = _targetReserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of requested pool tokens, * calculates the amount of reserve tokens required for purchasing the given amount of pool tokens * * Formula: * return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount requested amount of pool tokens * * @return reserve token amount */ function fundCost( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return (_amount.mul(_reserveBalance) - 1) / _supply + 1; uint256 result; uint8 precision; uint256 baseN = _supply.add(_amount); (result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio); uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1; return temp - _reserveBalance; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with, * calculates the amount of pool tokens received for purchasing with the given amount of reserve tokens * * Formula: * return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of reserve tokens to fund with * * @return pool token amount */ function fundSupplyAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_supply) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _reserveBalance.add(_amount); (result, precision) = power( baseN, _reserveBalance, _reserveRatio, MAX_WEIGHT ); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a pool token supply, reserve balance, reserve ratio and an amount of pool tokens to liquidate, * calculates the amount of reserve tokens received for selling the given amount of pool tokens * * Formula: * return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio)) * * @param _supply pool token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of pool tokens to liquidate * * @return reserve token amount */ function liquidateReserveAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO" ); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (_amount == 0) return 0; // special case for liquidating the entire supply if (_amount == _supply) return _reserveBalance; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_reserveBalance) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price. * We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance. * In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance. * * Formula input: * - let t denote the primary reserve token staked balance * - let s denote the primary reserve token balance * - let r denote the secondary reserve token balance * - let q denote the numerator of the rate between the tokens * - let p denote the denominator of the rate between the tokens * Where p primary tokens are equal to q secondary tokens * * Formula output: * - compute x = W(t / r * q / p * log(s / t)) / log(s / t) * - return x / (1 + x) as the weight of the primary reserve token * - return 1 / (1 + x) as the weight of the secondary reserve token * Where W is the Lambert W Function * * If the rate-provider provides the rates for a common unit, for example: * - P = 2 ==> 2 primary reserve tokens = 1 ether * - Q = 3 ==> 3 secondary reserve tokens = 1 ether * Then you can simply use p = P and q = Q * * If the rate-provider provides the rates for a single unit, for example: * - P = 2 ==> 1 primary reserve token = 2 ethers * - Q = 3 ==> 1 secondary reserve token = 3 ethers * Then you can simply use p = Q and q = P * * @param _primaryReserveStakedBalance the primary reserve token staked balance * @param _primaryReserveBalance the primary reserve token balance * @param _secondaryReserveBalance the secondary reserve token balance * @param _reserveRateNumerator the numerator of the rate between the tokens * @param _reserveRateDenominator the denominator of the rate between the tokens * * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token * * @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000) */ function balancedWeights( uint256 _primaryReserveStakedBalance, uint256 _primaryReserveBalance, uint256 _secondaryReserveBalance, uint256 _reserveRateNumerator, uint256 _reserveRateDenominator ) public view returns (uint32, uint32) { if (_primaryReserveStakedBalance == _primaryReserveBalance) require( _primaryReserveStakedBalance > 0 || _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); else require( _primaryReserveStakedBalance > 0 && _primaryReserveBalance > 0 && _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE" ); require( _reserveRateNumerator > 0 && _reserveRateDenominator > 0, "ERR_INVALID_RESERVE_RATE" ); uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator); uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator); if (_primaryReserveStakedBalance < _primaryReserveBalance) return balancedWeightsByStake( _primaryReserveBalance, _primaryReserveStakedBalance, tq, rp, true ); if (_primaryReserveStakedBalance > _primaryReserveBalance) return balancedWeightsByStake( _primaryReserveStakedBalance, _primaryReserveBalance, tq, rp, false ); return normalizedWeights(tq, rp); } /** * @dev General Description: * Determine a value of precision. * Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. * Return the result along with the precision used. * * Detailed Description: * Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". * The larger "precision" is, the more accurately this value represents the real value. * However, the larger "precision" is, the more bits are required in order to store this value. * And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). * This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". * Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. * This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power( uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD ) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = (_baseN * FIXED_1) / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = (baseLog * _expN) / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return ( generalExp( baseLogTimesExp >> (MAX_PRECISION - precision), precision ), precision ); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return (res * LN2_NUMERATOR) / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) { res += 0x40000000000000000000000000000000; x = (x * FIXED_1) / 0xd3094c70f034de4b96ff7d5b6f99fcd8; } // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) { res += 0x20000000000000000000000000000000; x = (x * FIXED_1) / 0xa45af1e1f40c333b3de1db4dd55f29a7; } // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) { res += 0x10000000000000000000000000000000; x = (x * FIXED_1) / 0x910b022db7ae67ce76b441c27035c6a1; } // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) { res += 0x08000000000000000000000000000000; x = (x * FIXED_1) / 0x88415abbe9a76bead8d00cf112e4d4a8; } // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) { res += 0x04000000000000000000000000000000; x = (x * FIXED_1) / 0x84102b00893f64c705e841d5d4064bd3; } // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) { res += 0x02000000000000000000000000000000; x = (x * FIXED_1) / 0x8204055aaef1c8bd5c3259f4822735a2; } // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) { res += 0x01000000000000000000000000000000; x = (x * FIXED_1) / 0x810100ab00222d861931c15e39b44e99; } // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) { res += 0x00800000000000000000000000000000; x = (x * FIXED_1) / 0x808040155aabbbe9451521693554f733; } // add 1 / 2^8 z = y = x - FIXED_1; w = (y * y) / FIXED_1; res += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02 res += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04 res += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06 res += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08 res += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10 res += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12 res += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000; z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14 res += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = (z * y) / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = (z * y) / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = (z * y) / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = (z * y) / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = (z * y) / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = (z * y) / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = (z * y) / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = (z * y) / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = (z * y) / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = (z * y) / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = (z * y) / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = (z * y) / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = (z * y) / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = (z * y) / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = (z * y) / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = (z * y) / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = (z * y) / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = (z * y) / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = (res * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = (res * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = (res * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = (res * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = (res * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = (res * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = (res * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 */ function lowerStake(uint256 _x) internal view returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertPos1(_x); if (_x <= LAMBERT_POS2_MAXVAL) return lambertPos2(_x); if (_x <= LAMBERT_POS3_MAXVAL) return lambertPos3(_x); require(false); } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 */ function higherStake(uint256 _x) internal pure returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertNeg1(_x); return (FIXED_1 * FIXED_1) / _x; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertPos1.py' */ function lambertPos1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34! } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL */ function lambertPos2(uint256 _x) internal view returns (uint256) { uint256 x = _x - LAMBERT_CONV_RADIUS - 1; uint256 i = x / LAMBERT_POS2_SAMPLE; uint256 a = LAMBERT_POS2_SAMPLE * i; uint256 b = LAMBERT_POS2_SAMPLE * (i + 1); uint256 c = lambertArray[i]; uint256 d = lambertArray[i + 1]; return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL */ function lambertPos3(uint256 _x) internal pure returns (uint256) { uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x); uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1); return ((l1 - l2 + (l2 * FIXED_1) / l1) * FIXED_1) / _x; } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertNeg1.py' */ function lambertNeg1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!) } /** * @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function. */ function balancedWeightsByStake( uint256 _hi, uint256 _lo, uint256 _tq, uint256 _rp, bool _lowerStake ) internal view returns (uint32, uint32) { (_tq, _rp) = safeFactors(_tq, _rp); uint256 f = _hi.mul(FIXED_1) / _lo; uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f); uint256 x = g.mul(_tq) / _rp; uint256 y = _lowerStake ? lowerStake(x) : higherStake(x); return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1)); } /** * @dev reduces "a" and "b" while maintaining their ratio. */ function safeFactors(uint256 _a, uint256 _b) internal pure returns (uint256, uint256) { if (_a <= FIXED_2 && _b <= FIXED_2) return (_a, _b); if (_a < FIXED_2) return ((_a * FIXED_2) / _b, FIXED_2); if (_b < FIXED_2) return (FIXED_2, (_b * FIXED_2) / _a); uint256 c = _a > _b ? _a : _b; uint256 n = floorLog2(c / FIXED_1); return (_a >> n, _b >> n); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)". */ function normalizedWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a <= _b) return accurateWeights(_a, _b); (uint32 y, uint32 x) = accurateWeights(_b, _a); return (x, y); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b". */ function accurateWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a > MAX_UNF_WEIGHT) { uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b)); uint256 y = MAX_WEIGHT - x; return (uint32(x), uint32(y)); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + (_n % _d) / (_d - _d / 2); } /** * @dev deprecated, backward compatibility */ function calculatePurchaseReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return purchaseTargetAmount( _supply, _reserveBalance, _reserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateSaleReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateCrossReserveReturn( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateCrossConnectorReturn( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function calculateFundCost( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return fundCost(_supply, _reserveBalance, _reserveRatio, _amount); } /** * @dev deprecated, backward compatibility */ function calculateLiquidateReturn( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return liquidateReserveAmount( _supply, _reserveBalance, _reserveRatio, _amount ); } /** * @dev deprecated, backward compatibility */ function purchaseRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return purchaseTargetAmount( _supply, _reserveBalance, _reserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function saleRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function crossReserveRate( uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount ) public view returns (uint256) { return crossReserveTargetAmount( _sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount ); } /** * @dev deprecated, backward compatibility */ function liquidateRate( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { return liquidateReserveAmount( _supply, _reserveBalance, _reserveRatio, _amount ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @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) { unchecked { 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) { unchecked { 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) { unchecked { // 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) { unchecked { 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) { unchecked { 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) { return a + b; } /** * @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 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) { return a * b; } /** * @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. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { 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) { 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) { unchecked { 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. * * 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) { unchecked { 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) { unchecked { require(b > 0, errorMessage); return a % b; } } }
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being generated by calculating keccak256 of a incremented counter. @param _numOfChoices number of voting choices @param _proposalParameters defines the parameters of the voting machine used for this proposal @param _proposer address @param _organization address - if this address is zero the msg.sender will be used as the organization address. @return proposal's id./* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. @param _proposalId the ID of the proposal @param _choice the index in the @return voted reputation for the given choice/* @dev isAbstainAllow returns if the voting machine allow abstain (0) @return bool true or false/* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. @return min - minimum number of choices/ SPDX-License-Identifier: MIT*/ Entity that holds a reserve token
contract GoodMarketMaker is DAOUpgradeableContract, DSMath { function pre( address _scheme, bytes32 _params, bytes32 _method ) external returns (bool); function when() external returns (CallPhase); } } } } pragma solidity >=0.8.0; import "../utils/DSMath.sol"; import "../utils/BancorFormula.sol"; import "../DAOStackInterfaces.sol"; import "../Interfaces.sol"; import "../utils/DAOUpgradeableContract.sol"; @title Dynamic reserve ratio market maker struct ReserveToken { uint256 reserveSupply; uint32 reserveRatio; uint256 gdSupply; uint256 lastExpansion; } ); mapping(address => ReserveToken) public reserveTokens; event BalancesUpdated( address indexed caller, address indexed reserveToken, uint256 amount, uint256 returnAmount, uint256 totalSupply, uint256 reserveBalance event ReserveRatioUpdated(address indexed caller, uint256 nom, uint256 denom); uint256 public reserveRatioDailyExpansion; uint256 decimals; function initialize( INameService _ns, uint256 _nom, uint256 _denom ) public virtual initializer { reserveRatioDailyExpansion = (_nom * 1e27) / _denom; decimals = 2; setDAO(_ns); } function _onlyActiveToken(ERC20 _token) internal view { ReserveToken storage rtoken = reserveTokens[address(_token)]; require(rtoken.gdSupply > 0, "Reserve token not initialized"); } function _onlyReserveOrAvatar() internal view { require( nameService.getAddress("RESERVE") == msg.sender || nameService.getAddress("AVATAR") == msg.sender, "GoodMarketMaker: not Reserve or Avatar" ); } function getBancor() public view returns (BancorFormula) { return BancorFormula(nameService.getAddress("BANCOR_FORMULA")); } function setReserveRatioDailyExpansion(uint256 _nom, uint256 _denom) public { _onlyReserveOrAvatar(); require(_denom > 0, "denominator must be above 0"); reserveRatioDailyExpansion = (_nom * 1e27) / _denom; require(reserveRatioDailyExpansion < 1e27, "Invalid nom or denom value"); emit ReserveRatioUpdated(msg.sender, _nom, _denom); } function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio ) public { _onlyReserveOrAvatar(); reserveTokens[address(_token)] = ReserveToken({ gdSupply: _gdSupply, reserveSupply: _tokenSupply, reserveRatio: _reserveRatio, lastExpansion: block.timestamp }); } function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio ) public { _onlyReserveOrAvatar(); reserveTokens[address(_token)] = ReserveToken({ gdSupply: _gdSupply, reserveSupply: _tokenSupply, reserveRatio: _reserveRatio, lastExpansion: block.timestamp }); } function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 ratio = uint256(reserveToken.reserveRatio); if (ratio == 0) { ratio = 1e6; } uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) / 1 days; for (uint256 i = 0; i < daysPassed; i++) { ratio = (ratio * reserveRatioDailyExpansion) / 1e27; } } function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 ratio = uint256(reserveToken.reserveRatio); if (ratio == 0) { ratio = 1e6; } uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) / 1 days; for (uint256 i = 0; i < daysPassed; i++) { ratio = (ratio * reserveRatioDailyExpansion) / 1e27; } } function calculateNewReserveRatio(ERC20 _token) public view returns (uint32) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 ratio = uint256(reserveToken.reserveRatio); if (ratio == 0) { ratio = 1e6; } uint256 daysPassed = (block.timestamp - reserveToken.lastExpansion) / 1 days; for (uint256 i = 0; i < daysPassed; i++) { ratio = (ratio * reserveRatioDailyExpansion) / 1e27; } } function expandReserveRatio(ERC20 _token) public returns (uint32) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } reserveToken.reserveRatio = calculateNewReserveRatio(_token); block.timestamp - ((block.timestamp - reserveToken.lastExpansion) % 1 days); return reserveToken.reserveRatio; } function expandReserveRatio(ERC20 _token) public returns (uint32) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); ReserveToken storage reserveToken = reserveTokens[address(_token)]; uint32 ratio = reserveToken.reserveRatio; if (ratio == 0) { ratio = 1e6; } reserveToken.reserveRatio = calculateNewReserveRatio(_token); block.timestamp - ((block.timestamp - reserveToken.lastExpansion) % 1 days); return reserveToken.reserveRatio; } reserveToken.lastExpansion = function buyReturn(ERC20 _token, uint256 _tokenAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculatePurchaseReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _tokenAmount ); } function sellReturn(ERC20 _token, uint256 _gdAmount) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, _gdAmount ); } function buy(ERC20 _token, uint256 _tokenAmount) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 gdReturn = buyReturn(_token, _tokenAmount); ReserveToken storage rtoken = reserveTokens[address(_token)]; rtoken.gdSupply += gdReturn; rtoken.reserveSupply += _tokenAmount; emit BalancesUpdated( msg.sender, address(_token), _tokenAmount, gdReturn, rtoken.gdSupply, rtoken.reserveSupply ); return gdReturn; } function mintFromReserveRatio(ERC20 _token, uint256 _gdAmount) public { _onlyReserveOrAvatar(); _onlyActiveToken(_token); ReserveToken storage rtoken = reserveTokens[address(_token)]; uint256 priceBeforeGdSupplyChange = currentPrice(_token); rtoken.gdSupply += _gdAmount; rtoken.reserveRatio = uint32( ((rtoken.reserveSupply * 1e27) / (rtoken.gdSupply * priceBeforeGdSupplyChange)) / 10**reserveDecimalsDiff } function sellWithContribution( ERC20 _token, uint256 _gdAmount, uint256 _contributionGdAmount ) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); require( _gdAmount >= _contributionGdAmount, "GD amount is lower than the contribution amount" ); ReserveToken storage rtoken = reserveTokens[address(_token)]; require( rtoken.gdSupply >= _gdAmount, "GD amount is higher than the total supply" ); uint256 amountAfterContribution = _gdAmount - _contributionGdAmount; uint256 tokenReturn = sellReturn(_token, amountAfterContribution); rtoken.gdSupply -= _gdAmount; rtoken.reserveSupply -= tokenReturn; emit BalancesUpdated( msg.sender, address(_token), _contributionGdAmount, tokenReturn, rtoken.gdSupply, rtoken.reserveSupply ); return tokenReturn; } function currentPrice(ERC20 _token) public view returns (uint256) { ReserveToken memory rtoken = reserveTokens[address(_token)]; return getBancor().calculateSaleReturn( rtoken.gdSupply, rtoken.reserveSupply, rtoken.reserveRatio, (10**decimals) ); } function calculateMintInterest(ERC20 _token, uint256 _addTokenSupply) public view returns (uint256) { uint256 decimalsDiff = uint256(27) - decimals; return ((_addTokenSupply * 1e27) / currentPrice(_token)) / (10**decimalsDiff); } function mintInterest(ERC20 _token, uint256 _addTokenSupply) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); if (_addTokenSupply == 0) { return 0; } uint256 toMint = calculateMintInterest(_token, _addTokenSupply); ReserveToken storage reserveToken = reserveTokens[address(_token)]; reserveToken.gdSupply += toMint; reserveToken.reserveSupply += _addTokenSupply; return toMint; } function mintInterest(ERC20 _token, uint256 _addTokenSupply) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); if (_addTokenSupply == 0) { return 0; } uint256 toMint = calculateMintInterest(_token, _addTokenSupply); ReserveToken storage reserveToken = reserveTokens[address(_token)]; reserveToken.gdSupply += toMint; reserveToken.reserveSupply += _addTokenSupply; return toMint; } function calculateMintExpansion(ERC20 _token) public view returns (uint256) { ReserveToken memory reserveToken = reserveTokens[address(_token)]; uint256 denom = (uint256(newReserveRatio) * 1e21 * currentPrice(_token) * uint256 gdDecimalsDiff = uint256(27) - decimals; uint256 toMint = ((reserveToken.reserveSupply * (10**reserveDecimalsDiff) * return toMint - reserveToken.gdSupply; } function mintExpansion(ERC20 _token) public returns (uint256) { _onlyReserveOrAvatar(); _onlyActiveToken(_token); uint256 toMint = calculateMintExpansion(_token); reserveTokens[address(_token)].gdSupply += toMint; expandReserveRatio(_token); return toMint; } }
14,636,523
[ 1, 4861, 279, 394, 14708, 598, 326, 864, 1472, 18, 16420, 14708, 711, 279, 3089, 1599, 1492, 353, 3832, 4374, 635, 21046, 417, 24410, 581, 5034, 434, 279, 28859, 3895, 18, 225, 389, 2107, 951, 17442, 1300, 434, 331, 17128, 7246, 225, 389, 685, 8016, 2402, 11164, 326, 1472, 434, 326, 331, 17128, 5228, 1399, 364, 333, 14708, 225, 389, 685, 5607, 1758, 225, 389, 15336, 1758, 300, 309, 333, 1758, 353, 3634, 326, 1234, 18, 15330, 903, 506, 1399, 487, 326, 6758, 1758, 18, 327, 14708, 1807, 612, 18, 19, 225, 12501, 1482, 1135, 326, 283, 458, 367, 331, 16474, 364, 279, 14708, 364, 279, 2923, 331, 17128, 6023, 18, 225, 389, 685, 8016, 548, 326, 1599, 434, 326, 14708, 225, 389, 11569, 326, 770, 316, 326, 327, 331, 16474, 283, 458, 367, 364, 326, 864, 6023, 19, 225, 353, 5895, 334, 530, 7009, 1135, 309, 326, 331, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 31732, 3882, 278, 12373, 353, 463, 20463, 10784, 429, 8924, 16, 463, 7303, 421, 288, 203, 202, 915, 675, 12, 203, 202, 202, 2867, 389, 9068, 16, 203, 202, 202, 3890, 1578, 389, 2010, 16, 203, 202, 202, 3890, 1578, 389, 2039, 203, 202, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 202, 915, 1347, 1435, 3903, 1135, 261, 1477, 11406, 1769, 203, 97, 203, 203, 97, 203, 203, 97, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 315, 6216, 5471, 19, 3948, 10477, 18, 18281, 14432, 203, 5666, 315, 6216, 5471, 19, 38, 304, 3850, 14972, 18, 18281, 14432, 203, 5666, 315, 6216, 18485, 2624, 10273, 18, 18281, 14432, 203, 5666, 315, 6216, 10273, 18, 18281, 14432, 203, 5666, 315, 6216, 5471, 19, 18485, 10784, 429, 8924, 18, 18281, 14432, 203, 203, 36, 2649, 12208, 20501, 7169, 13667, 312, 6388, 203, 202, 1697, 1124, 6527, 1345, 288, 203, 202, 202, 11890, 5034, 20501, 3088, 1283, 31, 203, 202, 202, 11890, 1578, 20501, 8541, 31, 203, 202, 202, 11890, 5034, 15551, 3088, 1283, 31, 203, 202, 202, 11890, 5034, 1142, 2966, 12162, 31, 203, 202, 97, 203, 203, 203, 202, 1769, 203, 203, 203, 203, 203, 202, 6770, 12, 2867, 516, 1124, 6527, 1345, 13, 1071, 20501, 5157, 31, 203, 202, 2575, 605, 26488, 7381, 12, 203, 202, 202, 2867, 8808, 4894, 16, 203, 202, 202, 2867, 8808, 20501, 1345, 16, 203, 202, 202, 11890, 5034, 3844, 16, 203, 202, 202, 2 ]
pragma solidity 0.4.25; pragma experimental ABIEncoderV2; /** * @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. * @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 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; } } library ERC20SafeTransfer { function safeTransfer(address _tokenAddress, address _to, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value)); return fetchReturnData(); } function safeTransferFrom(address _tokenAddress, address _from, address _to, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value)); return fetchReturnData(); } function safeApprove(address _tokenAddress, address _spender, uint256 _value) internal returns (bool success) { require(_tokenAddress.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value)); return fetchReturnData(); } function fetchReturnData() internal returns (bool success){ assembly { switch returndatasize() case 0 { success := 1 } case 32 { returndatacopy(0, 0, 32) success := mload(0) } default { revert(0, 0) } } } } /// @title A contract which allows its owner to withdraw any ether which is contained inside contract Withdrawable is Ownable { /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _token The address of the token that the user wants to withdraw /// @param _amount The amount of tokens that the caller wants to withdraw /// @return bool value indicating whether the transfer was successful function withdrawToken(address _token, uint256 _amount) external onlyOwner returns (bool) { return ERC20SafeTransfer.safeTransfer(_token, owner, _amount); } /// @notice Withdraw ether contained in this contract and send it back to owner /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _amount The amount of ether that the caller wants to withdraw function withdrawETH(uint256 _amount) external onlyOwner { owner.transfer(_amount); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function decimals() public view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /* Copyright 2018 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. */ /// @title TokenTransferProxy - Transfers tokens on behalf of contracts that have been approved via decentralized governance. /// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]> contract TokenTransferProxy is Ownable { /// @dev Only authorized addresses can invoke functions with this modifier. modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } mapping (address => bool) public authorized; address[] public authorities; event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); /* * Public functions */ /// @dev Authorizes an address. /// @param target Address to authorize. function addAuthorizedAddress(address target) public onlyOwner targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); emit LogAuthorizedAddressAdded(target, msg.sender); } /// @dev Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } emit LogAuthorizedAddressRemoved(target, msg.sender); } /// @dev Calls into ERC20 Token contract, invoking transferFrom. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. /// @return Success of transfer. function transferFrom( address token, address from, address to, uint value) public onlyAuthorized returns (bool) { require(ERC20SafeTransfer.safeTransferFrom(token, from, to, value)); return true; } /* * Public constant functions */ /// @dev Gets all authorized addresses. /// @return Array of authorized addresses. function getAuthorizedAddresses() public view returns (address[]) { return authorities; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Paused(); event Unpaused(); bool private _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, "Contract is paused."); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Contract not paused."); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(); } } /** * @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; } } /* Modified Util contract as used by Kyber Network */ library Utils { uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint256 constant internal MAX_DECIMALS = 18; uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_UINT = 2**256-1; // Currently constants can't be accessed from other contracts, so providing functions to do that here function precision() internal pure returns (uint256) { return PRECISION; } function max_qty() internal pure returns (uint256) { return MAX_QTY; } function max_rate() internal pure returns (uint256) { return MAX_RATE; } function max_decimals() internal pure returns (uint256) { return MAX_DECIMALS; } function eth_decimals() internal pure returns (uint256) { return ETH_DECIMALS; } function max_uint() internal pure returns (uint256) { return MAX_UINT; } /// @notice Retrieve the number of decimals used for a given ERC20 token /// @dev As decimals are an optional feature in ERC20, this contract uses `call` to /// ensure that an exception doesn't cause transaction failure /// @param token the token for which we should retrieve the decimals /// @return decimals the number of decimals in the given token function getDecimals(address token) internal view returns (uint256 decimals) { bytes4 functionSig = bytes4(keccak256("decimals()")); /// @dev Using assembly due to issues with current solidity `address.call()` /// implementation: https://github.com/ethereum/solidity/issues/2884 assembly { // Pointer to next free memory slot let ptr := mload(0x40) // Store functionSig variable at ptr mstore(ptr,functionSig) let functionSigLength := 0x04 let wordLength := 0x20 let success := call( 5000, // Amount of gas token, // Address to call 0, // ether to send ptr, // ptr to input data functionSigLength, // size of data ptr, // where to store output data (overwrite input) wordLength // size of output data (32 bytes) ) switch success case 0 { decimals := 0 // If the token doesn't implement `decimals()`, return 0 as default } case 1 { decimals := mload(ptr) // Set decimals to return data from call } mstore(0x40,add(ptr,0x04)) // Reset the free memory pointer to the next known free location } } /// @dev Checks that a given address has its token allowance and balance set above the given amount /// @param tokenOwner the address which should have custody of the token /// @param tokenAddress the address of the token to check /// @param tokenAmount the amount of the token which should be set /// @param addressToAllow the address which should be allowed to transfer the token /// @return bool true if the allowance and balance is set, false if not function tokenAllowanceAndBalanceSet( address tokenOwner, address tokenAddress, uint256 tokenAmount, address addressToAllow ) internal view returns (bool) { return ( ERC20(tokenAddress).allowance(tokenOwner, addressToAllow) >= tokenAmount && ERC20(tokenAddress).balanceOf(tokenOwner) >= tokenAmount ); } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) { if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns (uint) { //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns (uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns (uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns (uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /// @notice Bringing this in from the Math library as we've run out of space in TotlePrimary (see EIP-170) function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract ErrorReporter { function revertTx(string reason) public pure { revert(reason); } } contract Affiliate{ address public affiliateBeneficiary; uint256 public affiliatePercentage; //This is out of 1 ETH, e.g. 0.5 ETH is 50% of the fee uint256 public companyPercentage; address public companyBeneficiary; function init(address _companyBeneficiary, uint256 _companyPercentage, address _affiliateBeneficiary, uint256 _affiliatePercentage) public { require(companyBeneficiary == 0x0 && affiliateBeneficiary == 0x0); companyBeneficiary = _companyBeneficiary; companyPercentage = _companyPercentage; affiliateBeneficiary = _affiliateBeneficiary; affiliatePercentage = _affiliatePercentage; } function payout() public { // Payout both the affiliate and the company at the same time affiliateBeneficiary.transfer(SafeMath.div(SafeMath.mul(address(this).balance, affiliatePercentage), getTotalFeePercentage())); companyBeneficiary.transfer(address(this).balance); } function() public payable { } function getTotalFeePercentage() public view returns (uint256){ return affiliatePercentage + companyPercentage; } } contract AffiliateRegistry is Ownable { address target; mapping(address => bool) affiliateContracts; address public companyBeneficiary; uint256 public companyPercentage; event AffiliateRegistered(address affiliateContract); constructor(address _target, address _companyBeneficiary, uint256 _companyPercentage) public { target = _target; companyBeneficiary = _companyBeneficiary; companyPercentage = _companyPercentage; } function registerAffiliate(address affiliateBeneficiary, uint256 affiliatePercentage) external { Affiliate newAffiliate = Affiliate(createClone()); newAffiliate.init(companyBeneficiary, companyPercentage, affiliateBeneficiary, affiliatePercentage); affiliateContracts[address(newAffiliate)] = true; emit AffiliateRegistered(address(newAffiliate)); } function overrideRegisterAffiliate(address _companyBeneficiary, uint256 _companyPercentage, address affiliateBeneficiary, uint256 affiliatePercentage) external onlyOwner { Affiliate newAffiliate = Affiliate(createClone()); newAffiliate.init(_companyBeneficiary, _companyPercentage, affiliateBeneficiary, affiliatePercentage); affiliateContracts[address(newAffiliate)] = true; emit AffiliateRegistered(address(newAffiliate)); } function deleteAffiliate(address _affiliateAddress) public onlyOwner { affiliateContracts[_affiliateAddress] = false; } function createClone() internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isValidAffiliate(address affiliateContract) public view returns(bool) { return affiliateContracts[affiliateContract]; } function updateCompanyInfo(address newCompanyBeneficiary, uint256 newCompanyPercentage) public onlyOwner { companyBeneficiary = newCompanyBeneficiary; companyPercentage = newCompanyPercentage; } } /// @title A contract which can be used to ensure only the TotlePrimary contract can call /// some functions /// @dev Defines a modifier which should be used when only the totle contract should /// able able to call a function contract TotleControl is Ownable { mapping(address => bool) public authorizedPrimaries; /// @dev A modifier which only allows code execution if msg.sender equals totlePrimary address modifier onlyTotle() { require(authorizedPrimaries[msg.sender]); _; } /// @notice Contract constructor /// @dev As this contract inherits ownable, msg.sender will become the contract owner /// @param _totlePrimary the address of the contract to be set as totlePrimary constructor(address _totlePrimary) public { authorizedPrimaries[_totlePrimary] = true; } /// @notice A function which allows only the owner to change the address of totlePrimary /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param _totlePrimary the address of the contract to be set as totlePrimary function addTotle( address _totlePrimary ) external onlyOwner { authorizedPrimaries[_totlePrimary] = true; } function removeTotle( address _totlePrimary ) external onlyOwner { authorizedPrimaries[_totlePrimary] = false; } } contract SelectorProvider { bytes4 constant getAmountToGiveSelector = bytes4(keccak256("getAmountToGive(bytes)")); bytes4 constant staticExchangeChecksSelector = bytes4(keccak256("staticExchangeChecks(bytes)")); bytes4 constant performBuyOrderSelector = bytes4(keccak256("performBuyOrder(bytes,uint256)")); bytes4 constant performSellOrderSelector = bytes4(keccak256("performSellOrder(bytes,uint256)")); function getSelector(bytes4 genericSelector) public pure returns (bytes4); } /// @title Interface for all exchange handler contracts contract ExchangeHandler is SelectorProvider, TotleControl, Withdrawable, Pausable { /* * State Variables */ ErrorReporter public errorReporter; /* Logger public logger; */ /* * Modifiers */ /// @notice Constructor /// @dev Calls the constructor of the inherited TotleControl /// @param totlePrimary the address of the totlePrimary contract constructor( address totlePrimary, address _errorReporter /* ,address _logger */ ) TotleControl(totlePrimary) public { require(_errorReporter != address(0x0)); /* require(_logger != address(0x0)); */ errorReporter = ErrorReporter(_errorReporter); /* logger = Logger(_logger); */ } /// @notice Gets the amount that Totle needs to give for this order /// @param genericPayload the data for this order in a generic format /// @return amountToGive amount taker needs to give in order to fill the order function getAmountToGive( bytes genericPayload ) public view returns (uint256 amountToGive) { bool success; bytes4 functionSelector = getSelector(this.getAmountToGive.selector); assembly { let functionSelectorLength := 0x04 let functionSelectorOffset := 0x1C let scratchSpace := 0x0 let wordLength := 0x20 let bytesLength := mload(genericPayload) let totalLength := add(functionSelectorLength, bytesLength) let startOfNewData := add(genericPayload, functionSelectorOffset) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(genericPayload, functionSelectorCorrect) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. wordLength // Length of return variable is one word ) amountToGive := mload(scratchSpace) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform exchange-specific checks on the given order /// @dev this should be called to check for payload errors /// @param genericPayload the data for this order in a generic format /// @return checksPassed value representing pass or fail function staticExchangeChecks( bytes genericPayload ) public view returns (bool checksPassed) { bool success; bytes4 functionSelector = getSelector(this.staticExchangeChecks.selector); assembly { let functionSelectorLength := 0x04 let functionSelectorOffset := 0x1C let scratchSpace := 0x0 let wordLength := 0x20 let bytesLength := mload(genericPayload) let totalLength := add(functionSelectorLength, bytesLength) let startOfNewData := add(genericPayload, functionSelectorOffset) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(genericPayload, functionSelectorCorrect) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. wordLength // Length of return variable is one word ) checksPassed := mload(scratchSpace) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform a buy order at the exchange /// @param genericPayload the data for this order in a generic format /// @param amountToGiveForOrder amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performBuyOrder( bytes genericPayload, uint256 amountToGiveForOrder ) public payable returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { bool success; bytes4 functionSelector = getSelector(this.performBuyOrder.selector); assembly { let callDataOffset := 0x44 let functionSelectorOffset := 0x1C let functionSelectorLength := 0x04 let scratchSpace := 0x0 let wordLength := 0x20 let startOfFreeMemory := mload(0x40) calldatacopy(startOfFreeMemory, callDataOffset, calldatasize) let bytesLength := mload(startOfFreeMemory) let totalLength := add(add(functionSelectorLength, bytesLength), wordLength) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(startOfFreeMemory, functionSelectorCorrect) mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder) let startOfNewData := add(startOfFreeMemory,functionSelectorOffset) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. mul(wordLength, 0x02) // Length of return variables is two words ) amountSpentOnOrder := mload(scratchSpace) amountReceivedFromOrder := mload(add(scratchSpace, wordLength)) if eq(success, 0) { revert(0, 0) } } } /// @notice Perform a sell order at the exchange /// @param genericPayload the data for this order in a generic format /// @param amountToGiveForOrder amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order function performSellOrder( bytes genericPayload, uint256 amountToGiveForOrder ) public returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { bool success; bytes4 functionSelector = getSelector(this.performSellOrder.selector); assembly { let callDataOffset := 0x44 let functionSelectorOffset := 0x1C let functionSelectorLength := 0x04 let scratchSpace := 0x0 let wordLength := 0x20 let startOfFreeMemory := mload(0x40) calldatacopy(startOfFreeMemory, callDataOffset, calldatasize) let bytesLength := mload(startOfFreeMemory) let totalLength := add(add(functionSelectorLength, bytesLength), wordLength) mstore(add(scratchSpace, functionSelectorOffset), functionSelector) let functionSelectorCorrect := mload(scratchSpace) mstore(startOfFreeMemory, functionSelectorCorrect) mstore(add(startOfFreeMemory, add(wordLength, bytesLength)), amountToGiveForOrder) let startOfNewData := add(startOfFreeMemory,functionSelectorOffset) success := delegatecall( gas, address, // This address of the current contract startOfNewData, // Start data at the beginning of the functionSelector totalLength, // Total length of all data, including functionSelector scratchSpace, // Use the first word of memory (scratch space) to store our return variable. mul(wordLength, 0x02) // Length of return variables is two words ) amountSpentOnOrder := mload(scratchSpace) amountReceivedFromOrder := mload(add(scratchSpace, wordLength)) if eq(success, 0) { revert(0, 0) } } } } /// @title The primary contract for Totle contract TotlePrimary is Withdrawable, Pausable { /* * State Variables */ mapping(address => bool) public handlerWhitelistMap; address[] public handlerWhitelistArray; AffiliateRegistry affiliateRegistry; address public defaultFeeAccount; TokenTransferProxy public tokenTransferProxy; ErrorReporter public errorReporter; /* Logger public logger; */ /* * Types */ // Structs struct Trade { bool isSell; address tokenAddress; uint256 tokenAmount; bool optionalTrade; uint256 minimumExchangeRate; uint256 minimumAcceptableTokenAmount; Order[] orders; } struct Order { address exchangeHandler; bytes genericPayload; } struct TradeFlag { bool ignoreTrade; bool[] ignoreOrder; } struct CurrentAmounts { uint256 amountSpentOnTrade; uint256 amountReceivedFromTrade; uint256 amountLeftToSpendOnTrade; } /* * Events */ event LogRebalance( bytes32 id ); /* * Modifiers */ modifier handlerWhitelisted(address handler) { if (!handlerWhitelistMap[handler]) { errorReporter.revertTx("Handler not in whitelist"); } _; } modifier handlerNotWhitelisted(address handler) { if (handlerWhitelistMap[handler]) { errorReporter.revertTx("Handler already whitelisted"); } _; } /// @notice Constructor /// @param _tokenTransferProxy address of the TokenTransferProxy /// @param _errorReporter the address of the error reporter contract constructor (address _tokenTransferProxy, address _affiliateRegistry, address _errorReporter, address _defaultFeeAccount/*, address _logger*/) public { /* require(_logger != address(0x0)); */ tokenTransferProxy = TokenTransferProxy(_tokenTransferProxy); affiliateRegistry = AffiliateRegistry(_affiliateRegistry); errorReporter = ErrorReporter(_errorReporter); defaultFeeAccount = _defaultFeeAccount; /* logger = Logger(_logger); */ } /* * Public functions */ /// @notice Update the default fee account /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param newDefaultFeeAccount new default fee account function updateDefaultFeeAccount(address newDefaultFeeAccount) public onlyOwner { defaultFeeAccount = newDefaultFeeAccount; } /// @notice Add an exchangeHandler address to the whitelist /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param handler Address of the exchange handler which permission needs adding function addHandlerToWhitelist(address handler) public onlyOwner handlerNotWhitelisted(handler) { handlerWhitelistMap[handler] = true; handlerWhitelistArray.push(handler); } /// @notice Remove an exchangeHandler address from the whitelist /// @dev onlyOwner modifier only allows the contract owner to run the code /// @param handler Address of the exchange handler which permission needs removing function removeHandlerFromWhitelist(address handler) public onlyOwner handlerWhitelisted(handler) { delete handlerWhitelistMap[handler]; for (uint i = 0; i < handlerWhitelistArray.length; i++) { if (handlerWhitelistArray[i] == handler) { handlerWhitelistArray[i] = handlerWhitelistArray[handlerWhitelistArray.length - 1]; handlerWhitelistArray.length -= 1; break; } } } /// @notice Performs the requested portfolio rebalance /// @param trades A dynamic array of trade structs function performRebalance( Trade[] memory trades, address feeAccount, bytes32 id ) public payable whenNotPaused { if(!affiliateRegistry.isValidAffiliate(feeAccount)){ feeAccount = defaultFeeAccount; } Affiliate affiliate = Affiliate(feeAccount); uint256 feePercentage = affiliate.getTotalFeePercentage(); emit LogRebalance(id); /* logger.log("Starting Rebalance..."); */ TradeFlag[] memory tradeFlags = initialiseTradeFlags(trades); staticChecks(trades, tradeFlags); /* logger.log("Static checks passed."); */ transferTokens(trades, tradeFlags); /* logger.log("Tokens transferred."); */ uint256 etherBalance = msg.value; uint256 totalFee = 0; /* logger.log("Ether balance arg2: etherBalance.", etherBalance); */ for (uint256 i; i < trades.length; i++) { Trade memory thisTrade = trades[i]; TradeFlag memory thisTradeFlag = tradeFlags[i]; CurrentAmounts memory amounts = CurrentAmounts({ amountSpentOnTrade: 0, amountReceivedFromTrade: 0, amountLeftToSpendOnTrade: thisTrade.isSell ? thisTrade.tokenAmount : calculateMaxEtherSpend(thisTrade, etherBalance, feePercentage) }); /* logger.log("Going to perform trade. arg2: amountLeftToSpendOnTrade", amounts.amountLeftToSpendOnTrade); */ performTrade( thisTrade, thisTradeFlag, amounts ); uint256 ethTraded; uint256 ethFee; if(thisTrade.isSell){ ethTraded = amounts.amountReceivedFromTrade; } else { ethTraded = amounts.amountSpentOnTrade; } ethFee = calculateFee(ethTraded, feePercentage); totalFee = SafeMath.add(totalFee, ethFee); /* logger.log("Finished performing trade arg2: amountReceivedFromTrade, arg3: amountSpentOnTrade.", amounts.amountReceivedFromTrade, amounts.amountSpentOnTrade); */ if (amounts.amountReceivedFromTrade == 0 && thisTrade.optionalTrade) { /* logger.log("Received 0 from trade and this is an optional trade. Skipping."); */ continue; } /* logger.log( "Going to check trade acceptable amounts arg2: amountSpentOnTrade, arg2: amountReceivedFromTrade.", amounts.amountSpentOnTrade, amounts.amountReceivedFromTrade ); */ if (!checkIfTradeAmountsAcceptable(thisTrade, amounts.amountSpentOnTrade, amounts.amountReceivedFromTrade)) { errorReporter.revertTx("Amounts spent/received in trade not acceptable"); } /* logger.log("Trade passed the acceptable amounts check."); */ if (thisTrade.isSell) { /* logger.log( "This is a sell trade, adding ether to our balance arg2: etherBalance, arg3: amountReceivedFromTrade", etherBalance, amounts.amountReceivedFromTrade ); */ etherBalance = SafeMath.sub(SafeMath.add(etherBalance, ethTraded), ethFee); } else { /* logger.log( "This is a buy trade, deducting ether from our balance arg2: etherBalance, arg3: amountSpentOnTrade", etherBalance, amounts.amountSpentOnTrade ); */ etherBalance = SafeMath.sub(SafeMath.sub(etherBalance, ethTraded), ethFee); } /* logger.log("Transferring tokens to the user arg:6 tokenAddress.", 0,0,0,0, thisTrade.tokenAddress); */ transferTokensToUser( thisTrade.tokenAddress, thisTrade.isSell ? amounts.amountLeftToSpendOnTrade : amounts.amountReceivedFromTrade ); } if(totalFee > 0){ feeAccount.transfer(totalFee); } if(etherBalance > 0) { /* logger.log("Got a positive ether balance, sending to the user arg2: etherBalance.", etherBalance); */ msg.sender.transfer(etherBalance); } } /// @notice Performs static checks on the rebalance payload before execution /// @dev This function is public so a rebalance can be checked before performing a rebalance /// @param trades A dynamic array of trade structs /// @param tradeFlags A dynamic array of flags indicating trade and order status function staticChecks( Trade[] trades, TradeFlag[] tradeFlags ) public view whenNotPaused { bool previousBuyOccured = false; for (uint256 i; i < trades.length; i++) { Trade memory thisTrade = trades[i]; if (thisTrade.isSell) { if (previousBuyOccured) { errorReporter.revertTx("A buy has occured before this sell"); } if (!Utils.tokenAllowanceAndBalanceSet(msg.sender, thisTrade.tokenAddress, thisTrade.tokenAmount, address(tokenTransferProxy))) { if (!thisTrade.optionalTrade) { errorReporter.revertTx("Taker has not sent allowance/balance on a non-optional trade"); } /* logger.log( "Attempt to sell a token without allowance or sufficient balance arg2: tokenAmount, arg6: tokenAddress . Otional trade, ignoring.", thisTrade.tokenAmount, 0, 0, 0, thisTrade.tokenAddress ); */ tradeFlags[i].ignoreTrade = true; continue; } } else { previousBuyOccured = true; } /* logger.log("Checking that all the handlers are whitelisted."); */ for (uint256 j; j < thisTrade.orders.length; j++) { Order memory thisOrder = thisTrade.orders[j]; if ( !handlerWhitelistMap[thisOrder.exchangeHandler] ) { /* logger.log( "Trying to use a handler that is not whitelisted arg6: exchangeHandler.", 0, 0, 0, 0, thisOrder.exchangeHandler ); */ tradeFlags[i].ignoreOrder[j] = true; continue; } } } } /* * Internal functions */ /// @notice Initialises the trade flag struct /// @param trades the trades used to initialise the flags /// @return tradeFlags the initialised flags function initialiseTradeFlags(Trade[] trades) internal returns (TradeFlag[]) { /* logger.log("Initializing trade flags."); */ TradeFlag[] memory tradeFlags = new TradeFlag[](trades.length); for (uint256 i = 0; i < trades.length; i++) { tradeFlags[i].ignoreOrder = new bool[](trades[i].orders.length); } return tradeFlags; } /// @notice Transfers the given amount of tokens back to the msg.sender /// @param tokenAddress the address of the token to transfer /// @param tokenAmount the amount of tokens to transfer function transferTokensToUser( address tokenAddress, uint256 tokenAmount ) internal { /* logger.log("Transfering tokens to the user arg2: tokenAmount, arg6: .tokenAddress", tokenAmount, 0, 0, 0, tokenAddress); */ if (tokenAmount > 0) { if (!ERC20SafeTransfer.safeTransfer(tokenAddress, msg.sender, tokenAmount)) { errorReporter.revertTx("Unable to transfer tokens to user"); } } } /// @notice Executes the given trade /// @param trade a struct containing information about the trade /// @param tradeFlag a struct containing trade status information /// @param amounts a struct containing information about amounts spent /// and received in the rebalance function performTrade( Trade memory trade, TradeFlag memory tradeFlag, CurrentAmounts amounts ) internal { /* logger.log("Performing trade"); */ for (uint256 j; j < trade.orders.length; j++) { if(amounts.amountLeftToSpendOnTrade * 10000 < (amounts.amountSpentOnTrade + amounts.amountLeftToSpendOnTrade)){ return; } if((trade.isSell ? amounts.amountSpentOnTrade : amounts.amountReceivedFromTrade) >= trade.tokenAmount ) { return; } if (tradeFlag.ignoreOrder[j] || amounts.amountLeftToSpendOnTrade == 0) { /* logger.log( "Order ignore flag is set to true or have nothing left to spend arg2: amountLeftToSpendOnTrade", amounts.amountLeftToSpendOnTrade ); */ continue; } uint256 amountSpentOnOrder = 0; uint256 amountReceivedFromOrder = 0; Order memory thisOrder = trade.orders[j]; /* logger.log("Setting order exchange handler arg6: exchangeHandler.", 0, 0, 0, 0, thisOrder.exchangeHandler); */ ExchangeHandler thisHandler = ExchangeHandler(thisOrder.exchangeHandler); uint256 amountToGiveForOrder = Utils.min( thisHandler.getAmountToGive(thisOrder.genericPayload), amounts.amountLeftToSpendOnTrade ); if (amountToGiveForOrder == 0) { /* logger.log( "MASSIVE ERROR: amountToGiveForOrder was found to be 0, this hasn't been caught in preTradeChecks, which means dynamicExchangeChecks isnt written correctly!" ); */ continue; } /* logger.log( "Calculating amountToGiveForOrder arg2: amountToGiveForOrder, arg3: amountLeftToSpendOnTrade.", amountToGiveForOrder, amounts.amountLeftToSpendOnTrade ); */ if( !thisHandler.staticExchangeChecks(thisOrder.genericPayload) ) { /* logger.log("Order did not pass checks, skipping."); */ continue; } if (trade.isSell) { /* logger.log("This is a sell.."); */ if (!ERC20SafeTransfer.safeTransfer(trade.tokenAddress,address(thisHandler), amountToGiveForOrder)) { if( !trade.optionalTrade ) errorReporter.revertTx("Unable to transfer tokens to handler"); else { /* logger.log("Unable to transfer tokens to handler but the trade is optional"); */ return; } } /* logger.log("Going to perform a sell order."); */ (amountSpentOnOrder, amountReceivedFromOrder) = thisHandler.performSellOrder(thisOrder.genericPayload, amountToGiveForOrder); /* logger.log("Sell order performed arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder); */ } else { /* logger.log("Going to perform a buy order."); */ (amountSpentOnOrder, amountReceivedFromOrder) = thisHandler.performBuyOrder.value(amountToGiveForOrder)(thisOrder.genericPayload, amountToGiveForOrder); /* logger.log("Buy order performed arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder); */ } if (amountReceivedFromOrder > 0) { amounts.amountLeftToSpendOnTrade = SafeMath.sub(amounts.amountLeftToSpendOnTrade, amountSpentOnOrder); amounts.amountSpentOnTrade = SafeMath.add(amounts.amountSpentOnTrade, amountSpentOnOrder); amounts.amountReceivedFromTrade = SafeMath.add(amounts.amountReceivedFromTrade, amountReceivedFromOrder); /* logger.log( "Updated amounts arg2: amountLeftToSpendOnTrade, arg3: amountSpentOnTrade, arg4: amountReceivedFromTrade.", amounts.amountLeftToSpendOnTrade, amounts.amountSpentOnTrade, amounts.amountReceivedFromTrade ); */ } } } /// @notice Check if the amounts spent and gained on a trade are within the /// user"s set limits /// @param trade contains information on the given trade /// @param amountSpentOnTrade the amount that was spent on the trade /// @param amountReceivedFromTrade the amount that was received from the trade /// @return bool whether the trade passes the checks function checkIfTradeAmountsAcceptable( Trade trade, uint256 amountSpentOnTrade, uint256 amountReceivedFromTrade ) internal view returns (bool passed) { /* logger.log("Checking if trade amounts are acceptable."); */ uint256 tokenAmount = trade.isSell ? amountSpentOnTrade : amountReceivedFromTrade; passed = tokenAmount >= trade.minimumAcceptableTokenAmount; /*if( !passed ) { logger.log( "Received less than minimum acceptable tokens arg2: tokenAmount , arg3: minimumAcceptableTokenAmount.", tokenAmount, trade.minimumAcceptableTokenAmount ); }*/ if (passed) { uint256 tokenDecimals = Utils.getDecimals(ERC20(trade.tokenAddress)); uint256 srcDecimals = trade.isSell ? tokenDecimals : Utils.eth_decimals(); uint256 destDecimals = trade.isSell ? Utils.eth_decimals() : tokenDecimals; uint256 actualRate = Utils.calcRateFromQty(amountSpentOnTrade, amountReceivedFromTrade, srcDecimals, destDecimals); passed = actualRate >= trade.minimumExchangeRate; } /*if( !passed ) { logger.log( "Order rate was lower than minimum acceptable, rate arg2: actualRate, arg3: minimumExchangeRate.", actualRate, trade.minimumExchangeRate ); }*/ } /// @notice Iterates through a list of token orders, transfer the SELL orders to this contract & calculates if we have the ether needed /// @param trades A dynamic array of trade structs /// @param tradeFlags A dynamic array of flags indicating trade and order status function transferTokens(Trade[] trades, TradeFlag[] tradeFlags) internal { for (uint256 i = 0; i < trades.length; i++) { if (trades[i].isSell && !tradeFlags[i].ignoreTrade) { /* logger.log( "Transfering tokens arg2: tokenAmount, arg5: tokenAddress.", trades[i].tokenAmount, 0, 0, 0, trades[i].tokenAddress ); */ if ( !tokenTransferProxy.transferFrom( trades[i].tokenAddress, msg.sender, address(this), trades[i].tokenAmount ) ) { errorReporter.revertTx("TTP unable to transfer tokens to primary"); } } } } /// @notice Calculates the maximum amount that should be spent on a given buy trade /// @param trade the buy trade to return the spend amount for /// @param etherBalance the amount of ether that we currently have to spend /// @return uint256 the maximum amount of ether we should spend on this trade function calculateMaxEtherSpend(Trade trade, uint256 etherBalance, uint256 feePercentage) internal view returns (uint256) { /// @dev This function should never be called for a sell assert(!trade.isSell); uint256 tokenDecimals = Utils.getDecimals(ERC20(trade.tokenAddress)); uint256 srcDecimals = trade.isSell ? tokenDecimals : Utils.eth_decimals(); uint256 destDecimals = trade.isSell ? Utils.eth_decimals() : tokenDecimals; uint256 maxSpendAtMinRate = Utils.calcSrcQty(trade.tokenAmount, srcDecimals, destDecimals, trade.minimumExchangeRate); return Utils.min(removeFee(etherBalance, feePercentage), maxSpendAtMinRate); } // @notice Calculates the fee amount given a fee percentage and amount // @param amount the amount to calculate the fee based on // @param fee the percentage, out of 1 eth (e.g. 0.01 ETH would be 1%) function calculateFee(uint256 amount, uint256 fee) internal view returns (uint256){ return SafeMath.div(SafeMath.mul(amount, fee), 1 ether); } // @notice Calculates the cost if amount=cost+fee // @param amount the amount to calculate the base on // @param fee the percentage, out of 1 eth (e.g. 0.01 ETH would be 1%) function removeFee(uint256 amount, uint256 fee) internal view returns (uint256){ return SafeMath.div(SafeMath.mul(amount, 1 ether), SafeMath.add(fee, 1 ether)); } /* * Payable fallback function */ /// @notice payable fallback to allow handler or exchange contracts to return ether /// @dev only accounts containing code (ie. contracts) can send ether to this contract function() public payable whenNotPaused { // Check in here that the sender is a contract! (to stop accidents) uint256 size; address sender = msg.sender; assembly { size := extcodesize(sender) } if (size == 0) { errorReporter.revertTx("EOA cannot send ether to primary fallback"); } } } /// @title A contract which is used to check and set allowances of tokens /// @dev In order to use this contract is must be inherited in the contract which is using /// its functionality contract AllowanceSetter { uint256 constant MAX_UINT = 2**256 - 1; /// @notice A function which allows the caller to approve the max amount of any given token /// @dev In order to function correctly, token allowances should not be set anywhere else in /// the inheriting contract /// @param addressToApprove the address which we want to approve to transfer the token /// @param token the token address which we want to call approve on function approveAddress(address addressToApprove, address token) internal { if(ERC20(token).allowance(address(this), addressToApprove) == 0) { require(ERC20SafeTransfer.safeApprove(token, addressToApprove, MAX_UINT)); } } } contract TotleProxyPrimary is Ownable, AllowanceSetter { TokenTransferProxy public tokenTransferProxy; TotlePrimary public totlePrimary; constructor(address _tokenTransferProxy, address _totlePrimary) public { tokenTransferProxy = TokenTransferProxy(_tokenTransferProxy); totlePrimary = TotlePrimary(_totlePrimary); } function performRebalance( TotlePrimary.Trade[] memory trades, address feeAccount, bytes32 id, address paymentReceiver, bool redirectEth, address[] redirectTokens ) public payable { transferTokensIn(trades); totlePrimary.performRebalance.value(msg.value)(trades, feeAccount, id); transferTokensOut(trades, paymentReceiver, redirectTokens); if(redirectEth) { paymentReceiver.transfer(address(this).balance); } else { msg.sender.transfer(address(this).balance); } } function transferTokensIn(TotlePrimary.Trade[] trades) internal { for (uint256 i = 0; i < trades.length; i++) { if (trades[i].isSell) { if (!tokenTransferProxy.transferFrom( trades[i].tokenAddress, msg.sender, address(this), trades[i].tokenAmount )) { revert("TTP unable to transfer tokens to proxy"); } approveAddress(address(tokenTransferProxy), trades[i].tokenAddress); } } } function transferTokensOut(TotlePrimary.Trade[] trades, address receiver, address[] redirectTokens) internal { for (uint256 i = 0; i < trades.length; i++) { bool redirect = false; for(uint256 tokenIndex = 0; tokenIndex < redirectTokens.length; tokenIndex++){ if(redirectTokens[tokenIndex] == trades[i].tokenAddress){ redirect = true; break; } } uint256 balance = ERC20(trades[i].tokenAddress).balanceOf(address(this)); if(balance > 0){ ERC20SafeTransfer.safeTransfer(trades[i].tokenAddress, redirect ? receiver : msg.sender, balance); } } } function setTokenTransferProxy(address _newTokenTransferProxy) public onlyOwner { tokenTransferProxy = TokenTransferProxy(_newTokenTransferProxy); } function setTotlePrimary(address _newTotlePrimary) public onlyOwner { totlePrimary = TotlePrimary(_newTotlePrimary); } }
@notice A function which allows the caller to approve the max amount of any given token @dev In order to function correctly, token allowances should not be set anywhere else in the inheriting contract @param addressToApprove the address which we want to approve to transfer the token @param token the token address which we want to call approve on
function approveAddress(address addressToApprove, address token) internal { if(ERC20(token).allowance(address(this), addressToApprove) == 0) { require(ERC20SafeTransfer.safeApprove(token, addressToApprove, MAX_UINT)); } }
883,827
[ 1, 37, 445, 1492, 5360, 326, 4894, 358, 6617, 537, 326, 943, 3844, 434, 1281, 864, 1147, 225, 657, 1353, 358, 445, 8783, 16, 1147, 1699, 6872, 1410, 486, 506, 444, 25651, 469, 316, 326, 6811, 310, 6835, 225, 1758, 774, 12053, 537, 326, 1758, 1492, 732, 2545, 358, 6617, 537, 358, 7412, 326, 1147, 225, 1147, 326, 1147, 1758, 1492, 732, 2545, 358, 745, 6617, 537, 603, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6617, 537, 1887, 12, 2867, 1758, 774, 12053, 537, 16, 1758, 1147, 13, 2713, 288, 203, 3639, 309, 12, 654, 39, 3462, 12, 2316, 2934, 5965, 1359, 12, 2867, 12, 2211, 3631, 1758, 774, 12053, 537, 13, 422, 374, 13, 288, 203, 5411, 2583, 12, 654, 39, 3462, 9890, 5912, 18, 4626, 12053, 537, 12, 2316, 16, 1758, 774, 12053, 537, 16, 4552, 67, 57, 3217, 10019, 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 ]
./partial_match/4/0x6b0787A77c11458EF87Bd733a63BBC11980d285D/sources/OroNetwork.sol
calculate time difference Get number of weeks Get the left out days Get Interest amount based on user loan amount
function viewInterest(address token, uint256 loanId) public view returns (uint256 leftoutDays, uint256 value) { uint256 time = ( loans[loanId].interestpaidOn > 0 ? loans[loanId].interestpaidOn : loans[loanId].depositTime ); time = now.sub(time); time = time.div(604800); if(loans[loanId].interestpaidOn == 0 && time == 0) time = 1; leftoutDays = time.mod(604800); uint256 interest; if (loans[loanId].amount > 0 && loans[loanId].amount >= 10000) { interest = (token == USDC ? USDCInterest[1] : OROInterest[1]); } if (loans[loanId].amount > 10000 && loans[loanId].amount >= 50000) { interest = (token == USDC ? USDCInterest[2] : OROInterest[2]); } if (loans[loanId].amount > 50000 && loans[loanId].amount >= 100000) { interest = (token == USDC ? USDCInterest[3] : OROInterest[3]); } if (loans[loanId].amount > 100000) { interest = (token == USDC ? USDCInterest[4] : OROInterest[4]); } value = ( token == USDC ? time.mul( (toUSDC(loans[loanId].asset, loans[loanId].amount)) .mul(interest) .div(10000) .div(52) ) : time.mul( (toORO(loans[loanId].asset, loans[loanId].amount)) .mul(interest) .div(10000) .div(52) ) ); }
8,638,039
[ 1, 11162, 813, 7114, 968, 1300, 434, 17314, 968, 326, 2002, 596, 4681, 968, 5294, 395, 3844, 2511, 603, 729, 28183, 3844, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 1476, 29281, 12, 2867, 1147, 16, 2254, 5034, 28183, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 2002, 659, 9384, 16, 2254, 5034, 460, 13, 203, 565, 288, 203, 3639, 2254, 5034, 813, 273, 203, 5411, 261, 203, 7734, 437, 634, 63, 383, 304, 548, 8009, 2761, 395, 29434, 1398, 405, 374, 203, 10792, 692, 437, 634, 63, 383, 304, 548, 8009, 2761, 395, 29434, 1398, 203, 10792, 294, 437, 634, 63, 383, 304, 548, 8009, 323, 1724, 950, 203, 5411, 11272, 203, 3639, 813, 273, 2037, 18, 1717, 12, 957, 1769, 203, 3639, 813, 273, 813, 18, 2892, 12, 26, 3028, 17374, 1769, 203, 3639, 309, 12, 383, 634, 63, 383, 304, 548, 8009, 2761, 395, 29434, 1398, 422, 374, 597, 813, 422, 374, 13, 7010, 5411, 813, 273, 404, 31, 203, 3639, 2002, 659, 9384, 273, 813, 18, 1711, 12, 26, 3028, 17374, 1769, 203, 203, 3639, 2254, 5034, 16513, 31, 203, 3639, 309, 261, 383, 634, 63, 383, 304, 548, 8009, 8949, 405, 374, 597, 437, 634, 63, 383, 304, 548, 8009, 8949, 1545, 12619, 13, 288, 203, 5411, 16513, 273, 261, 2316, 422, 11836, 5528, 692, 11836, 5528, 29281, 63, 21, 65, 294, 531, 1457, 29281, 63, 21, 19226, 203, 3639, 289, 203, 3639, 309, 261, 383, 634, 63, 383, 304, 548, 8009, 8949, 405, 12619, 597, 437, 634, 63, 383, 304, 548, 8009, 8949, 1545, 1381, 2787, 13, 288, 203, 5411, 16513, 273, 261, 2316, 422, 11836, 5528, 692, 11836, 5528, 2 ]
/* MiniDogeZilla, * Ever-burning MiniDoge Godzilla * 3% Reflections 2% Liquidity 4% Marketing Telegram: https://t.me/Minidogezilla Website: https://www.minidogezilla.finance/ Twitter: https://twitter.com/minidogezilla */ pragma solidity ^0.8.9; // SPDX-License-Identifier: MIT 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); } abstract contract Authorized{ address private _owner; address private _previousOwner; mapping (address => bool) _authorized; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = msg.sender; _owner = msgSender; _authorized[_owner] = true; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } modifier onlyAuthorized { require(_authorized[msg.sender], "Authorization: caller is not the authorized"); _; } function manageAuthorization(address account, bool authorize) public onlyOwner { _authorized[account] = authorize; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 { 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; } contract MiniDogeZilla is IERC20, Authorized { mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) public automatedMarketMakerPairs; string private _name = "MiniDogeZilla"; string private _symbol = "MDZ"; uint8 private _decimals = 9 ; uint256 private DECIMALS = 10 ** _decimals; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 69000000000000000000000 * DECIMALS; // 69e21 tokens, total supply uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 public _marketingFee = 4; uint256 private _totalLPFee = 6; uint256 private _previousTotalLPFee = _totalLPFee; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; address public deadAddress = address(0x000000000000000000000000000000000000dEaD); address public marketingAddress; uint256 public swapTokensAtAmount = 2 * _tTotal / 1000; // 0.2% of total supply, 138e18 tokens uint256 public maxTx = 5 * _tTotal / 1000; // 0.5% of total supply, 345e18 tokens uint256 public maxWallet = 20 * _tTotal / 1000; // 2.0% of total supply, 1380e18 tokens uint256 private nAntiBotBlocks; uint256 private launchBlock; bool public tradingIsEnabled = false; bool public antiBotActive = false; bool private swapping = false; bool private inBurn = false; bool private accumulatingForBurn = false; uint256 burnAmount = 0; bool intensify = false; uint256 intensifyDuration = 0; uint256 intensifyStart = 0; event Launch(uint256 indexed nAntiBotBlocks); event SetFees(uint256 indexed liquidityFee, uint256 indexed marketingFee, uint256 indexed totalFee); event SetTradeRestrictions(uint256 indexed maxTx, uint256 indexed maxWallet); event SetSwapTokensAtAmount(uint256 indexed swapTokensAtAmount); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived ); constructor () { _rOwned[msg.sender] = _rTotal; marketingAddress = msg.sender; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); automatedMarketMakerPairs[uniswapV2Pair] = true; uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[deadAddress] = true; excludeFromReward(deadAddress); emit Transfer(address(0), msg.sender, _tTotal); } modifier inSwap{ swapping = true; _; swapping = false; } modifier inburn{ inBurn = true; _; inBurn = false; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); require(_allowances[sender][msg.sender] >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { require(_allowances[msg.sender][spender] >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _getValues(uint256 tAmount, address from) private returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount, from); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount, address from) private returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount, from); uint256 tLiquidity = calculateLiquidityFee(tAmount, from); uint256 tTransferAmount = tAmount - tFee - tLiquidity; return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount * currentRate; uint256 rFee = tFee * currentRate; uint256 rLiquidity = tLiquidity * currentRate; uint256 rTransferAmount = rAmount - rFee - rLiquidity; return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity * currentRate; _rOwned[address(this)] = _rOwned[address(this)] + rLiquidity; if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + tLiquidity; } function rush(uint256 _minutes) external onlyAuthorized { require(_minutes <= 4 * 60, "Rush may not last over four hours."); intensify = true; intensifyDuration = _minutes * 1 minutes; intensifyStart = block.timestamp; } function calculateTaxFee(uint256 _amount, address from) private returns (uint256) { if (_taxFee == 0 && _totalLPFee == 0){ return 0; } uint256 fee = 0; if(intensify){ uint256 halfTime = intensifyStart + intensifyDuration / 2; uint256 fullTime = intensifyStart + intensifyDuration; if(block.timestamp < halfTime){ fee = automatedMarketMakerPairs[from] ? 0 : 10; } else if(block.timestamp < fullTime){ fee = automatedMarketMakerPairs[from] ? 2 : 5; } else{ fee = _taxFee; intensify = false; } } else{ fee = _taxFee; } return _amount * fee / 10**2; } function calculateLiquidityFee(uint256 _amount, address from) private returns (uint256) { if (_taxFee == 0 && _totalLPFee == 0){ return 0; } uint256 fee = 0; if(intensify){ uint256 halfTime = intensifyStart + intensifyDuration / 2; uint256 fullTime = intensifyStart + intensifyDuration; if(block.timestamp < halfTime){ fee = automatedMarketMakerPairs[from] ? 0 : 10; } else if(block.timestamp < fullTime){ fee = automatedMarketMakerPairs[from] ? 3 : 10; } else{ fee = _totalLPFee; intensify = false; } } else{ fee = _totalLPFee; } return _amount * fee / 10**2; } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousTotalLPFee = _totalLPFee; _taxFee = 0; _totalLPFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _totalLPFee = _previousTotalLPFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { 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); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "MiniDogeZilla: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function launch(uint256 _nAntiBotBlocks) public onlyOwner{ require(!tradingIsEnabled, "Project already launched."); nAntiBotBlocks = _nAntiBotBlocks; launchBlock = block.number; tradingIsEnabled = true; antiBotActive = true; emit Launch(nAntiBotBlocks); } function setFees(uint256 marketingFee, uint256 liquidityFee, uint256 taxFee) public onlyOwner{ require(0 <= taxFee && taxFee <= 6, "Requested tax fee out of acceptable range."); require(0 <= liquidityFee && liquidityFee <= 6 , "Requested liquidity fee out of acceptable range."); require(0 <= marketingFee && marketingFee <= 6, "Requested marketing fee out of acceptable range."); require(0 < marketingFee + liquidityFee, "Total liquidity fee amount must be strictly positive."); _taxFee = taxFee; _liquidityFee = liquidityFee; _marketingFee = marketingFee; _totalLPFee = _liquidityFee + _marketingFee; emit SetFees(_liquidityFee, _marketingFee, _taxFee); } function setTradeRestrictions(uint256 _maxTx, uint256 _maxWallet) public onlyOwner{ require(_maxTx * DECIMALS >= (5 * _tTotal / 1000), "Requested max transaction amount too low."); require(_maxWallet * DECIMALS >= (20 * _tTotal / 1000), "Requested max allowable wallet amount too low."); maxTx = _maxTx * DECIMALS; maxWallet = _maxWallet * DECIMALS; emit SetTradeRestrictions(maxTx, maxWallet); } function setSwapTokensAtAmount(uint256 _swapTokensAtAmount) public onlyOwner{ require(_tTotal / 1000 <= _swapTokensAtAmount * DECIMALS && _swapTokensAtAmount * DECIMALS <= 2 * _tTotal / 100, "Requested contract swap amount out of acceptable range."); swapTokensAtAmount = _swapTokensAtAmount * DECIMALS; emit SetSwapTokensAtAmount(swapTokensAtAmount); } function checkValidTrade(address from, address to, uint256 amount) private view{ if (from != owner() && to != owner() && to != deadAddress) { require(tradingIsEnabled, "Project has yet to launch."); require(amount <= maxTx, "Transfer amount exceeds the max allowable."); if (automatedMarketMakerPairs[from]){ require(balanceOf(address(to)) + amount <= maxWallet, "Token purchase implies violation of max allowable wallet amount restriction."); } } } function _transfer(address from, address to, uint256 amount) private { if(amount == 0) { return; } checkValidTrade(from, to, amount); bool takeFee = tradingIsEnabled && !swapping; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if(takeFee && antiBotActive) { uint256 fees; if(block.number < launchBlock + nAntiBotBlocks){ fees = amount * 99 / 100; amount = amount - fees; takeFee = false; _tokenTransfer(from, address(this), fees, takeFee); } else{ antiBotActive = false; } } if(accumulatingForBurn){ if(shouldBurn()){ burn(burnAmount); } } else if(shouldSwap(to)) { swapTokens(swapTokensAtAmount); } _tokenTransfer(from, to, amount, takeFee); } function shouldBurn() private view returns (bool){ uint256 contractTokenBalance = balanceOf(address(this)); bool canBurn = contractTokenBalance >= burnAmount; return tradingIsEnabled && canBurn && !inBurn && !antiBotActive; } function burn(uint256 _burnAmount) private inburn { uint256 currentRate = _getRate(); uint256 rBurn = _burnAmount * currentRate; _rOwned[address(this)] = _rOwned[address(this)] - rBurn; _rOwned[deadAddress] = _rOwned[deadAddress] + rBurn; _tOwned[deadAddress] = _tOwned[deadAddress] + _burnAmount; emit Transfer(address(this), deadAddress, _burnAmount); accumulatingForBurn = false; } function shouldSwap(address to) private view returns (bool){ uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; return tradingIsEnabled && canSwap && !swapping && automatedMarketMakerPairs[to] && !antiBotActive; } function swapTokens(uint256 tokens) inSwap private { uint256 LPtokens = tokens * _liquidityFee / _totalLPFee; uint256 halfLPTokens = LPtokens / 2; uint256 marketingtokens = tokens - LPtokens; uint256 initialBalance = address(this).balance; swapTokensForEth(halfLPTokens + marketingtokens); uint256 newBalance = address(this).balance - initialBalance; // alpha = _liquidityFee.div(_totalLPFee).div(2); // bnbForLP = newBalance.mul(alpha).div(1 - alpha); uint256 bnbForLP = newBalance * _liquidityFee / _totalLPFee / 2 / ( 1e3 - 1e3 * _liquidityFee / _totalLPFee / 2 ) * 1e3; uint256 bnbForMarketing = newBalance - bnbForLP; (bool temp,) = payable(marketingAddress).call{value: bnbForMarketing, gas: 30000}(""); temp; //warning-suppresion addLiquidity(halfLPTokens, bnbForLP); emit SwapAndLiquify(halfLPTokens, bnbForLP); //69e18 } 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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function planBurn(uint256 _burnNumerator, uint256 _burnDenominator) public onlyAuthorized { burnAmount = _tTotal * _burnNumerator / _burnDenominator; accumulatingForBurn = true; } function buybackStuckBNB(uint256 percent) public onlyAuthorized { uint256 amountToBuyBack = address(this).balance * percent / 100; // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountToBuyBack}( 0, // accept any amount of Tokens path, deadAddress, block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender); _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender); _rOwned[sender] = _rOwned[sender] - rAmount; _tOwned[recipient] = _tOwned[recipient] + tTransferAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender); _tOwned[sender] = _tOwned[sender] - tAmount; _rOwned[sender] = _rOwned[sender] - rAmount; _rOwned[recipient] = _rOwned[recipient] + rTransferAmount; _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function airdrop(address sender, address[] calldata recipients, uint256[] calldata values) external onlyOwner { require(recipients.length == values.length, "Mismatch between Address and token count"); for (uint256 i = 0; i < recipients.length; i++) { _transfer(sender, recipients[i], values[i] * DECIMALS); } } receive() external payable {} }
warning-suppresion
(bool temp,) = payable(marketingAddress).call{value: bnbForMarketing, gas: 30000}(""); temp;
12,553,302
[ 1, 8551, 17, 2859, 12202, 285, 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, 3639, 261, 6430, 1906, 16, 13, 273, 8843, 429, 12, 3355, 21747, 1887, 2934, 1991, 95, 1132, 30, 324, 6423, 1290, 3882, 21747, 16, 16189, 30, 890, 2787, 97, 2932, 8863, 1906, 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 ]
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // Slightly modified Zeppelin&#39;s Vested Token deriving MiniMeToken /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /* Copyright 2016, Jordi Baylina 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/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract&#39;s goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO&#39;s /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token&#39;s name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to issue the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @param _owner The address that&#39;s balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // 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 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint256 _amount ) onlyController returns (bool) { uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint256 previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract&#39;s controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) * * Based on VestedToken.sol from https://github.com/OpenZeppelin/zeppelin-solidity * * Math – Copyright (c) 2016 Smart Contract Solutions, Inc. * SafeMath – Copyright (c) 2016 Smart Contract Solutions, Inc. * MiniMeToken – Copyright 2017, Jordi Baylina (Giveth) **/ // @dev MiniMeIrrevocableVestedToken is a derived version of MiniMeToken adding the // ability to createTokenGrants which are basically a transfer that limits the // receiver of the tokens how can he spend them over time. // For simplicity, token grants are not saved in MiniMe type checkpoints. // Vanilla cloning ESCBCoin will clone it into a MiniMeToken without vesting. // More complex cloning could account for past vesting calendars. contract MiniMeIrrevocableVestedToken is MiniMeToken { using SafeMath for uint256; uint256 MAX_GRANTS_PER_ADDRESS = 20; // Keep the struct at 2 stores (1 slot for value + 64 * 3 (dates) + 20 (address) = 2 slots // (2nd slot is 212 bytes, lower than 256)) struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint64 start, uint64 cliff, uint64 vesting, uint256 grantId); mapping (address => bool) canCreateGrants; address vestingWhitelister; modifier canTransfer(address _sender, uint _value) { require(_value <= spendableBalanceOf(_sender)); _; } modifier onlyVestingWhitelister { require(msg.sender == vestingWhitelister); _; } function MiniMeIrrevocableVestedToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) { vestingWhitelister = msg.sender; doSetCanCreateGrants(vestingWhitelister, true); } // @dev Add canTransfer modifier before allowing transfer and transferFrom to go through function transfer(address _to, uint _value) canTransfer(msg.sender, _value) public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) public returns (bool success) { return super.transferFrom(_from, _to, _value); } function spendableBalanceOf(address _holder) constant public returns (uint) { return transferableTokens(_holder, uint64(now)); } /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool Token can be revoked with send amount to back. * @param _burnsOnRevoke bool Token can be revoked with send amount to back and destroyed. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(canCreateGrants[msg.sender]); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, _cliff, _vesting, _start, count - 1); } function setCanCreateGrants(address _addr, bool _allowed) onlyVestingWhitelister public { doSetCanCreateGrants(_addr, _allowed); } function doSetCanCreateGrants(address _addr, bool _allowed) internal { canCreateGrants[_addr] = _allowed; } function changeVestingWhitelister(address _newWhitelister) onlyVestingWhitelister public { doSetCanCreateGrants(vestingWhitelister, false); vestingWhitelister = _newWhitelister; doSetCanCreateGrants(vestingWhitelister, true); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; var previousBalanceReceiver = balanceOfAt(receiver, block.number); //balances[receiver] = balances[receiver].add(nonVested); updateValueAtNow(balances[receiver], previousBalanceReceiver + nonVested); var previousBalance_holder = balanceOfAt(_holder, block.number); //balances[_holder] = balances[_holder].sub(nonVested); updateValueAtNow(balances[_holder], previousBalance_holder - nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder&#39;s total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) public view returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return Math.min256(vestedTransferable, balanceOf(holder)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) public view returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint256 representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) internal view returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above&#39;s figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) public view returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { // Of all the tokens of the grant, how many of them are not vested? // grantValue - vestedTokens return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = Math.max64(grants[holder][i].vesting, date); } } } /** * Dividends * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Adam Dossa * Based on ProfitSharingContract.sol from https://github.com/adamdossa/ProfitSharingContract **/ contract MiniMeIrrVesDivToken is MiniMeIrrevocableVestedToken { event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim); event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); uint256 public RECYCLE_TIME = 1 years; function MiniMeIrrVesDivToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeIrrevocableVestedToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) {} struct Dividend { uint256 blockNumber; uint256 timestamp; uint256 amount; uint256 claimedAmount; uint256 totalSupply; bool recycled; mapping (address => bool) claimed; } Dividend[] public dividends; mapping (address => uint256) dividendsClaimed; modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length); _; } function depositDividend() public payable onlyController { uint256 currentSupply = super.totalSupplyAt(block.number); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), msg.value, 0, currentSupply, false ) ); DividendDeposited(msg.sender, blockNumber, getNow(), msg.value, currentSupply, dividendIndex); } function claimDividend(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.claimed[msg.sender] == false); require(dividend.recycled == false); uint256 balance = super.balanceOfAt(msg.sender, dividend.blockNumber); uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply); dividend.claimed[msg.sender] = true; dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim); if (claim > 0) { msg.sender.transfer(claim); DividendClaimed(msg.sender, _dividendIndex, claim); } } function claimDividendAll() public { require(dividendsClaimed[msg.sender] < dividends.length); for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) { if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) { dividendsClaimed[msg.sender] = SafeMath.add(i, 1); claimDividend(i); } } } function recycleDividend(uint256 _dividendIndex) public onlyController validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.recycled == false); require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME)); dividends[_dividendIndex].recycled = true; uint256 currentSupply = super.totalSupplyAt(block.number); uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), remainingAmount, 0, currentSupply, false ) ); DividendRecycled(msg.sender, blockNumber, getNow(), remainingAmount, currentSupply, dividendIndex); } function getNow() internal constant returns (uint256) { return now; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) **/ contract ESCBCoin is MiniMeIrrVesDivToken { // @dev ESCBCoin constructor just parametrizes the MiniMeIrrVesDivToken constructor function ESCBCoin ( address _tokenFactory ) public MiniMeIrrVesDivToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent "ESCB token", // Token name 18, // Decimals "ESCB", // Symbol true // Enable transfers ) {} } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) **/ /* @notice The ESCBCoinPlaceholder contract will take control over the ESCB coin after the sale is finalized and before the EscrowBlock Network is deployed. The contract allows for ESCBCoin transfers and transferFrom and implements the logic for transfering control of the token to the network when the sale asks it to do so. */ contract ESCBCoinPlaceholder is TokenController { address public tokenSale; ESCBCoin public token; function ESCBCoinPlaceholder(address _sale, address _ESCBCoin) public { tokenSale = _sale; token = ESCBCoin(_ESCBCoin); } function changeController(address network) public { assert(msg.sender == tokenSale); token.changeController(network); selfdestruct(network); // network gets all amount } // In between the sale and the network. Default settings for allowing token transfers. function proxyPayment(address _owner) public payable returns (bool) { revert(); return false; } function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } } // @dev Contract to hold sale raised funds during the sale period. // Prevents attack in which the ESCB Multisig sends raised ether // to the sale contract to mint tokens to itself, and getting the // funds back immediately. contract AbstractSale { function saleFinalized() public returns (bool); function minGoalReached() public returns (bool); } contract SaleWallet { using SafeMath for uint256; enum State { Active, Refunding } State public currentState; mapping (address => uint256) public deposited; //Events event Withdrawal(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Deposit(address beneficiary, uint256 weiAmount); // Public variables address public multisig; AbstractSale public tokenSale; // @dev Constructor initializes public variables // @param _multisig The address of the multisig that will receive the funds // @param _tokenSale The address of the token sale function SaleWallet(address _multisig, address _tokenSale) { currentState = State.Active; multisig = _multisig; tokenSale = AbstractSale(_tokenSale); } // @dev Receive all sent funds and build the refund map function deposit(address investor, uint256 amount) public { require(currentState == State.Active); require(msg.sender == address(tokenSale)); deposited[investor] = deposited[investor].add(amount); Deposit(investor, amount); } // @dev Withdraw function sends all the funds to the wallet if conditions are correct function withdraw() public { require(currentState == State.Active); assert(msg.sender == multisig); // Only the multisig can request it if (tokenSale.minGoalReached()) { // Allow when sale reached minimum goal return doWithdraw(); } } function doWithdraw() internal { assert(multisig.send(this.balance)); Withdrawal(); } function enableRefunds() public { require(currentState == State.Active); assert(msg.sender == multisig); // Only the multisig can request it require(!tokenSale.minGoalReached()); // Allow when minimum goal isn&#39;t reached require(tokenSale.saleFinalized()); // Allow when sale is finalized currentState = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(currentState == State.Refunding); require(msg.sender == address(tokenSale)); require(deposited[investor] != 0); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; assert(investor.send(depositedValue)); Refunded(investor, depositedValue); } // @dev Receive all sent funds function () public payable {} } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) * Copyright 2017, Jordi Baylina (Giveth) * * Based on SampleCampaign-TokenController.sol from https://github.com/Giveth/minime * This is the new token sale smart contract for conduction IITO and Airdrop together, * also it will allow having a stable price for some period after exchange listing. **/ contract ESCBTokenSale is TokenController { uint256 public initialTime; // Time in which the sale starts. Inclusive. sale will be opened at initial time. uint256 public controlTime; // The Unix time in which the sale needs to check on the refunding start. uint256 public price; // Number of wei-ESCBCoin tokens for 1 ether address public ESCBDevMultisig; // The address to hold the funds donated uint256 public affiliateBonusPercent = 2; // Purpose in percentage of payment via referral uint256 public totalCollected = 0; // In wei bool public saleStopped = false; // Has ESCB Dev stopped the sale? bool public saleFinalized = false; // Has ESCB Dev finalized the sale? mapping (address => bool) public activated; // Address confirmates that wants to activate the sale ESCBCoin public token; // The token ESCBCoinPlaceholder public networkPlaceholder; // The network placeholder SaleWallet public saleWallet; // Wallet that receives all sale funds uint256 constant public dust = 1 finney; // Minimum investment uint256 public minGoal; // amount of minimum fund in wei uint256 public goal; // Goal for IITO in wei uint256 public currentStage = 1; // Current stage uint256 public allocatedStage = 1; // Current stage when was allocated tokens for ESCB uint256 public usedTotalSupply = 0; // This uses for calculation ESCB allocation part event ActivatedSale(); event FinalizedSale(); event NewBuyer(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount); event NewExternalFoundation(address indexed holder, uint256 ESCBCoinAmount, uint256 etherAmount, bytes32 externalId); event AllocationForESCBFund(address indexed holder, uint256 ESCBCoinAmount); event NewStage(uint64 numberStage); // @dev There are several checks to make sure the parameters are acceptable // @param _initialTime The Unix time in which the sale starts // @param _controlTime The Unix time in which the sale needs to check on the refunding start // @param _ESCBDevMultisig The address that will store the donated funds and manager for the sale // @param _price The price. Price in wei-ESCBCoin per wei function ESCBTokenSale (uint _initialTime, uint _controlTime, address _ESCBDevMultisig, uint256 _price) non_zero_address(_ESCBDevMultisig) { assert (_initialTime >= getNow()); assert (_initialTime < _controlTime); // Save constructor arguments as global variables initialTime = _initialTime; controlTime = _controlTime; ESCBDevMultisig = _ESCBDevMultisig; price = _price; } modifier only(address x) { require(msg.sender == x); _; } modifier only_before_sale { require(getNow() < initialTime); _; } modifier only_during_sale_period { require(getNow() >= initialTime); // if minimum goal is reached, then infinite time to reach the main goal require(getNow() < controlTime || minGoalReached()); _; } modifier only_after_sale { require(getNow() >= controlTime || goalReached()); _; } modifier only_sale_stopped { require(saleStopped); _; } modifier only_sale_not_stopped { require(!saleStopped); _; } modifier only_before_sale_activation { require(!isActivated()); _; } modifier only_sale_activated { require(isActivated()); _; } modifier only_finalized_sale { require(getNow() >= controlTime || goalReached()); require(saleFinalized); _; } modifier non_zero_address(address x) { require(x != 0); _; } modifier minimum_value(uint256 x) { require(msg.value >= x); _; } // @notice Deploy ESCBCoin is called only once to setup all the needed contracts. // @param _token: Address of an instance of the ESCBCoin token // @param _networkPlaceholder: Address of an instance of ESCBCoinPlaceholder // @param _saleWallet: Address of the wallet receiving the funds of the sale // @param _minGoal: Minimum fund for success // @param _goal: The end fund amount function setESCBCoin(address _token, address _networkPlaceholder, address _saleWallet, uint256 _minGoal, uint256 _goal) payable non_zero_address(_token) only(ESCBDevMultisig) public { // 3 times by non_zero_address is not working for current compiler version require(_networkPlaceholder != 0); require(_saleWallet != 0); // Assert that the function hasn&#39;t been called before, as activate will happen at the end assert(!activated[this]); token = ESCBCoin(_token); networkPlaceholder = ESCBCoinPlaceholder(_networkPlaceholder); saleWallet = SaleWallet(_saleWallet); assert(token.controller() == address(this)); // sale is controller assert(token.totalSupply() == 0); // token is empty assert(networkPlaceholder.tokenSale() == address(this)); // placeholder has reference to Sale assert(networkPlaceholder.token() == address(token)); // placeholder has reference to ESCBCoin assert(saleWallet.multisig() == ESCBDevMultisig); // receiving wallet must match assert(saleWallet.tokenSale() == address(this)); // watched token sale must be self assert(_minGoal > 0); // minimum goal is not empty assert(_goal > 0); // the main goal is not empty assert(_minGoal < _goal); // minimum goal is less than the main goal minGoal = _minGoal; goal = _goal; // Contract activates sale as all requirements are ready doActivateSale(this); } function activateSale() public { doActivateSale(msg.sender); ActivatedSale(); } function doActivateSale(address _entity) non_zero_address(token) // cannot activate before setting token only_before_sale private { activated[_entity] = true; } // @notice Whether the needed accounts have activated the sale. // @return Is sale activated function isActivated() constant public returns (bool) { return activated[this] && activated[ESCBDevMultisig]; } // @notice Get the price for tokens for the current stage // @param _amount the amount for which the price is requested // @return Number of wei-ESCBToken function getPrice(uint256 _amount) only_during_sale_period only_sale_not_stopped only_sale_activated constant public returns (uint256) { return priceForStage(SafeMath.mul(_amount, price)); } // @notice Get the bonus tokens for a stage // @param _amount the amount of tokens // @return Number of wei-ESCBCoin with bonus for 1 wei function priceForStage(uint256 _amount) internal returns (uint256) { if (totalCollected >= 0 && totalCollected <= 80 ether) { // 1 ETH = 500 USD, then 40 000 USD 1 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 20), 100)); } if (totalCollected > 80 ether && totalCollected <= 200 ether) { // 1 ETH = 500 USD, then 100 000 USD 2 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 18), 100)); } if (totalCollected > 200 ether && totalCollected <= 400 ether) { // 1 ETH = 500 USD, then 200 000 USD 3 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 16), 100)); } if (totalCollected > 400 ether && totalCollected <= 1000 ether) { // 1 ETH = 500 USD, then 500 000 USD 4 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 14), 100)); } if (totalCollected > 1000 ether && totalCollected <= 2000 ether) { // 1 ETH = 500 USD, then 1 000 000 USD 5 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 12), 100)); } if (totalCollected > 2000 ether && totalCollected <= 4000 ether) { // 1 ETH = 500 USD, then 2 000 000 USD 6 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 10), 100)); } if (totalCollected > 4000 ether && totalCollected <= 8000 ether) { // 1 ETH = 500 USD, then 4 000 000 USD 7 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 8), 100)); } if (totalCollected > 8000 ether && totalCollected <= 12000 ether) { // 1 ETH = 500 USD, then 6 000 000 USD 8 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 6), 100)); } if (totalCollected > 12000 ether && totalCollected <= 16000 ether) { // 1 ETH = 500 USD, then 8 000 000 USD 9 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 4), 100)); } if (totalCollected > 16000 ether && totalCollected <= 20000 ether) { // 1 ETH = 500 USD, then 10 000 000 USD 10 stage return SafeMath.add(_amount, SafeMath.div(SafeMath.mul(_amount, 2), 100)); } if (totalCollected > 20000 ether) { // without bonus return _amount; } } // ESCBDevMultisig can use this function for allocation tokens // for ESCB Foundation by each stage, start from 2nd // Amount of stages can not be more than MAX_GRANTS_PER_ADDRESS function allocationForESCBbyStage() only(ESCBDevMultisig) public { if (totalCollected >= 0 && totalCollected <= 80 ether) { // 1 ETH = 500 USD, then 40 000 USD 1 stage currentStage = 1; } if (totalCollected > 80 ether && totalCollected <= 200 ether) { // 1 ETH = 500 USD, then 100 000 USD 2 stage currentStage = 2; } if (totalCollected > 200 ether && totalCollected <= 400 ether) { // 1 ETH = 500 USD, then 200 000 USD 3 stage currentStage = 3; } if (totalCollected > 400 ether && totalCollected <= 1000 ether) { // 1 ETH = 500 USD, then 500 000 USD 4 stage currentStage = 4; } if (totalCollected > 1000 ether && totalCollected <= 2000 ether) { // 1 ETH = 500 USD, then 1 000 000 USD 5 stage currentStage = 5; } if (totalCollected > 2000 ether && totalCollected <= 4000 ether) { // 1 ETH = 500 USD, then 2 000 000 USD 6 stage currentStage = 6; } if (totalCollected > 4000 ether && totalCollected <= 8000 ether) { // 1 ETH = 500 USD, then 4 000 000 USD 7 stage currentStage = 7; } if (totalCollected > 8000 ether && totalCollected <= 12000 ether) { // 1 ETH = 500 USD, then 6 000 000 USD 8 stage currentStage = 8; } if (totalCollected > 12000 ether && totalCollected <= 16000 ether) { // 1 ETH = 500 USD, then 8 000 000 USD 9 stage currentStage = 9; } if (totalCollected > 16000 ether && totalCollected <= 20000 ether) { // 1 ETH = 500 USD, then 10 000 000 USD 10 stage currentStage = 10; } if(currentStage > allocatedStage) { // ESCB Foundation owns 30% of the total number of emitted tokens. // totalSupply here 66%, then we 30%/66% to get amount 30% of tokens uint256 ESCBTokens = SafeMath.div(SafeMath.mul(SafeMath.sub(uint256(token.totalSupply()), usedTotalSupply), 15), 33); uint256 prevTotalSupply = uint256(token.totalSupply()); if(token.generateTokens(address(this), ESCBTokens)) { allocatedStage = currentStage; usedTotalSupply = prevTotalSupply; uint64 cliffDate = uint64(SafeMath.add(uint256(now), 365 days)); uint64 vestingDate = uint64(SafeMath.add(uint256(now), 547 days)); token.grantVestedTokens(ESCBDevMultisig, ESCBTokens, uint64(now), cliffDate, vestingDate, true, false); AllocationForESCBFund(ESCBDevMultisig, ESCBTokens); } else { revert(); } } } // @notice Notifies the controller about a transfer, for this sale all // transfers are allowed by default and no extra notifications are needed // @param _from The origin of the transfer // @param _to The destination of the transfer // @param _amount The amount of the transfer // @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns (bool) { return true; } // @notice Notifies the controller about an approval, for this sale all // approvals are allowed by default and no extra notifications are needed // @param _owner The address that calls `approve()` // @param _spender The spender in the `approve()` call // @param _amount The amount in the `approve()` call // @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns (bool) { return true; } // @dev The fallback function is called when ether is sent to the contract, it // simply calls `doPayment()` with the address that sent the ether as the // `_owner`. Payable is a require solidity modifier for functions to receive // ether, without this modifier functions will throw if ether is sent to them function () public payable { doPayment(msg.sender); } // @dev This function allow to get bonus tokens for a buyer and for referral function paymentAffiliate(address _referral) non_zero_address(_referral) payable public { uint256 boughtTokens = doPayment(msg.sender); uint256 affiliateBonus = SafeMath.div( SafeMath.mul(boughtTokens, affiliateBonusPercent), 100 ); // Calculate how many bonus tokens need to add assert(token.generateTokens(_referral, affiliateBonus)); assert(token.generateTokens(msg.sender, affiliateBonus)); } //////////// // Controller interface //////////// // @notice `proxyPayment()` allows the caller to send ether to the Token directly and // have the tokens created in an address of their choosing // @param _owner The address that will hold the newly created tokens function proxyPayment(address _owner) payable public returns (bool) { doPayment(_owner); return true; } // @dev `doPayment()` is an internal function that sends the ether that this // contract receives to the ESCBDevMultisig and creates tokens in the address of the sender // @param _owner The address that will hold the newly created tokens function doPayment(address _owner) only_during_sale_period only_sale_not_stopped only_sale_activated non_zero_address(_owner) minimum_value(dust) internal returns (uint256) { assert(totalCollected + msg.value <= goal); // If goal is reached, throw uint256 boughtTokens = priceForStage(SafeMath.mul(msg.value, price)); // Calculate how many tokens bought saleWallet.transfer(msg.value); // Send funds to multisig saleWallet.deposit(_owner, msg.value); // Send info about deposit to multisig assert(token.generateTokens(_owner, boughtTokens)); // Allocate tokens. totalCollected = SafeMath.add(totalCollected, msg.value); // Save total collected amount NewBuyer(_owner, boughtTokens, msg.value); return boughtTokens; } // @notice Function for issuing new tokens for address which made purchasing not in // ETH currency, for example via cards or wire transfer. // @dev Only ESCB Dev can do it with the publishing of transaction id in an external system. // Any audits will be able to confirm eligibility of issuing in such case. // @param _owner The address that will hold the newly created tokens // @param _amount Amount of purchasing in ETH function issueWithExternalFoundation(address _owner, uint256 _amount, bytes32 _extId) only_during_sale_period only_sale_not_stopped only_sale_activated non_zero_address(_owner) only(ESCBDevMultisig) public returns (uint256) { assert(totalCollected + _amount <= goal); // If goal is reached, throw uint256 boughtTokens = priceForStage(SafeMath.mul(_amount, price)); // Calculate how many tokens bought assert(token.generateTokens(_owner, boughtTokens)); // Allocate tokens. totalCollected = SafeMath.add(totalCollected, _amount); // Save total collected amount // Events NewBuyer(_owner, boughtTokens, _amount); NewExternalFoundation(_owner, boughtTokens, _amount, _extId); return boughtTokens; } // @notice Function to stop sale for an emergency. // @dev Only ESCB Dev can do it after it has been activated. function emergencyStopSale() only_sale_activated only_sale_not_stopped only(ESCBDevMultisig) public { saleStopped = true; } // @notice Function to restart stopped sale. // @dev Only ESCB Dev can do it after it has been disabled and sale is ongoing. function restartSale() only_during_sale_period only_sale_stopped only(ESCBDevMultisig) public { saleStopped = false; } // @notice Finalizes sale when main goal is reached or if for control time the minimum goal was not reached. // @dev Transfers the token controller power to the ESCBCoinPlaceholder. function finalizeSale() only_after_sale only(ESCBDevMultisig) public { token.changeController(networkPlaceholder); // Sale loses token controller power in favor of network placeholder saleFinalized = true; // Set finalized flag as true, that will allow enabling network deployment saleStopped = true; FinalizedSale(); } // @notice Deploy ESCB Network contract. // @param _networkAddress: The address the network was deployed at. function deployNetwork(address _networkAddress) only_finalized_sale non_zero_address(_networkAddress) only(ESCBDevMultisig) public { networkPlaceholder.changeController(_networkAddress); } // @notice Set up new ESCB Dev. // @param _newMultisig: The address new ESCB Dev. function setESCBDevMultisig(address _newMultisig) non_zero_address(_newMultisig) only(ESCBDevMultisig) public { ESCBDevMultisig = _newMultisig; } // @notice Get current unix time stamp function getNow() constant internal returns (uint) { return now; } // @notice If crowdsale is unsuccessful, investors can claim refunds here function claimRefund() only_finalized_sale public { require(!minGoalReached()); saleWallet.refund(msg.sender); } // @notice Check minimum goal for 1st stage function minGoalReached() public view returns (bool) { return totalCollected >= minGoal; } // @notice Check the main goal for 10th stage function goalReached() public view returns (bool) { return totalCollected >= goal; } }
placeholder has reference to ESCBCoin
assert(networkPlaceholder.token() == address(token));
2,303,013
[ 1, 12988, 711, 2114, 358, 512, 2312, 16283, 885, 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 ]
[ 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, 0 ]
[ 1, 377, 1815, 12, 5185, 14038, 18, 2316, 1435, 422, 1758, 12, 2316, 10019, 377, 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 ]
pragma solidity ^0.6.0; import "./Roles.sol"; /** * @title Hierarchy * @author Alberto Cuesta Canada * @notice Implements a dynamic role structure for Roles */ contract Hierarchy is Roles { event AdminRoleSet(bytes32 roleId, bytes32 adminRoleId); bytes32 public constant ROOT_ROLE_ID = ""; // adminRoles[roleId] is admin role of roleId. mapping (bytes32 => bytes32) private _adminRoles; /// @dev Create a root role, with itself as an admin role, and `root` as a member. constructor (address root) public { _addMember(root, ROOT_ROLE_ID); } /// @dev Restricted to members of the admin role of the one passed as a parameter. modifier onlyAdmin(bytes32 roleId) { require(isAdmin(msg.sender, roleId), "Restricted to admins."); _; } /// @dev Restricted to members of the role passed as a parameter. modifier onlyMember(bytes32 roleId) { require(hasRole(msg.sender, roleId), "Restricted to members."); _; } /// @dev Returns `true` if the account belongs to the admin role of the one passed as a parameter. function isAdmin(address account, bytes32 roleId) public view returns (bool) { return hasRole(account, _adminRoles[roleId]); } /// @dev Returns `true` if the `account` belongs to the role. function isMember(address account, bytes32 roleId) public view returns (bool) { return hasRole(account, roleId); } /// @dev Returns the admin role for `roleId`. function getAdminRole(bytes32 roleId) public view returns (bytes32) { return _adminRoles[roleId]; } /// @dev Create a new role with the specified admin role. function addAdminRole(bytes32 roleId, bytes32 adminRoleId) public onlyMember(adminRoleId) { _adminRoles[roleId] = adminRoleId; emit AdminRoleSet(roleId, adminRoleId); } /// @dev Add a member to a role, caller must belong to its admin role. function addMember(address account, bytes32 roleId) public onlyAdmin(roleId) { _addMember(account, roleId); } /// @dev Remove a member from a role, caller must belong to its admin role. function removeMember(address account, bytes32 roleId) public onlyAdmin(roleId) { _removeMember(account, roleId); } }
@dev Remove a member from a role, caller must belong to its admin role.
function removeMember(address account, bytes32 roleId) public onlyAdmin(roleId) { _removeMember(account, roleId); }
6,355,503
[ 1, 3288, 279, 3140, 628, 279, 2478, 16, 4894, 1297, 10957, 358, 2097, 3981, 2478, 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 ]
[ 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, 565, 445, 1206, 4419, 12, 2867, 2236, 16, 1731, 1578, 21152, 13, 203, 3639, 1071, 1338, 4446, 12, 4615, 548, 13, 288, 203, 3639, 389, 4479, 4419, 12, 4631, 16, 21152, 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, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; import "./Owned.sol"; import "./O2OControlled.sol"; contract O2OController is Owned { struct Controller { address addr; bool isControlled; bool isInitialized; } mapping (bytes32 => Controller) public contracts; bytes32[] public contractIds; /** * Constructor. */ function O2OController() public { registerContract(owner, "O2O.Owner", false); registerContract(address(this), "O2O.Controller", false); } /** * @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)); owner = _newOwner; setContract(_newOwner, "O2O.Owner", false); } /** * Store address of one contract in mapping. * @param _addr Address of contract * @param _id ID of contract */ function setContract(address _addr, bytes32 _id, bool _isControlled) internal { contracts[_id].addr = _addr; contracts[_id].isControlled = _isControlled; } /** * Get contract address from ID. This function is called by the * contract's setContracts function. * @param _id ID of contract * @return The address of the contract. */ function getContract(bytes32 _id) view public returns (address _addr) { _addr = contracts[_id].addr; } /** * Registration of contracts. * It will only accept calls of deployments initiated by the owner. * @param _id ID of contract * @return bool success */ function registerContract(address _addr, bytes32 _id, bool _isControlled) onlyOwner public returns (bool _result) { setContract(_addr, _id, _isControlled); contractIds.push(_id); _result = true; } /** * Deregister a contract. * In future, contracts should be exchangeable. * @param _id ID of contract * @return bool success */ function deregister(bytes32 _id) onlyOwner public returns (bool _result) { if (getContract(_id) == 0x0) { return false; } setContract(0x0, _id, false); _result = true; } /** * After deploying all contracts, this function is called and calls * setContracts() for every registered contract. * This call pulls the addresses of the needed contracts in the respective contract. * We assume that contractIds.length is small, so this won't run out of gas. */ function setAllContracts() onlyOwner view public { O2OControlled controlledContract; // TODO: Check for upper bound for i // i = 0 is O2O.Owner, we skip this. // check! for (uint i = 0; i < contractIds.length; i++) { if (contracts[contractIds[i]].isControlled == true) { controlledContract = O2OControlled(contracts[contractIds[i]].addr); controlledContract.setContracts(); } } } function setOneContract(uint i) onlyOwner view public { O2OControlled controlledContract; // TODO: Check for upper bound for i controlledContract = O2OControlled(contracts[contractIds[i]].addr); controlledContract.setContracts(); } /** * Destruct one contract. * @param _id ID of contract to destroy. */ function destructOne(bytes32 _id) onlyOwner public { address addr = getContract(_id); if (addr != 0x0) { O2OControlled(addr).destruct(); } } /** * Destruct all contracts. * We assume that contractIds.length is small, so this won't run out of gas. * Otherwise, you can still destroy one contract after the other with destructOne. */ function destructAll() onlyOwner public { // TODO: Check for upper bound for i for (uint i = 0; i < contractIds.length; i++) { if (contracts[contractIds[i]].isControlled == true) { destructOne(contractIds[i]); } } selfdestruct(owner); } }
* Get contract address from ID. This function is called by the contract's setContracts function. @param _id ID of contract @return The address of the contract./
function getContract(bytes32 _id) view public returns (address _addr) { _addr = contracts[_id].addr; }
886,616
[ 1, 967, 6835, 1758, 628, 1599, 18, 1220, 445, 353, 2566, 635, 326, 6835, 1807, 444, 20723, 445, 18, 225, 389, 350, 540, 1599, 434, 6835, 327, 1021, 1758, 434, 326, 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, 0, 0, 0, 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, 336, 8924, 12, 3890, 1578, 389, 350, 13, 1476, 1071, 1135, 261, 2867, 389, 4793, 13, 288, 203, 3639, 389, 4793, 273, 20092, 63, 67, 350, 8009, 4793, 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 ]
// Список глаголов, которые присоединяют правое предложное дополнение с предлогом WITH wordentry_set Verbs_Linking_WITH = { eng_verb:prepare{}, // Passover haminados are prepared with similar methods. eng_verb:replace{}, // Signs were replaced with rare character combinations. eng_verb:twin{}, // Enniskillen is twinned with Bielefeld, Germany. eng_verb:mark{}, // Each corner is marked with a pylon. eng_verb:thrill{}, // Stanley was absolutely thrilled with the film. eng_verb:end{}, // The two ended up with 23 tracks. eng_verb:bundle{}, // Some operating systems come bundled with them. eng_verb:train{}, // United States Marines train with the AK-47. eng_verb:receive{}, // The theory was largely received with ridicule; eng_verb:link{}, // Cantor linked the Absolute Infinite with God. eng_verb:provide{}, // Pakistan also provides Belarus with Military expertise. eng_verb:interfere{}, // Feelings of countertransference can interfere with therapy. eng_verb:contaminate{}, // The fish consumed by the birds are contaminated with pesticides. eng_verb:combine{}, eng_verb:cooperate{}, // The organisms cooperate with each other. eng_verb:compete{}, // The organisms compete with each other. eng_verb:test{}, // test this idea with an experiment eng_verb:enhance{}, eng_verb:associate{}, // Which interaction is most likely associated with the formation of non-volcanic mountains? eng_verb:spray{}, // A farmer sprayed his orange trees with a pesticide eng_verb:eat{}, // It is often eaten with pork crackling. eng_verb:bind{}, // Thymine binds only with adenine eng_verb:run{}, // I run with my dog eng_verb:come{}, // He came with them eng_verb:fight{}, // The soldiers fought with great courage eng_verb:sympathise{}, // We sympathise with you. eng_verb:well{}, // Her eyes welled with tears. eng_verb:swim{}, // These fish swim with a saltating motion. eng_verb:commute{}, // These operators commute with each other. eng_verb:pelt{}, // They pelted each other with snowballs. eng_verb:grapple{}, // The two men grappled with each other for several minutes. eng_verb:draw{}, // John is drawing with a pencil. eng_verb:meet{}, // I can't meet with you today. eng_verb:pulsate{}, // The city pulsated with music and excitement. eng_verb:wobble{}, // His voice wobbled with restrained emotion. eng_verb:re-enter{}, // You cannot re-enter the country with this visa. eng_verb:panel{}, // Panel the walls with wood. eng_verb:color{}, // Color the walls with paint in warm tones. eng_verb:radiate{}, // Her face radiated with happiness. eng_verb:beam{}, // She was beaming with joy. eng_verb:die{}, // I was dying with embarrassment when my little lie was discovered. eng_verb:cloud{}, // Their faces were clouded with sadness. eng_verb:zap{}, // This show zaps the viewers with some shocking scenes. eng_verb:sizzle{}, // She was sizzling with anger. eng_verb:seethe{}, // The customer was seething with anger. eng_verb:charge{}, // The speaker charged up the crowd with his inflammatory remarks. eng_verb:strike{}, // This writer strikes a chord with young women. eng_verb:render{}, // The face of the child is rendered with much tenderness in this painting. eng_verb:write{}, // Russian is written with the Cyrillic alphabet. eng_verb:interlude{}, // The guitar player interluded with a beautiful improvisation. eng_verb:lace{}, // The halo itself is laced with faint, narrow structures. eng_verb:button{}, // He cannot button his shirt with his slinged arm. eng_verb:tamper{}, // The machine will self-destruct if you tamper with it. eng_verb:suffocate{}, // The child suffocated herself with a plastic bag that the parents had left on the floor. eng_verb:retrofit{}, // The mansion was retrofitted with modern plumbing. eng_verb:spatter{}, // The baby spattered the bib with food. eng_verb:speckle{}, // Speckle the wall with tiny yellow spots. eng_verb:grain{}, // His hands were grained with dirt. eng_verb:speak{}, // He spoke with blithe ignorance of the true situation. eng_verb:fill{}, // The airport was filled with stormbound passengers. eng_verb:discontent{}, // He was discontented with his position. eng_verb:dust{}, // Everything was dusted over with a fine layer of soot. eng_verb:cover{}, // The wallpaper was covered all over with flowers. eng_verb:supply{}, // They were abundantly supplied with food. eng_verb:please{}, // His father was well pleased with his grades. eng_verb:clog{}, // The story was clogged with too many details. eng_verb:satisfy{}, // We are entirely satisfied with the meal. eng_verb:overgrow{}, // The patio overgrew with ivy. eng_verb:improve{}, // The editor improved the manuscript with his changes. eng_verb:correlate{}, // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. eng_verb:visit{}, // He was visited with a terrible illness that killed him quickly. eng_verb:defoliate{}, // Defoliate the trees with pesticides. eng_verb:act{}, // He acted with the best of motives. eng_verb:talk{}, // He talked short with everyone. eng_verb:bend{}, // He was bent double with pain. eng_verb:bore{}, // The housewife bored us with her domestically limited conversation. eng_verb:deal{}, // He dealt proficiently with the problem. eng_verb:decorate{}, // The temple was garishly decorated with bright plastic flowers. eng_verb:obsess{}, // I am maniacally obsessed with jealousy. eng_verb:endow{}, // The area is slenderly endowed with natural resources. eng_verb:flood{}, // The reactor meltdown was avoided by flooding it with water and boric acid eng_verb:play{}, // I will play the games with you eng_verb:shower{}, // He showered her with caresses. eng_verb:teem{}, // The oceans are teeming with life. eng_verb:help{}, // He helped us with this exercise eng_verb:hold{}, // He held the book with this eng_verb:burn{}, // I have burnt myself with the fireworks eng_verb:fiddle{}, // Don't fiddle with the screws. eng_verb:dance{}, // I do not dance with her eng_verb:go{}, // Those bolts go with these parts. eng_verb:walk{}, // They are walking with their son eng_verb:work{}, // He is currently working with new data eng_verb:stay{}, // The children are staying with their uncle and aunt eng_verb:start{}, // They started with us last year eng_verb:live{}, // I live with animals in a house eng_verb:avoid{}, // The reactor meltdown was avoided by flooding it with water and boric acid eng_verb:sit{}, // I sit with book in a chair eng_verb:cut{} // He cut the string with his penknife. }
Signs were replaced with rare character combinations.
eng_verb:replace{},
12,969,163
[ 1, 2766, 87, 4591, 8089, 598, 25671, 3351, 17265, 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 ]
[ 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, 24691, 67, 16629, 30, 2079, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x102D06dBeF61D6e0511d431cc6123F242B48482E/sources/contracts/others/AlcazarAirdrop.sol
* @notice Distribute the prizes to the three winners @dev This function must be called by the owner of the contract./
function callAirdrop() external onlyOwner { require(initialized, "Contract not initialized"); require(s_requestId == r_requestId, "Request IDs do not match"); require(s_randomWords.length == numWords, "Number of words does not match"); uint256 numHolders = distributors.length; require(numHolders > 3, "Not enough distributors"); s_requestId = 0; uint256[3] memory idx; uint256[3] memory sortedIdx; for (uint256 i = 0; i < 3; i++) { idx[i] = s_randomWords[i] % (numHolders - i); for (uint256 j = 0; j < i; j++) { if (idx[i] >= sortedIdx[j]) { idx[i] = idx[i] + 1; break; } } idx[i] = idx[i] % numHolders; sortedIdx[i] = idx[i]; if (i > 0 && sortedIdx[i] < sortedIdx[i - 1]) { uint256 t = sortedIdx[i]; sortedIdx[i] = sortedIdx[i - 1]; sortedIdx[i - 1] = t; } } AirdropResult storage airdropResult = results[currentID]; uint256 amount = token.balanceOf(address(this)); if(amount > totalStaked ) { amount -= totalStaked; } else amount = 0; amount = amount * distributeRate / 10000; for (uint256 i = 0; i < 3; i++) { address winnerA = distributors[idx[i]]; airdropResult.winner[i] = winnerA; uint256 amountA = amount * airdropRates[i] / 10000; airdropResult.amount[i] = amountA; token.safeTransfer(winnerA, amountA); } emit HolderDistributed(currentID, airdropResult.winner, airdropResult.amount); currentID = currentID + 1; lastAirdropTime = block.timestamp; distributors = new address[](0); }
3,207,172
[ 1, 1669, 887, 326, 846, 3128, 358, 326, 8925, 5657, 9646, 225, 1220, 445, 1297, 506, 2566, 635, 326, 3410, 434, 326, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 745, 37, 6909, 1764, 1435, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 13227, 16, 315, 8924, 486, 6454, 8863, 203, 3639, 2583, 12, 87, 67, 2293, 548, 422, 436, 67, 2293, 548, 16, 315, 691, 7115, 741, 486, 845, 8863, 203, 3639, 2583, 12, 87, 67, 9188, 7363, 18, 2469, 422, 818, 7363, 16, 315, 1854, 434, 4511, 1552, 486, 845, 8863, 203, 203, 3639, 2254, 5034, 818, 27003, 273, 1015, 665, 13595, 18, 2469, 31, 203, 3639, 2583, 12, 2107, 27003, 405, 890, 16, 315, 1248, 7304, 1015, 665, 13595, 8863, 203, 203, 3639, 272, 67, 2293, 548, 273, 374, 31, 203, 203, 3639, 2254, 5034, 63, 23, 65, 3778, 2067, 31, 203, 3639, 2254, 5034, 63, 23, 65, 3778, 3115, 4223, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 890, 31, 277, 27245, 288, 203, 5411, 2067, 63, 77, 65, 273, 272, 67, 9188, 7363, 63, 77, 65, 738, 261, 2107, 27003, 300, 277, 1769, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 277, 31, 525, 27245, 288, 203, 7734, 309, 261, 3465, 63, 77, 65, 1545, 3115, 4223, 63, 78, 5717, 288, 203, 10792, 2067, 63, 77, 65, 273, 2067, 63, 77, 65, 397, 404, 31, 203, 10792, 898, 31, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 2067, 63, 77, 65, 273, 2067, 63, 77, 65, 738, 818, 27003, 31, 203, 5411, 3115, 4223, 63, 77, 65, 273, 2067, 63, 77, 15533, 203, 5411, 309, 261, 77, 2 ]
pragma solidity ^0.4.15; /** * @title a collection of functions for manipulating the VM memory * @author Sami Mäkelä */ contract VMMemory { // a and b are integer values that represent 8 bytes each function toMemory(uint a, uint b) internal pure returns (uint8[]) { uint8[] memory arr = new uint8[](16); storeN(arr, 0, 8, a); storeN(arr, 8, 8, b); return arr; } function storeN(uint8[] mem, uint addr, uint n, uint v) internal pure { for (uint i = 0; i < n; i++) { mem[addr+i] = uint8(v); v = v/256; } } function loadN(uint8[] mem, uint addr, uint n) internal pure returns (uint) { uint res = 0; uint exp = 1; for (uint i = 0; i < n; i++) { res += mem[addr+i]*exp; exp = exp*256; } return res; } function fromMemory(uint8[] mem) internal pure returns (uint a, uint b) { a = loadN(mem, 0, 8); b = loadN(mem, 8, 8); } function typeSize(uint ty) internal pure returns (uint) { if (ty == 0) return 4; // I32 else if (ty == 1) return 8; // I64 else if (ty == 2) return 4; // F32 else if (ty == 3) return 8; // F64 } function store(uint8[] mem, uint addr, uint v, uint ty, uint packing) internal pure { if (packing == 0) storeN(mem, addr, typeSize(ty), v); else { // Only integers can be packed, also cannot pack I32 to 32-bit? require(ty < 2 && !(ty == 0 && packing == 4)); storeN(mem, addr, packing, v); } } function storeX(uint8[] mem, uint addr, uint v, uint hint) internal pure { store(mem, addr, v, (hint/2**3)&0x3, hint&0x7); } function load(uint8[] mem, uint addr, uint ty, uint packing, bool sign_extend) internal pure returns (uint) { if (packing == 0) return loadN(mem, addr, typeSize(ty)); else { require(ty < 2 && !(ty == 0 && packing == 4)); uint res = loadN(mem, addr, packing); if (sign_extend) { res = res | uint(-1)*2**(8*packing)*(res/2**(8*packing-1)); } if (ty == 0) res = res % (2**32); else res = res % (2**64); return res; } } function loadX(uint8[] mem, uint addr, uint hint) internal pure returns (uint) { return load(mem, addr, (hint/2**4)&0x3, (hint/2)&0x7, hint&0x1 == 1); } /* function test(uint a, uint b) returns (uint, uint) { return fromMemory(toMemory(a,b)); }*/ }
Only integers can be packed, also cannot pack I32 to 32-bit?
function store(uint8[] mem, uint addr, uint v, uint ty, uint packing) internal pure { if (packing == 0) storeN(mem, addr, typeSize(ty), v); else { require(ty < 2 && !(ty == 0 && packing == 4)); storeN(mem, addr, packing, v); } }
1,788,449
[ 1, 3386, 12321, 848, 506, 12456, 16, 2546, 2780, 2298, 467, 1578, 358, 3847, 17, 3682, 35, 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, 565, 445, 1707, 12, 11890, 28, 8526, 1663, 16, 2254, 3091, 16, 2254, 331, 16, 2254, 13806, 16, 2254, 2298, 310, 13, 2713, 16618, 288, 203, 3639, 309, 261, 2920, 310, 422, 374, 13, 1707, 50, 12, 3917, 16, 3091, 16, 618, 1225, 12, 4098, 3631, 331, 1769, 203, 3639, 469, 288, 203, 5411, 2583, 12, 4098, 411, 576, 597, 401, 12, 4098, 422, 374, 597, 2298, 310, 422, 1059, 10019, 203, 5411, 1707, 50, 12, 3917, 16, 3091, 16, 2298, 310, 16, 331, 1769, 203, 3639, 289, 203, 565, 289, 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 ]
pragma solidity 0.4.13; /** * @title Wallet Getter Library * @author Majoolr.io * * version 1.0.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Wallet Library family is inspired by the multisig wallets built by Consensys * at https://github.com/ConsenSys/MultiSigWallet and Parity at * https://github.com/paritytech/contracts/blob/master/Wallet.sol with added * functionality. Majoolr works on open source projects in the Ethereum * community with the purpose of testing, documenting, and deploying reusable * code onto the blockchain to improve security and usability of smart contracts. * Majoolr also strives to educate non-profits, schools, and other community * members about the application of blockchain technology. For further * information: majoolr.io, consensys.net, paritytech.io * * 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. */ library WalletGetterLib { /*Getter Functions*/ /// @dev Get list of wallet owners, will return fixed 50 until fork /// @param self Wallet in contract storage /// @return address[51] Returns entire 51 owner slots function getOwners(WalletMainLib.WalletData storage self) constant returns (address[51]) { address[51] memory o; for(uint i = 0; i<self.owners.length; i++){ o[i] = self.owners[i]; } return o; } /// @dev Get index of an owner /// @param self Wallet in contract storage /// @param _owner Address of owner /// @return uint Index of the owner function getOwnerIndex(WalletMainLib.WalletData storage self, address _owner) constant returns (uint) { return self.ownerIndex[_owner]; } /// @dev Get max number of wallet owners /// @param self Wallet in contract storage /// @return uint Maximum number of owners function getMaxOwners(WalletMainLib.WalletData storage self) constant returns (uint) { return self.maxOwners; } /// @dev Get number of wallet owners /// @param self Wallet in contract storage /// @return uint Number of owners function getOwnerCount(WalletMainLib.WalletData storage self) constant returns (uint) { return self.owners.length - 1; } /// @dev Get sig requirements for administrative changes /// @param self Wallet in contract storage /// @return uint Number of sigs required function getRequiredAdmin(WalletMainLib.WalletData storage self) constant returns (uint) { return self.requiredAdmin; } /// @dev Get sig requirements for minor tx spends /// @param self Wallet in contract storage /// @return uint Number of sigs required function getRequiredMinor(WalletMainLib.WalletData storage self) constant returns (uint) { return self.requiredMinor; } /// @dev Get sig requirements for major tx spends /// @param self Wallet in contract storage /// @return uint Number of sigs required function getRequiredMajor(WalletMainLib.WalletData storage self) constant returns (uint) { return self.requiredMajor; } /// @dev Get current day spend for token /// @param self Wallet in contract storage /// @param _token Address of token, 0 for ether /// @return uint[2] 0-index is day timestamp, 1-index is the day spend function getCurrentSpend(WalletMainLib.WalletData storage self, address _token) constant returns (uint[2]) { uint[2] memory cs; cs[0] = self.currentSpend[_token][0]; cs[1] = self.currentSpend[_token][1]; return cs; } /// @dev Get major tx threshold per token /// @param self Wallet in contract storage /// @param _token Address of token, 0 for ether /// @return uint Threshold amount function getMajorThreshold(WalletMainLib.WalletData storage self, address _token) constant returns (uint) { return self.majorThreshold[_token]; } /// @dev Get last 10 transactions for the day, fixed at 10 until fork /// @param self Wallet in contract storage /// @param _date Timestamp of day requested /// @return bytes32[10] Last 10 tx&#39;s starting with latest function getTransactions(WalletMainLib.WalletData storage self, uint _date) constant returns (bytes32[10]) { bytes32[10] memory t; uint li = self.transactions[_date].length - 1; for(uint i = li; i >= 0; i--){ t[li - i] = self.transactions[_date][i]; } return t; } /// @dev Get the number of tx&#39;s with the same id /// @param self Wallet in contract storage /// @param _id ID of transactions requested /// @return uint Number of tx&#39;s with same ID function getTransactionLength(WalletMainLib.WalletData storage self, bytes32 _id) constant returns (uint) { return self.transactionInfo[_id].length; } /// @dev Get list of confirmations for a tx, use getTransactionLength to get latest number /// @param self Wallet in contract storage /// @param _id ID of transaction requested /// @param _number The transaction index number /// @return uint256[50] Returns list of confirmations, fixed at 50 until fork function getTransactionConfirms(WalletMainLib.WalletData storage self, bytes32 _id, uint _number) constant returns (uint256[50]) { uint256[50] memory tc; for(uint i = 0; i<self.transactionInfo[_id][_number].confirmedOwners.length; i++){ tc[i] = self.transactionInfo[_id][_number].confirmedOwners[i]; } return tc; } /// @dev Retrieve tx confirmation count /// @param self Wallet in contract storage /// @param _id ID of transaction requested /// @param _number The transaction index number /// @return uint Returns the current number of tx confirmations function getTransactionConfirmCount(WalletMainLib.WalletData storage self, bytes32 _id, uint _number) constant returns(uint) { return self.transactionInfo[_id][_number].confirmCount; } /// @dev Retrieve if transaction was successful /// @param self Wallet in contract storage /// @param _id ID of transaction requested /// @param _number The transaction index number /// @return bool Returns true if tx successfully executed, false otherwise function getTransactionSuccess(WalletMainLib.WalletData storage self, bytes32 _id, uint _number) constant returns (bool) { return self.transactionInfo[_id][_number].success; } } pragma solidity 0.4.13; /** * @title Wallet Main Library * @author Majoolr.io * * version 1.0.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Wallet Library family is inspired by the multisig wallets built by Consensys * at https://github.com/ConsenSys/MultiSigWallet and Parity at * https://github.com/paritytech/contracts/blob/master/Wallet.sol with added * functionality. Majoolr works on open source projects in the Ethereum * community with the purpose of testing, documenting, and deploying reusable * code onto the blockchain to improve security and usability of smart contracts. * Majoolr also strives to educate non-profits, schools, and other community * members about the application of blockchain technology. For further * information: majoolr.io, consensys.net, paritytech.io * * 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. */ library WalletMainLib { using Array256Lib for uint256[]; using BasicMathLib for uint; struct WalletData { uint maxOwners; //Maximum wallet owners, should be 50 address[] owners; //Array of all owners uint requiredAdmin; //Number of sigs required for administrative changes uint requiredMajor; //Number of sigs required for major transactions uint requiredMinor; //Number of sigs required for minor transactions // The amount of a token spent per day, ether is at address mapping 0, // all other tokens defined by address. uint[0] corresponds to the current // day, uint[1] is the spend amount mapping (address => uint[2]) currentSpend; //The day spend threshold for transactions to be major, ether at 0, all others by address mapping (address => uint) majorThreshold; //Array of transactions per day, uint is the day timestamp, bytes32 is the transaction id mapping (uint => bytes32[]) transactions; //Tracks the index of each owner in the owners Array mapping (address => uint) ownerIndex; //Array of Transaction&#39;s by id, new tx&#39;s with exact inputs as previous tx will add to array mapping (bytes32 => Transaction[]) transactionInfo; } struct Transaction { uint day; //Timestamp of the day initialized uint value; //Amount of ether being sent address tokenAdress; //Address of token transferred uint amount; //Amount of tokens transferred bytes data; //Temp location for pending transactions, erased after final confirmation uint256[] confirmedOwners; //Array of owners confirming transaction uint confirmCount; //Tracks the number of confirms uint confirmRequired; //Number of sigs required for this transaction bool success; //True after final confirmation } /*Events*/ event LogRevokeNotice(bytes32 txid, address sender, uint confirmsNeeded); event LogTransactionFailed(bytes32 txid, address sender); event LogTransactionConfirmed(bytes32 txid, address sender, uint confirmsNeeded); event LogTransactionComplete(bytes32 txid, address target, uint value, bytes data); event LogContractCreated(address newContract, uint value); event LogErrMsg(string msg); /// @dev Constructor /// @param self The wallet in contract storage /// @param _owners Array of initial owners /// @param _requiredAdmin Set number of sigs for administrative tasks /// @param _requiredMajor Set number of sigs for major tx /// @param _requiredMinor Set number of sigs for minor tx /// @param _majorThreshold Set major tx threshold amount for ether /// @return Will return true when complete function init(WalletData storage self, address[] _owners, uint _requiredAdmin, uint _requiredMajor, uint _requiredMinor, uint _majorThreshold) returns (bool) { require(self.owners.length == 0); require(_owners.length >= _requiredAdmin && _requiredAdmin > 0); require(_owners.length >= _requiredMajor && _requiredMajor > 0); require(_owners.length >= _requiredMinor && _requiredMinor > 0); self.owners.push(0); //Leave index-0 empty for easier owner checks for (uint i=0; i<_owners.length; i++) { require(_owners[i] != 0); self.owners.push(_owners[i]); self.ownerIndex[_owners[i]] = i+1; } self.requiredAdmin = _requiredAdmin; self.requiredMajor = _requiredMajor; self.requiredMinor = _requiredMinor; self.maxOwners = 50; //Limits to 50 owners, should create wallet pools for more owners self.majorThreshold[0] = _majorThreshold; //Sets ether threshold at address 0 return true; } /*Checks*/ /// @dev Verifies a confirming owner has not confirmed already /// @param self Contract wallet in storage /// @param _id ID of the tx being checked /// @param _number Index number of this tx /// @return Returns true if check passes, false otherwise function checkNotConfirmed(WalletData storage self, bytes32 _id, uint _number) constant returns (bool) { require(self.ownerIndex[msg.sender] > 0); uint _txLen = self.transactionInfo[_id].length; if(_txLen == 0 || _number >= _txLen){ LogErrMsg("Tx not initiated"); LogTransactionFailed(_id, msg.sender); return false; } if(self.transactionInfo[_id][_number].success){ LogErrMsg("Transaction already complete"); LogTransactionFailed(_id, msg.sender); return false; } //Function from Majoolr.io array utility library bool found; uint index; (found, index) = self.transactionInfo[_id][_number].confirmedOwners.indexOf(uint(msg.sender), false); if(found){ LogErrMsg("Owner already confirmed"); LogTransactionFailed(_id, msg.sender); return false; } return true; } /*Utility Functions*/ /// @dev Used later to calculate the number of confirmations needed for tx /// @param _required Number of sigs required /// @param _count Current number of sigs function calcConfirmsNeeded(uint _required, uint _count) constant returns (uint){ return _required - _count; } /// @dev Used to check if tx is moving tokens and parses amount /// @param _txData Data for proposed tx /// @return bool True if transaction is moving tokens /// @return uint Amount of tokens involved, 0 if not spending tx function getAmount(bytes _txData) constant returns (bool,uint) { bytes32 getSig; bytes4 sig; bytes4 tSig = 0xa9059cbb; //transfer func signature bytes4 aSig = 0x095ea7b3; //approve func signature bytes4 tfSig = 0x23b872dd; //transferFrom func signature bool transfer; bytes32 _amountData; uint _amount; assembly { getSig := mload(add(_txData,0x20)) } sig = bytes4(getSig); if(sig == tSig || sig == aSig){ transfer = true; assembly { _amountData := mload(add(_txData,0x44)) } _amount = uint(_amountData); } else if(sig == tfSig){ transfer = true; assembly { _amountData := mload(add(_txData,0x64)) } _amount = uint(_amountData); } return (transfer,_amount); } /// @dev Retrieves sig requirement for spending tx /// @param self Contract wallet in storage /// @param _to Target address of transaction /// @param _value Amount of ether spend /// @param _isTransfer True if transferring other tokens, false otherwise /// @param _amount Amount of tokens being transferred, 0 if not a transfer tx /// @return uint The required sigs for tx function getRequired(WalletData storage self, address _to, uint _value, bool _isTransfer, uint _amount) returns (uint) { bool err; uint res; bool major = true; //Reset spend if this is first check of the day if((now/ 1 days) > self.currentSpend[0][0]){ self.currentSpend[0][0] = now / 1 days; self.currentSpend[0][1] = 0; } (err, res) = self.currentSpend[0][1].plus(_value); if(err){ LogErrMsg("Overflow eth spend"); return 0; } if(res < self.majorThreshold[0]) major = false; if(_to != 0 && _isTransfer){ if((now / 1 days) > self.currentSpend[_to][0]){ self.currentSpend[_to][0] = now / 1 days; self.currentSpend[_to][1] = 0; } (err, res) = self.currentSpend[_to][1].plus(_amount); if(err){ LogErrMsg("Overflow token spend"); return 0; } if(res >= self.majorThreshold[_to]) major = true; } return major ? self.requiredMajor : self.requiredMinor; } /// @dev Function to create new contract /// @param _txData Transaction data /// @param _value Amount of eth sending to new contract function createContract(bytes _txData, uint _value) { address _newContract; bool allGood; assembly { _newContract := create(_value, add(_txData, 0x20), mload(_txData)) allGood := gt(extcodesize(_newContract),0) } require(allGood); LogContractCreated(_newContract, _value); } /*Primary Function*/ /// @dev Create and execute transaction from wallet /// @param self Wallet in contract storage /// @param _to Address of target /// @param _value Amount of ether sending /// @param _txData Data for executing transaction /// @param _confirm True if confirming, false if revoking confirmation /// @param _data Message data passed from wallet contract /// @return bool Returns true if successful, false otherwise /// @return bytes32 Returns the tx ID, can be used for confirm/revoke functions function serveTx(WalletData storage self, address _to, uint _value, bytes _txData, bool _confirm, bytes _data) returns (bool,bytes32) { bytes32 _id = sha3("serveTx",_to,_value,_txData); uint _number = self.transactionInfo[_id].length; uint _required = self.requiredMajor; //Run checks if not called from generic confirm/revoke function if(msg.sender != address(this)){ bool allGood; uint _amount; // if the owner is revoking his/her confirmation but doesn&#39;t know the // specific transaction id hash if(!_confirm) { allGood = revokeConfirm(self, _id); return (allGood,_id); } else { // else confirming the transaction //if this is a new transaction id or if a previous identical transaction had already succeeded if(_number == 0 || self.transactionInfo[_id][_number - 1].success){ require(self.ownerIndex[msg.sender] > 0); //Reuse allGood due to stack limit if(_to != 0) (allGood,_amount) = getAmount(_txData); _required = getRequired(self, _to, _value, allGood,_amount); if(_required == 0) return (false, _id); // add this transaction to the wallets record and initialize the settings self.transactionInfo[_id].length++; self.transactionInfo[_id][_number].confirmRequired = _required; self.transactionInfo[_id][_number].day = now / 1 days; self.transactions[now / 1 days].push(_id); } else { // else the transaction is already pending _number--; // set the index to the index of the existing transaction //make sure the sender isn&#39;t already confirmed allGood = checkNotConfirmed(self, _id, _number); if(!allGood) return (false,_id); } } // add the senders confirmation to the transaction self.transactionInfo[_id][_number].confirmedOwners.push(uint(msg.sender)); self.transactionInfo[_id][_number].confirmCount++; }else { // else were calling from generic confirm/revoke function, set the // _number index to the index of the existing transaction _number--; } // if there are enough confirmations if(self.transactionInfo[_id][_number].confirmCount == self.transactionInfo[_id][_number].confirmRequired) { // execute the transaction self.currentSpend[0][1] += _value; self.currentSpend[_to][1] += _amount; self.transactionInfo[_id][_number].success = true; if(_to == 0){ //Failure is self contained in method createContract(_txData, _value); } else { require(_to.call.value(_value)(_txData)); } delete self.transactionInfo[_id][_number].data; LogTransactionComplete(_id, _to, _value, _data); } else { if(self.transactionInfo[_id][_number].data.length == 0) self.transactionInfo[_id][_number].data = _data; uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired, self.transactionInfo[_id][_number].confirmCount); LogTransactionConfirmed(_id, msg.sender, confirmsNeeded); } return (true,_id); } /*Confirm/Revoke functions using tx ID*/ /// @dev Confirms a current pending tx, will execute if final confirmation /// @param self Wallet in contract storage /// @param _id ID of the transaction /// @return Returns true if successful, false otherwise function confirmTx(WalletData storage self, bytes32 _id) returns (bool){ require(self.ownerIndex[msg.sender] > 0); uint _number = self.transactionInfo[_id].length; bool ret; if(_number == 0){ LogErrMsg("Tx not initiated"); LogTransactionFailed(_id, msg.sender); return false; } _number--; bool allGood = checkNotConfirmed(self, _id, _number); if(!allGood) return false; self.transactionInfo[_id][_number].confirmedOwners.push(uint256(msg.sender)); self.transactionInfo[_id][_number].confirmCount++; if(self.transactionInfo[_id][_number].confirmCount == self.transactionInfo[_id][_number].confirmRequired) { address a = address(this); require(a.call(self.transactionInfo[_id][_number].data)); } else { uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired, self.transactionInfo[_id][_number].confirmCount); LogTransactionConfirmed(_id, msg.sender, confirmsNeeded); ret = true; } return ret; } /// @dev Revokes a prior confirmation from sender, call with tx ID /// @param self Wallet in contract storage /// @param _id ID of the transaction /// @return Returns true if successful, false otherwise function revokeConfirm(WalletData storage self, bytes32 _id) returns (bool) { require(self.ownerIndex[msg.sender] > 0); uint _number = self.transactionInfo[_id].length; if(_number == 0){ LogErrMsg("Tx not initiated"); LogTransactionFailed(_id, msg.sender); return false; } _number--; if(self.transactionInfo[_id][_number].success){ LogErrMsg("Transaction already complete"); LogTransactionFailed(_id, msg.sender); return false; } //Function from Majoolr.io array utility library bool found; uint index; (found, index) = self.transactionInfo[_id][_number].confirmedOwners.indexOf(uint(msg.sender), false); if(!found){ LogErrMsg("Owner has not confirmed tx"); LogTransactionFailed(_id, msg.sender); return false; } self.transactionInfo[_id][_number].confirmedOwners[index] = 0; self.transactionInfo[_id][_number].confirmCount--; uint confirmsNeeded = calcConfirmsNeeded(self.transactionInfo[_id][_number].confirmRequired, self.transactionInfo[_id][_number].confirmCount); //Transaction removed if all sigs revoked but id remains in wallet transaction list if(self.transactionInfo[_id][_number].confirmCount == 0) self.transactionInfo[_id].length--; LogRevokeNotice(_id, msg.sender, confirmsNeeded); return true; } } pragma solidity ^0.4.13; /** * @title Array256 Library * @author Majoolr.io * * version 1.0.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Array256 Library provides a few utility functions to work with * storage uint256[] types in place. Majoolr works on open source projects in * the Ethereum community with the purpose of testing, documenting, and deploying * reusable code onto the blockchain to improve security and usability of smart * contracts. Majoolr also strives to educate non-profits, schools, and other * community members about the application of blockchain technology. * For further information: majoolr.io * * 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. */ library Array256Lib { /// @dev Sum vector /// @param self Storage array containing uint256 type variables /// @return sum The sum of all elements, does not check for overflow function sumElements(uint256[] storage self) constant returns(uint256 sum) { assembly { mstore(0x60,self_slot) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { sum := add(sload(add(sha3(0x60,0x20),i)),sum) } } } /// @dev Returns the max value in an array. /// @param self Storage array containing uint256 type variables /// @return maxValue The highest value in the array function getMax(uint256[] storage self) constant returns(uint256 maxValue) { assembly { mstore(0x60,self_slot) maxValue := sload(sha3(0x60,0x20)) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { switch gt(sload(add(sha3(0x60,0x20),i)), maxValue) case 1 { maxValue := sload(add(sha3(0x60,0x20),i)) } } } } /// @dev Returns the minimum value in an array. /// @param self Storage array containing uint256 type variables /// @return minValue The highest value in the array function getMin(uint256[] storage self) constant returns(uint256 minValue) { assembly { mstore(0x60,self_slot) minValue := sload(sha3(0x60,0x20)) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { switch gt(sload(add(sha3(0x60,0x20),i)), minValue) case 0 { minValue := sload(add(sha3(0x60,0x20),i)) } } } } /// @dev Finds the index of a given value in an array /// @param self Storage array containing uint256 type variables /// @param value The value to search for /// @param isSorted True if the array is sorted, false otherwise /// @return found True if the value was found, false otherwise /// @return index The index of the given value, returns 0 if found is false function indexOf(uint256[] storage self, uint256 value, bool isSorted) constant returns(bool found, uint256 index) { assembly{ mstore(0x60,self_slot) switch isSorted case 1 { let high := sub(sload(self_slot),1) let mid := 0 let low := 0 for { } iszero(gt(low, high)) { } { mid := div(add(low,high),2) switch lt(sload(add(sha3(0x60,0x20),mid)),value) case 1 { low := add(mid,1) } case 0 { switch gt(sload(add(sha3(0x60,0x20),mid)),value) case 1 { high := sub(mid,1) } case 0 { found := 1 index := mid low := add(high,1) } } } } case 0 { for { let low := 0 } lt(low, sload(self_slot)) { low := add(low, 1) } { switch eq(sload(add(sha3(0x60,0x20),low)), value) case 1 { found := 1 index := low low := sload(self_slot) } } } } } /// @dev Utility function for heapSort /// @param index The index of child node /// @return pI The parent node index function getParentI(uint256 index) constant private returns (uint256 pI) { uint256 i = index - 1; pI = i/2; } /// @dev Utility function for heapSort /// @param index The index of parent node /// @return lcI The index of left child function getLeftChildI(uint256 index) constant private returns (uint256 lcI) { uint256 i = index * 2; lcI = i + 1; } /// @dev Sorts given array in place /// @param self Storage array containing uint256 type variables function heapSort(uint256[] storage self) { uint256 end = self.length - 1; uint256 start = getParentI(end); uint256 root = start; uint256 lChild; uint256 rChild; uint256 swap; uint256 temp; while(start >= 0){ root = start; lChild = getLeftChildI(start); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end+1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } if(start == 0) break; else start = start - 1; } while(end > 0){ temp = self[end]; self[end] = self[0]; self[0] = temp; end = end - 1; root = 0; lChild = getLeftChildI(0); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end + 1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } } } } pragma solidity ^0.4.13; /** * @title Basic Math Library * @author Majoolr.io * * version 1.1.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Basic Math Library is inspired by the Safe Math library written by * OpenZeppelin at https://github.com/OpenZeppelin/zeppelin-solidity/ . * Majoolr works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Majoolr * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: majoolr.io, openzeppelin.org * * 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. */ library BasicMathLib { event Err(string typeErr); /// @dev Multiplies two numbers and checks for overflow before returning. /// Does not throw but rather logs an Err event if there is overflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The product of a and b, or 0 if there is overflow function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ res := mul(a,b) switch or(iszero(b), eq(div(res,b), a)) case 0 { err := 1 res := 0 } } if (err) Err("times func overflow"); } /// @dev Divides two numbers but checks for 0 in the divisor first. /// Does not throw but rather logs an Err event if 0 is in the divisor. /// @param a First number /// @param b Second number /// @return err False normally, or true if `b` is 0 /// @return res The quotient of a and b, or 0 if `b` is 0 function dividedBy(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ switch iszero(b) case 0 { res := div(a,b) mstore(add(mload(0x40),0x20),res) return(mload(0x40),0x40) } } Err("tried to divide by zero"); return (true, 0); } /// @dev Adds two numbers and checks for overflow before returning. /// Does not throw but rather logs an Err event if there is overflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The sum of a and b, or 0 if there is overflow function plus(uint256 a, uint256 b) constant returns (bool err, uint256 res) { assembly{ res := add(a,b) switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b))) case 0 { err := 1 res := 0 } } if (err) Err("plus func overflow"); } /// @dev Subtracts two numbers and checks for underflow before returning. /// Does not throw but rather logs an Err event if there is underflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is underflow /// @return res The difference between a and b, or 0 if there is underflow function minus(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ res := sub(a,b) switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1) case 0 { err := 1 res := 0 } } if (err) Err("minus func underflow"); } }
@dev Multiplies two numbers and checks for overflow before returning. Does not throw but rather logs an Err event if there is overflow. @param a First number @param b Second number @return err False normally, or true if there is overflow @return res The product of a and b, or 0 if there is overflow
function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ res := mul(a,b) switch or(iszero(b), eq(div(res,b), a)) case 0 { err := 1 res := 0 } } if (err) Err("times func overflow"); }
2,063,598
[ 1, 5002, 5259, 2795, 5600, 471, 4271, 364, 9391, 1865, 5785, 18, 9637, 486, 604, 1496, 9178, 5963, 392, 1926, 871, 309, 1915, 353, 9391, 18, 225, 279, 5783, 1300, 225, 324, 7631, 1300, 327, 393, 1083, 15849, 16, 578, 638, 309, 1915, 353, 9391, 327, 400, 1021, 3017, 434, 279, 471, 324, 16, 578, 374, 309, 1915, 353, 9391, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 4124, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 5381, 1135, 261, 6430, 393, 16, 11890, 5034, 400, 13, 288, 203, 565, 19931, 95, 203, 1377, 400, 519, 14064, 12, 69, 16, 70, 13, 203, 1377, 1620, 578, 12, 291, 7124, 12, 70, 3631, 7555, 12, 2892, 12, 455, 16, 70, 3631, 279, 3719, 203, 1377, 648, 374, 288, 203, 3639, 393, 519, 404, 203, 3639, 400, 519, 374, 203, 1377, 289, 203, 565, 289, 203, 565, 309, 261, 370, 13, 203, 1377, 1926, 2932, 8293, 1326, 9391, 8863, 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 ]
pragma solidity ^0.4.11; contract ERC20Token { function balanceOf(address _who) constant returns (uint balance); function allowance(address _owner, address _spender) constant returns (uint remaining); function transferFrom(address _from, address _to, uint _value); function transfer(address _to, uint _value); } contract GroveAPI { function insert(bytes32 indexName, bytes32 id, int value) public; } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract UnicornRanch { using SafeMath for uint; enum VisitType { Spa, Afternoon, Day, Overnight, Week, Extended } enum VisitState { InProgress, Completed, Repossessed } struct Visit { uint unicornCount; VisitType t; uint startBlock; uint expiresBlock; VisitState state; } struct VisitMeta { address owner; uint index; } address public cardboardUnicornTokenAddress; address public groveAddress; address public owner = msg.sender; mapping (address => Visit[]) bookings; mapping (bytes32 => VisitMeta) public bookingMetadataForKey; mapping (uint8 => uint) public visitLength; mapping (uint8 => uint) public visitCost; uint public visitingUnicorns = 0; uint public repossessionBlocks = 120960; uint8 public repossessionBountyPerTen = 2; uint8 public repossessionBountyPerHundred = 25; uint public birthBlockThreshold = 60480; uint8 public birthPerTen = 1; uint8 public birthPerHundred = 15; event NewBooking(address indexed _who, uint indexed _index, VisitType indexed _type, uint _unicornCount); event BookingUpdate(address indexed _who, uint indexed _index, VisitState indexed _newState, uint _unicornCount); event RepossessionBounty(address indexed _who, uint _unicornCount); event DonationReceived(address indexed _who, uint _unicornCount); modifier onlyOwner { require(msg.sender == owner); _; } function UnicornRanch() { visitLength[uint8(VisitType.Spa)] = 720; visitLength[uint8(VisitType.Afternoon)] = 1440; visitLength[uint8(VisitType.Day)] = 2880; visitLength[uint8(VisitType.Overnight)] = 8640; visitLength[uint8(VisitType.Week)] = 60480; visitLength[uint8(VisitType.Extended)] = 120960; visitCost[uint8(VisitType.Spa)] = 0; visitCost[uint8(VisitType.Afternoon)] = 0; visitCost[uint8(VisitType.Day)] = 1 szabo; visitCost[uint8(VisitType.Overnight)] = 1 szabo; visitCost[uint8(VisitType.Week)] = 1 szabo; visitCost[uint8(VisitType.Extended)] = 1 szabo; } function getBookingCount(address _who) constant returns (uint count) { return bookings[_who].length; } function getBooking(address _who, uint _index) constant returns (uint _unicornCount, VisitType _type, uint _startBlock, uint _expiresBlock, VisitState _state) { Visit storage v = bookings[_who][_index]; return (v.unicornCount, v.t, v.startBlock, v.expiresBlock, v.state); } function bookSpaVisit(uint _unicornCount) payable { return addBooking(VisitType.Spa, _unicornCount); } function bookAfternoonVisit(uint _unicornCount) payable { return addBooking(VisitType.Afternoon, _unicornCount); } function bookDayVisit(uint _unicornCount) payable { return addBooking(VisitType.Day, _unicornCount); } function bookOvernightVisit(uint _unicornCount) payable { return addBooking(VisitType.Overnight, _unicornCount); } function bookWeekVisit(uint _unicornCount) payable { return addBooking(VisitType.Week, _unicornCount); } function bookExtendedVisit(uint _unicornCount) payable { return addBooking(VisitType.Extended, _unicornCount); } function addBooking(VisitType _type, uint _unicornCount) payable { if (_type == VisitType.Afternoon) { return donateUnicorns(availableBalance(msg.sender)); } require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount)); // Must be paying proper amount ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); // Transfer the actual asset visitingUnicorns = visitingUnicorns.add(_unicornCount); uint expiresBlock = block.number.add(visitLength[uint8(_type)]); // Calculate when this booking will be done // Add the booking to the ledger bookings[msg.sender].push(Visit( _unicornCount, _type, block.number, expiresBlock, VisitState.InProgress )); uint newIndex = bookings[msg.sender].length - 1; bytes32 uniqueKey = keccak256(msg.sender, newIndex); // Create a unique key for this booking // Add a reference for that key, to find the metadata about it later bookingMetadataForKey[uniqueKey] = VisitMeta( msg.sender, newIndex ); if (groveAddress > 0) { // Insert into Grove index for applications to query GroveAPI g = GroveAPI(groveAddress); g.insert("bookingExpiration", uniqueKey, int(expiresBlock)); } // Send event about this new booking NewBooking(msg.sender, newIndex, _type, _unicornCount); } function completeBooking(uint _index) { require(bookings[msg.sender].length > _index); // Sender must have at least this many bookings Visit storage v = bookings[msg.sender][_index]; require(block.number >= v.expiresBlock); // Expired time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed uint unicornsToReturn = v.unicornCount; ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); // Determine if any births occurred uint birthCount = 0; if (SafeMath.sub(block.number, v.startBlock) >= birthBlockThreshold) { if (v.unicornCount >= 100) { birthCount = uint(birthPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { birthCount = uint(birthPerTen).mul(v.unicornCount / 10); } } if (birthCount > 0) { uint availableUnicorns = cardboardUnicorns.balanceOf(address(this)) - visitingUnicorns; if (availableUnicorns < birthCount) { birthCount = availableUnicorns; } unicornsToReturn = unicornsToReturn.add(birthCount); } // Update the status of the Visit v.state = VisitState.Completed; bookings[msg.sender][_index] = v; // Transfer the asset back to the owner visitingUnicorns = visitingUnicorns.sub(unicornsToReturn); cardboardUnicorns.transfer(msg.sender, unicornsToReturn); // Send event about this update BookingUpdate(msg.sender, _index, VisitState.Completed, unicornsToReturn); } function repossessBooking(address _who, uint _index) { require(bookings[_who].length > _index); // Address in question must have at least this many bookings Visit storage v = bookings[_who][_index]; require(block.number > v.expiresBlock.add(repossessionBlocks)); // Repossession time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed // Update the status of the Visit v.state = VisitState.Repossessed; bookings[_who][_index] = v; visitingUnicorns = visitingUnicorns.sub(v.unicornCount); // Send event about this update BookingUpdate(_who, _index, VisitState.Repossessed, v.unicornCount); // Calculate Bounty amount uint bountyCount = 1; if (v.unicornCount >= 100) { bountyCount = uint(repossessionBountyPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { bountyCount = uint(repossessionBountyPerTen).mul(v.unicornCount / 10); } // Send bounty to bounty hunter ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transfer(msg.sender, bountyCount); // Send event about the bounty payout RepossessionBounty(msg.sender, bountyCount); } function availableBalance(address _who) internal returns (uint) { ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); uint count = cardboardUnicorns.allowance(_who, address(this)); if (count == 0) { return 0; } uint balance = cardboardUnicorns.balanceOf(_who); if (balance < count) { return balance; } return count; } function() payable { if (cardboardUnicornTokenAddress == 0) { return; } return donateUnicorns(availableBalance(msg.sender)); } function donateUnicorns(uint _unicornCount) payable { if (_unicornCount == 0) { return; } ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); DonationReceived(msg.sender, _unicornCount); } /** * Change ownership of the Ranch */ function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } /** * Change the outside contracts used by this contract */ function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { cardboardUnicornTokenAddress = _newTokenAddress; } function changeGroveAddress(address _newAddress) onlyOwner { groveAddress = _newAddress; } /** * Update block durations for various types of visits */ function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitLength[uint8(VisitType.Spa)] = _spa; visitLength[uint8(VisitType.Afternoon)] = _afternoon; visitLength[uint8(VisitType.Day)] = _day; visitLength[uint8(VisitType.Overnight)] = _overnight; visitLength[uint8(VisitType.Week)] = _week; visitLength[uint8(VisitType.Extended)] = _extended; } /** * Update ether costs for various types of visits */ function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitCost[uint8(VisitType.Spa)] = _spa; visitCost[uint8(VisitType.Afternoon)] = _afternoon; visitCost[uint8(VisitType.Day)] = _day; visitCost[uint8(VisitType.Overnight)] = _overnight; visitCost[uint8(VisitType.Week)] = _week; visitCost[uint8(VisitType.Extended)] = _extended; } /** * Update bounty reward settings */ function changeRepoSettings(uint _repoBlocks, uint8 _repoPerTen, uint8 _repoPerHundred) onlyOwner { repossessionBlocks = _repoBlocks; repossessionBountyPerTen = _repoPerTen; repossessionBountyPerHundred = _repoPerHundred; } /** * Update birth event settings */ function changeBirthSettings(uint _birthBlocks, uint8 _birthPerTen, uint8 _birthPerHundred) onlyOwner { birthBlockThreshold = _birthBlocks; birthPerTen = _birthPerTen; birthPerHundred = _birthPerHundred; } function withdraw() onlyOwner { owner.transfer(this.balance); // Send all ether in this contract to this contract&#39;s owner } function withdrawForeignTokens(address _tokenContract) onlyOwner { ERC20Token token = ERC20Token(_tokenContract); token.transfer(owner, token.balanceOf(address(this))); // Send all owned tokens to this contract&#39;s owner } }
Must be paying proper amount
require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount));
6,634,455
[ 1, 10136, 506, 8843, 310, 5338, 3844, 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, 2583, 12, 3576, 18, 1132, 1545, 3757, 8018, 63, 11890, 28, 24899, 723, 13, 8009, 16411, 24899, 318, 335, 14245, 1380, 10019, 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 ]
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity ^0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "./KeepToken.sol"; /// @title KEEP Signer Subsidy Rewards /// @notice A contract for distributing KEEP token rewards to keeps. /// When a reward contract is created, the creator defines a reward schedule /// consisting of one or more reward intervals and their interval weights, /// the length of reward intervals, and the quota of how many keeps must be /// created in an interval for the full reward for that interval to be paid out. /// /// The amount of KEEP to be distributed is determined by funding the contract, /// and additional KEEP can be added at any time. /// The reward contract is funded with `approveAndCall` with no extra data, /// but it also collects any KEEP mistakenly sent to it in any other way. /// /// An interval is defined by the timestamps [startOf, endOf); /// a keep created at the time `startOf(i)` belongs to interval `i` /// and one created at `endOf(i)` belongs to `i+1`. /// /// When an interval is over, it will be allocated a percentage of the remaining /// unallocated rewards based on its weight, and adjusted by the number of keeps /// created in the interval if the quota is not met. /// /// The adjustment for not meeting the keep quota is a percentage that equals /// the percentage of the quota that was met; if the number of keeps created is /// 80% of the quota then 80% of the base reward will be allocated for the /// interval. /// /// Any unallocated rewards will stay in the unallocated rewards pool, /// to be allocated for future intervals. Intervals past the initially defined /// schedule have a weight of 100%, meaning that all remaining unallocated /// rewards will be allocated to the interval. /// /// Keeps of the appropriate type can receive rewards once the interval they /// were created in is over, and the keep has closed happily. /// There is no time limit to receiving rewards, nor is there need to wait for /// all keeps from the interval to close. /// Calling `receiveReward` automatically allocates the rewards for the interval /// the specified keep was created in and all previous intervals. /// /// If a keep is terminated, that fact can be reported to the reward contract. /// Reporting a terminated keep returns its allocated reward to the pool of /// unallocated rewards. /// /// @dev A concrete implementation of the abstract rewards contract must specify /// functions for accessing information about keeps and paying out rewards. /// For the purpose of rewards, Random Beacon signing groups count as "keeps" /// and the beacon operator contract acts as the "factory". contract Rewards is Ownable { using SafeMath for uint256; using SafeERC20 for KeepToken; KeepToken public token; // Array representing the percentage of unallocated rewards // available for each reward interval. uint256[] public intervalWeights; // percent array // Length of one interval in seconds (timestamp diff). uint256 public termLength; // The number of keeps required in an interval // for the full reward to be allocated to the interval. uint256 public minimumKeepsPerInterval; // Total number of KEEP tokens to distribute by this contract. // Includes those already dispensed. uint256 public totalRewards; // Rewards that haven't been allocated to finished intervals. uint256 public unallocatedRewards; // Rewards that have been dispensed from this contract as signer rewards. // `token.balanceOf(address(this))` should always equal // `totalRewards.sub(dispensedRewards)` uint256 public dispensedRewards; // The following invariant should always hold: // token.balanceOf(address(this)) >= totalRewards.sub(dispensedRewards) // Timestamp of first interval beginning. // Interval 0 covers everything before `firstIntervalStart` // and the first `termLength` after `firstIntervalStart`. uint256 public firstIntervalStart; // Mapping of interval number to tokens allocated for the interval. uint256[] internal intervalAllocations; // mapping of keeps to booleans. // True if the keep has been used to claim a reward. mapping(bytes32 => bool) internal claimed; // Mapping of interval to number of keeps created in/before the interval mapping(uint256 => uint256) internal keepsByInterval; // Mapping of interval to number of keeps whose rewards have been paid out, // or reallocated because the keep closed unhappily mapping(uint256 => uint256) public intervalKeepsProcessed; // Indicates whether the contract has been properly funded. Rewards can not // be allocated before the first funding and the owner of the // contract is responsible for marking it as already funded. Further funding // of the contract is possible with no owner's intervention. bool public funded = false; // Owner of the contract may initiate an upgrade to a new rewards contract // but the pending and past intervals must have their rewards allocated // before any KEEP tokens are transferred out from this contract. uint256 public upgradeInitiatedTimestamp; uint256 public upgradeFinalizedTimestamp; address public newRewardsContract; event RewardReceived(bytes32 keep, uint256 amount); event UpgradeInitiated(address newRewardsContract); event UpgradeFinalized(uint256 amountTransferred); constructor( address _token, uint256 _firstIntervalStart, uint256[] memory _intervalWeights, uint256 _termLength, uint256 _minimumKeepsPerInterval ) public { token = KeepToken(_token); firstIntervalStart = _firstIntervalStart; intervalWeights = _intervalWeights; termLength = _termLength; minimumKeepsPerInterval = _minimumKeepsPerInterval; } /// @notice Funds the rewards contract. /// @dev Adds the received amount of tokens to `totalRewards` and /// `unallocatedRewards`. May be called at any time, even after allocating /// some intervals. /// If the contract has been upgraded, /// the funding will be transferred to the new contract instead. /// Changes to `unallocatedRewards` will take effect on subsequent interval /// allocations. Intended to be used with `approveAndCall`. /// If the reward contract has received tokens outside `approveAndCall`, /// this collects them as well. /// The following invariant should hold right after calling this function: /// token.balanceOf(address(this)) == totalRewards.sub(dispensedRewards). /// @param _from The original sender of the tokens. /// Must have approved at least `_value` tokens for the rewards contract. /// @param _value The amount of tokens to fund. /// @param _token The token to fund the rewards in. /// Must match the one specified in the rewards contract. function receiveApproval( address _from, uint256 _value, address _token, bytes memory ) public { require(IERC20(_token) == token, "Unsupported token"); token.safeTransferFrom(_from, address(this), _value); uint256 currentBalance = token.balanceOf(address(this)); uint256 beforeBalance = totalRewards.sub(dispensedRewards); require( currentBalance >= beforeBalance, "Reward contract has lost tokens" ); uint256 addedBalance = currentBalance.sub(beforeBalance); totalRewards = totalRewards.add(addedBalance); deallocate(addedBalance); } function markAsFunded() public onlyOwner { funded = true; } /// @notice Stakers can receive KEEP rewards from multiple keeps of their choice /// in one transaction to reduce total cost comparing to single calls for rewards. /// It is a caller responsibility to determine the cost and consumed gas when /// receiving rewards from multiple keeps. /// @param keepIdentifiers An array of keep identifiers. function receiveRewards(bytes32[] memory keepIdentifiers) public { for (uint256 i = 0; i < keepIdentifiers.length; i++) { receiveReward(keepIdentifiers[i]); } } /// @notice Sends the reward for a keep to the keep members. /// @param keepIdentifier A unique identifier for the keep, /// e.g. address or number converted to a `bytes32`. function receiveReward(bytes32 keepIdentifier) public factoryMustRecognize(keepIdentifier) rewardsNotClaimed(keepIdentifier) mustBeClosed(keepIdentifier) { _processKeep(true, keepIdentifier); } /// @notice Report about the terminated keeps in batch. All the allocated /// rewards in these keeps will be returned to the unallocated pool. /// @param keepIdentifiers An array of keep identifiers. function reportTerminations(bytes32[] memory keepIdentifiers) public { for (uint256 i = 0; i < keepIdentifiers.length; i++) { reportTermination(keepIdentifiers[i]); } } /// @notice Report that the keep was terminated, and return its allocated /// rewards to the unallocated pool. /// @param keepIdentifier The terminated keep. function reportTermination(bytes32 keepIdentifier) public factoryMustRecognize(keepIdentifier) rewardsNotClaimed(keepIdentifier) mustBeTerminated(keepIdentifier) { _processKeep(false, keepIdentifier); } /// @notice Checks if a keep is eligible to receive rewards. /// @dev Keeps that close dishonorably or early are not eligible for rewards. /// @param _keep The keep to check. /// @return True if the keep is eligible, false otherwise function eligibleForReward(bytes32 _keep) public view returns (bool) { return _recognizedByFactory(_keep) && _isClosed(_keep) && !rewardClaimed(_keep); } /// @notice Checks if a keep is terminated and thus its rewards can be /// returned to the unallocated pool. /// @param _keep The keep to check. /// @return True if the keep is terminated, false otherwise function eligibleButTerminated(bytes32 _keep) public view returns (bool) { return _recognizedByFactory(_keep) && _isTerminated(_keep); } /// @notice Return the interval number the provided timestamp falls within. /// @dev If the timestamp is before `firstIntervalStart`, the interval is 0. /// @param timestamp The timestamp whose interval is queried. /// @return The interval of the timestamp. function intervalOf(uint256 timestamp) public view returns (uint256) { uint256 _firstIntervalStart = firstIntervalStart; uint256 _termLength = termLength; if (timestamp < _firstIntervalStart) { return 0; } uint256 difference = timestamp.sub(_firstIntervalStart); uint256 interval = difference.div(_termLength); return interval; } /// @notice Return the timestamp corresponding to the start of the interval. /// @dev The start of an interval is inclusive; /// a keep created at the timestamp `startOf(i)` is in interval `i`. /// @param interval The interval whose start is queried. /// @return The start timestamp of the interval. function startOf(uint256 interval) public view returns (uint256) { return firstIntervalStart.add(interval.mul(termLength)); } /// @notice Return the timestamp corresponding to the end of the interval. /// @dev The end of an interval is exclusive; /// a keep created at the timestamp `endOf(i)` is in interval `i+1`. /// @param interval The interval whose end is queried. /// @return The end timestamp of the interval. function endOf(uint256 interval) public view returns (uint256) { return startOf(interval.add(1)); } /// @notice Return whether the given interval is finished. /// @param interval The interval. /// @return Whether the interval is finished. function isFinished(uint256 interval) public view returns (bool) { return block.timestamp >= endOf(interval); } /// @notice Return whether the given keep has already claimed rewards /// or had its rewards reallocated due to termination. /// @param _keep The identifier of the keep. /// @return True if rewards have been paid out for the keep, /// or its termination has been reported. /// False otherwise. function rewardClaimed(bytes32 _keep) public view returns (bool) { return claimed[_keep]; } /// @notice Return the number of keeps created in the specified interval. /// @param interval The interval. /// @return Number of keeps created in the interval. function keepsInInterval(uint256 interval) public returns (uint256) { return (_getEndpoint(interval).sub(_getPreviousEndpoint(interval))); } /// @notice Return the percentage of remaining unallocated rewards /// that is to be allocated to the specified interval. /// @param interval The interval. /// @return The percentage weight of the interval. function getIntervalWeight(uint256 interval) public view returns (uint256) { if (interval < intervalWeights.length) { return intervalWeights[interval]; } else { return intervalWeights[intervalWeights.length - 1]; } } /// @notice Get the number of intervals with explicitly specified weights. /// All subsequent intervals will have an implicit weight of 100. /// @return The number of explicitly specified intervals. function getIntervalCount() public view returns (uint256) { return intervalWeights.length; } /// @notice Allocate rewards for unallocated intervals up to and including /// the given interval. /// @dev The given interval must be finished and unallocated. /// To allocate rewards correctly, any earlier intervals that are still /// unallocated will be allocated before the given interval. /// With reasonable interval lengths this should not pose a problem, /// and if allocating a later interval results in an out-of-gas issue, /// forcing the allocation of an earlier interval should fix it. /// @param interval The interval to allocate. function allocateRewards(uint256 interval) public mustBeFinished(interval) mustBeFunded { uint256 allocatedIntervals = intervalAllocations.length; require(!(interval < allocatedIntervals), "Interval already allocated"); // Allocate previous intervals first if (interval > allocatedIntervals) { allocateRewards(interval.sub(1)); } uint256 totalAllocation = _adjustedAllocation(interval); unallocatedRewards = unallocatedRewards.sub(totalAllocation); intervalAllocations.push(totalAllocation); } /// @notice Get the total amount of tokens /// allocated for all keeps in the specified interval. /// @dev This function returns correct results for any allocated interval. /// Dividing the allocated rewards by the number of keeps in the interval /// will give the correct reward for a keep in the interval. /// However, if a keep in the interval is terminated /// its reward will be returned to the pool of unallocated tokens. /// This will not be reflected in the return value of this function. /// @param interval A previously allocated interval. /// @return The total number of tokens allocated for keeps in the interval. function getAllocatedRewards(uint256 interval) public view returns (uint256) { require( interval < intervalAllocations.length, "Interval not allocated yet" ); return intervalAllocations[interval]; } /// @notice Return whether the specified interval has been allocated. /// @param interval The interval. /// @return Whether the interval has been allocated yet. function isAllocated(uint256 interval) public view returns (bool) { uint256 allocatedIntervals = intervalAllocations.length; return (interval < allocatedIntervals); } /// @notice Initiates the process of upgrading to another rewards contract. /// @param _newRewardsContract The address of a new rewards contract. function initiateRewardsUpgrade(address _newRewardsContract) public onlyOwner { upgradeInitiatedTimestamp = block.timestamp; newRewardsContract = _newRewardsContract; emit UpgradeInitiated(newRewardsContract); } /// @notice Finalizes the process of upgrading to another rewards contract /// by allocating all past intervals and then, transferring the /// not-yet-allocated tokens to a new rewards contract. /// Can be called only when the interval during which the upgrade was /// initiated ended. /// Before finalizing the upgrade, make sure all terminated groups are /// reported. function finalizeRewardsUpgrade() public onlyOwner { require(upgradeInitiatedTimestamp != 0, "Upgrade not initiated"); uint256 currentInterval = intervalOf(block.timestamp); uint256 upgradeInitiatedInterval = intervalOf(upgradeInitiatedTimestamp); require( currentInterval > upgradeInitiatedInterval, "Interval at which the upgrade was initiated hasn't ended yet" ); // ensure all past intervals are allocated if (!isAllocated(currentInterval.sub(1))) { allocateRewards(currentInterval.sub(1)); } // transfer the unallocated KEEP to the new rewards contract and update // this contract's balances uint256 amountToTransfer = unallocatedRewards; totalRewards = totalRewards.sub(amountToTransfer); unallocatedRewards = 0; emit UpgradeFinalized(amountToTransfer); bool success = token.approveAndCall( newRewardsContract, amountToTransfer, bytes("") ); require(success, "Upgrade finalization failed"); upgradeInitiatedTimestamp = 0; upgradeFinalizedTimestamp = block.timestamp; } /// @notice Return the number of keeps created before `intervalEndpoint` /// @dev Wraps the binary search of `_find` /// with a number of checks for edge cases. function _findEndpoint(uint256 intervalEndpoint) internal view returns (uint256) { require( intervalEndpoint <= block.timestamp, "interval hasn't ended yet" ); uint256 keepCount = _getKeepCount(); // no keeps created yet -> return 0 if (keepCount == 0) { return 0; } uint256 lb = 0; // lower bound, inclusive uint256 timestampLB = _getCreationTime(_getKeepAtIndex(lb)); // all keeps created after the interval -> return 0 if (timestampLB >= intervalEndpoint) { return 0; } uint256 ub = keepCount.sub(1); // upper bound, inclusive uint256 timestampUB = _getCreationTime(_getKeepAtIndex(ub)); // all keeps created in or before the interval -> return keep count if (timestampUB < intervalEndpoint) { return keepCount; } // The above cases also cover the case // where only 1 keep has been created; // lb == ub // if it was created after the interval, return 0 // otherwise, return 1 return _find(lb, timestampLB, ub, timestampUB, intervalEndpoint); } /// @notice Return the number of keeps created before `targetTime`, /// with specified upper and lower bounds. /// @dev Binary search assumes the following invariants: /// lower bound >= 0, lbTime < targetTime /// upper bound < keepCount, ubTime >= targetTime /// @param _lb The lower bound of the search (inclusive) /// @param _lbTime The creation time of keep number `lb` /// @param _ub The upper bound of the search (inclusive) /// @param _ubTime The creation time of keep number `ub` /// @param targetTime The target time function _find( uint256 _lb, uint256 _lbTime, uint256 _ub, uint256 _ubTime, uint256 targetTime ) internal view returns (uint256) { uint256 lb = _lb; uint256 lbTime = _lbTime; uint256 ub = _ub; uint256 ubTime = _ubTime; uint256 len = ub.sub(lb); while (len > 1) { // upper bound >= lower bound + 2 // mid > lower bound uint256 mid = lb.add(len.div(2)); uint256 midTime = _getCreationTime(_getKeepAtIndex(mid)); if (midTime >= targetTime) { ub = mid; ubTime = midTime; } else { lb = mid; lbTime = midTime; } len = ub.sub(lb); } return ub; } /// @notice Return the endpoint index of the interval, /// i.e. the number of keeps created in and before the interval. /// The interval must have ended; otherwise the endpoint might still change. /// @dev Uses a locally cached result, and stores the result if it isn't /// cached yet. All keeps created before the initiation fall in interval 0. /// @param interval The number of the interval. /// @return endpoint The number of keeps the factory had created /// before the end of the interval. function _getEndpoint(uint256 interval) internal mustBeFinished(interval) returns (uint256 endpoint) { // Get the endpoint from local cache; // might not be recorded yet uint256 maybeEndpoint = keepsByInterval[interval]; // Either the endpoint is zero // (no keeps created by the end of the interval) // or the endpoint isn't cached yet if (maybeEndpoint == 0) { // Check what the real endpoint is // if the actual value is 0, this call short-circuits // so we don't need to special-case the zero uint256 realEndpoint = _findEndpoint(endOf(interval)); // We didn't have the correct value cached, // so store it if (realEndpoint != 0) { keepsByInterval[interval] = realEndpoint; } endpoint = realEndpoint; } else { endpoint = maybeEndpoint; } return endpoint; } /// @notice Get the endpoint of the previous interval. /// @dev Like _getEndpoint, gracefully handles the beginning of interval 0. /// @param interval The interval. /// @return The number of keeps created by the end of the preceding interval. function _getPreviousEndpoint(uint256 interval) internal returns (uint256) { if (interval == 0) { return 0; } else { return _getEndpoint(interval.sub(1)); } } /// @notice Calculate the reward allocation for an interval /// without adjusting for the number of keeps in the interval. /// @param interval The next interval to be allocated. /// Results for other intervals will not be accurate. /// @return The base reward allocation for the interval. function _baseAllocation(uint256 interval) internal view returns (uint256) { uint256 _unallocatedRewards = unallocatedRewards; uint256 weightPercentage = getIntervalWeight(interval); return _unallocatedRewards.mul(weightPercentage).div(100); } /// @notice Calculate the reward allocation for an interval /// after adjusting for the number of keeps in the interval. /// @dev An interval with at least `minimumKeepsPerInterval` keeps /// will have the full reward allocated to it. /// An interval with fewer keeps will only be allocated a fraction of the /// base reward equaling the fraction of the quota that was met. /// The reward allocated for each keep in the interval is constant /// regardless of the number of keeps in the interval until the quota is /// met, and further increases in the number of keeps will lead to the same /// allocation being shared among more of them. Each keep in an interval is /// allocated the same reward. If the number of keeps in an interval meets /// the quota, but the base allocation isn't divisible by the number of /// keeps, the remainder will remain unallocated. /// Allocations for an already allocated interval, or when all prior /// intervals haven't been allocated yet, will produce incorrect results. /// @param interval The next interval to be allocated. /// @return The amount of tokens to allocate as rewards for the interval. function _adjustedAllocation(uint256 interval) internal returns (uint256) { uint256 __baseAllocation = _baseAllocation(interval); if (__baseAllocation == 0) { return 0; } uint256 keepCount = keepsInInterval(interval); uint256 adjustmentCount = Math.max(keepCount, minimumKeepsPerInterval); if (adjustmentCount == 0) { return 0; } // Rewards divide equally among keeps return __baseAllocation.mul(keepCount).div(adjustmentCount); } /// @notice Process the rewards for the given keep, allocating finished /// intervals as necessary, and then either paying out the rewards to the /// keep's members or returning them to the unallocated pool, depending on /// the keep's eligibility. /// @param eligible Whether the keep is eligible for rewards or not. /// @param keepIdentifier The specified keep. function _processKeep(bool eligible, bytes32 keepIdentifier) internal { uint256 creationTime = _getCreationTime(keepIdentifier); uint256 interval = intervalOf(creationTime); if (!isAllocated(interval)) { allocateRewards(interval); } uint256 allocation = intervalAllocations[interval]; uint256 _keepsInInterval = keepsInInterval(interval); uint256 perKeepReward = allocation.div(_keepsInInterval); claimed[keepIdentifier] = true; intervalKeepsProcessed[interval] = intervalKeepsProcessed[interval].add( 1 ); if (eligible) { dispensedRewards = dispensedRewards.add(perKeepReward); _distributeReward(keepIdentifier, perKeepReward); emit RewardReceived(keepIdentifier, perKeepReward); } else { // Return the reward to the unallocated pool deallocate(perKeepReward); } } /// @notice Return the given amount to the unallocated pool. /// If the contract has been upgraded, /// the deallocated amount will be sent to the new contract. /// @param amount The amount to deallocate function deallocate(uint256 amount) internal { if (upgradeFinalizedTimestamp != 0) { bool success = token.approveAndCall(newRewardsContract, amount, bytes("")); if (!success) { unallocatedRewards = unallocatedRewards.add(amount); } } else { unallocatedRewards = unallocatedRewards.add(amount); } } /// @notice Get the total number of keeps ever created by the factory, /// including closed and terminated keeps. /// @return The number of keeps. function _getKeepCount() internal view returns (uint256); /// @notice Get the identifier of the keep at the given index, /// when all keeps created by the factory are ordered by creation time. /// @param index The index of the queried keep. /// @return The `bytes32` identifier of the keep at the given index. /// @dev Implementation is not required to check if a keep with the given /// index exists. function _getKeepAtIndex(uint256 index) internal view returns (bytes32); /// @notice Get the creation time of the given keep. /// @param _keep The identifier of the keep. /// @return The creation timestamp of the keep. /// @dev If the idenfifier is invalid or not recognized by factory, function /// may revert or return 0. function _getCreationTime(bytes32 _keep) internal view returns (uint256); /// @notice Is the given keep closed. /// @param _keep The identifier of the keep. /// @return True if the keep is closed, false otherwise. /// If the identifier is invalid, may return false or an error. function _isClosed(bytes32 _keep) internal view returns (bool); /// @notice Is the given keep terminated. /// @param _keep The identifier of the keep. /// @return True if the keep is terminated, false otherwise. /// If the identifier is invalid, may return false or an error. function _isTerminated(bytes32 _keep) internal view returns (bool); /// @notice Does the given `bytes32` identifier match a valid keep. /// @param _keep A possible keep identifier. /// @return True if the identifier matches a keep created by the factory. /// For any other identifier, must return false and not an error. function _recognizedByFactory(bytes32 _keep) internal view returns (bool); /// @notice Pay the given amount of tokens to members of the keep. /// @param _keep The keep whose members to reward. /// @param amount The total amount of tokens to distribute to the members. function _distributeReward(bytes32 _keep, uint256 amount) internal; modifier rewardsNotClaimed(bytes32 _keep) { require(!rewardClaimed(_keep), "Rewards already claimed"); _; } modifier mustBeFinished(uint256 interval) { require(isFinished(interval), "Interval hasn't ended yet"); _; } modifier mustBeClosed(bytes32 _keep) { require(_isClosed(_keep), "Keep is not closed"); _; } modifier mustBeTerminated(bytes32 _keep) { require(_isTerminated(_keep), "Keep is not terminated"); _; } modifier factoryMustRecognize(bytes32 _keep) { require(_recognizedByFactory(_keep), "Keep not recognized by factory"); _; } modifier mustBeFunded() { require(funded, "Contract has not been funded yet"); _; } }
@notice Sends the reward for a keep to the keep members. @param keepIdentifier A unique identifier for the keep, e.g. address or number converted to a `bytes32`.
function receiveReward(bytes32 keepIdentifier) public factoryMustRecognize(keepIdentifier) rewardsNotClaimed(keepIdentifier) mustBeClosed(keepIdentifier) { _processKeep(true, keepIdentifier); }
6,394,887
[ 1, 10501, 326, 19890, 364, 279, 3455, 358, 326, 3455, 4833, 18, 225, 3455, 3004, 432, 3089, 2756, 364, 326, 3455, 16, 425, 18, 75, 18, 1758, 578, 1300, 5970, 358, 279, 1375, 3890, 1578, 8338, 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, 6798, 17631, 1060, 12, 3890, 1578, 3455, 3004, 13, 203, 3639, 1071, 203, 3639, 3272, 10136, 22931, 554, 12, 10102, 3004, 13, 203, 3639, 283, 6397, 1248, 9762, 329, 12, 10102, 3004, 13, 203, 3639, 1297, 1919, 7395, 12, 10102, 3004, 13, 203, 565, 288, 203, 3639, 389, 2567, 11523, 12, 3767, 16, 3455, 3004, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.5.17 <0.9.0; import "@unlock-protocol/contracts/dist/PublicLock/IPublicLockV10.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Base64.sol"; import "hardhat/console.sol"; import "./Layer.sol"; import { BokkyPooBahsDateTimeLibrary } from "./BokkyPooBahsDateTimeLibrary.sol"; /** * @notice Functions to be implemented by a tokenURIHook. * @dev Lock hooks are configured on the lock contract by calling `setEventHooks` on the lock. */ contract Hook { address public _avatarLock; address public _buntaiLock; address public _gundanLock; address public _mappingContract; string public _ipfsHash; /** * The hook is initialized with each lock contract as well as each layer contract */ constructor( address avatarLock, address buntaiLock, address gundanLock, address mappingContract, string memory ipfsHash ) { _avatarLock = avatarLock; _buntaiLock = buntaiLock; _gundanLock = gundanLock; _mappingContract = mappingContract; _ipfsHash = ipfsHash; } /** * Not altering the price by default */ function keyPurchasePrice( address, /* from */ address, /* recipient */ address, /* referrer */ bytes calldata /* data */ ) external view returns (uint256 minKeyPrice) { // TODO Let's look at the list? return IPublicLock(msg.sender).keyPrice(); } /** * When a new key is purchased, we need to grant a weapon * Challenge: we */ function onKeyPurchase( address, /*from*/ address recipient, address, /*referrer*/ bytes calldata, /*data*/ uint256, /*minKeyPrice*/ uint256 /*pricePaid*/ ) external { if (msg.sender == _avatarLock) { // If the sender is the avatar lock IPublicLock avatar = IPublicLock(_avatarLock); uint id = avatar.totalSupply(); address[] memory recipients = new address[](1); recipients[0] = recipient; uint[] memory expirations = new uint[](1); expirations[0] = type(uint256).max; // Not expiring! address[] memory managers = new address[](1); managers[0] = recipient; if (id % 2 == 0) { IPublicLock(_buntaiLock).grantKeys(recipients, expirations, managers); } else { IPublicLock(_gundanLock).grantKeys(recipients, expirations, managers); } } } // see https://github.com/unlock-protocol/unlock/blob/master/smart-contracts/contracts/interfaces/hooks/IHook.sol function tokenURI( address, // lockAddress, address, // operator, // We could alter the rendering based on _who_ is viewing! address, // owner, uint256, // keyId, uint256 //expirationTimestamp // a cool trick could be to render based on how far the expiration of the key is! ) external view returns (string memory) { // uint timeOfDay = 0; // string memory kind = ""; string memory image = "QmYkkshevBxHg7XwdP1pw6A4T82xzD8G2RpLDFo6KDy3zm"; // (, , , uint hour, , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); // if (hour <= 8) { // timeOfDay = 0; // 0 => night // } else if (hour <= 17) { // timeOfDay = 1; // 1 => day // } else if (hour <= 21) { // timeOfDay = 2; // 2 => sunset // } else { // timeOfDay = 0; // 0 => night // } // // If the calling contract is the avatar contract // if (lockAddress == _avatarLock) { // kind = "avatars"; // uint weapon = 0; // // Check if there is a mapping! // if (avatarsWeapons[keyId] > 0) { // // If there is one, let's check the owner and make sure it's the correct one // IPublicLock weaponLock = IPublicLock(_weaponLock); // // TODO change me in v10! // uint weaponExpiration = weaponLock.keyExpirationTimestampFor(owner); // address weaponOwner = weaponLock.ownerOf(keyId); // if (weaponExpiration > block.timestamp && weaponOwner == owner) { // weapon = avatarsWeapons[keyId]; // } // } // image = string( // abi.encodePacked( // _ipfsHash, // "/", // kind, // "/", // Strings.toString(keyId), // "-", // Strings.toString(weapon), // "-", // Strings.toString(timeOfDay) // ) // ); // } // else if (lockAddress == _weaponLock) { // kind = "weapons"; // image = string( // abi.encodePacked( // _ipfsHash, // "/", // kind, // "/", // Strings.toString(keyId) // ) // ); // } // create the json that includes the image // We need to include more properties! string memory json = string( abi.encodePacked('{"image":"', image, '"}') ); // render the base64 encoded json metadata return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes(abi.encodePacked(json))) ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.17 <0.9.0; pragma experimental ABIEncoderV2; /** * @title The PublicLock Interface * @author Nick Furfaro (unlock-protocol.com) */ interface IPublicLock { // See indentationissue description here: // https://github.com/duaraghav8/Ethlint/issues/268 // solium-disable indentation /// Functions function initialize( address _lockCreator, uint _expirationDuration, address _tokenAddress, uint _keyPrice, uint _maxNumberOfKeys, string calldata _lockName ) external; /** * @notice Allow the contract to accept tips in ETH sent directly to the contract. * @dev This is okay to use even if the lock is priced in ERC-20 tokens */ // receive() external payable; // roles function DEFAULT_ADMIN_ROLE() external pure returns (bytes32); function KEY_GRANTER_ROLE() external pure returns (bytes32); function LOCK_MANAGER_ROLE() external pure returns (bytes32); /** * @notice The version number of the current implementation on this network. * @return The current version number. */ function publicLockVersion() external pure returns (uint16); /** * @dev Called by a lock manager or beneficiary to withdraw all funds from the lock and send them to the `beneficiary`. * @dev Throws if called by other than a lock manager or beneficiary * @param _tokenAddress specifies the token address to withdraw or 0 for ETH. This is usually * the same as `tokenAddress` in MixinFunds. * @param _amount specifies the max amount to withdraw, which may be reduced when * considering the available balance. Set to 0 or MAX_UINT to withdraw everything. * -- however be wary of draining funds as it breaks the `cancelAndRefund` and `expireAndRefundFor` * use cases. */ function withdraw( address _tokenAddress, uint _amount ) external; /** * @notice An ERC-20 style approval, allowing the spender to transfer funds directly from this lock. */ function approveBeneficiary( address _spender, uint _amount ) external returns (bool); /** * A function which lets a Lock manager of the lock to change the price for future purchases. * @dev Throws if called by other than a Lock manager * @dev Throws if lock has been disabled * @dev Throws if _tokenAddress is not a valid token * @param _keyPrice The new price to set for keys * @param _tokenAddress The address of the erc20 token to use for pricing the keys, * or 0 to use ETH */ function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external; /** * A function to change the default duration of each key in the lock * @notice keys previously bought are unaffected by this change (i.e. * existing keys timestamps are not recalculated/updated) * @param _newExpirationDuration the new amount of time for each key purchased * or type(uint).max for a non-expiring key */ function setExpirationDuration(uint _newExpirationDuration) external; /** * A function which lets a Lock manager update the beneficiary account, * which receives funds on withdrawal. * @dev Throws if called by other than a Lock manager or beneficiary * @dev Throws if _beneficiary is address(0) * @param _beneficiary The new address to set as the beneficiary */ function updateBeneficiary( address _beneficiary ) external; /** * Checks if the user has a non-expired key. * @param _user The address of the key owner */ function getHasValidKey( address _user ) external view returns (bool); /** * @dev Returns the key's ExpirationTimestamp field for a given owner. * @param _tokenId the id of the key * @dev Returns 0 if the owner has never owned a key for this lock */ function keyExpirationTimestampFor( uint _tokenId ) external view returns (uint timestamp); /** * Public function which returns the total number of unique owners (both expired * and valid). This may be larger than totalSupply. */ function numberOfOwners() external view returns (uint); /** * Allows a Lock manager to assign a descriptive name for this Lock. * @param _lockName The new name for the lock * @dev Throws if called by other than a Lock manager */ function updateLockName( string calldata _lockName ) external; /** * Allows a Lock manager to assign a Symbol for this Lock. * @param _lockSymbol The new Symbol for the lock * @dev Throws if called by other than a Lock manager */ function updateLockSymbol( string calldata _lockSymbol ) external; /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns(string memory); /** * Allows a Lock manager to update the baseTokenURI for this Lock. * @dev Throws if called by other than a Lock manager * @param _baseTokenURI String representing the base of the URI for this lock. */ function setBaseTokenURI( string calldata _baseTokenURI ) external; /** @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * @param _tokenId The tokenID we're inquiring about * @return String representing the URI for the requested token */ function tokenURI( uint256 _tokenId ) external view returns(string memory); /** * @notice Allows a Lock manager to add or remove an event hook */ function setEventHooks( address _onKeyPurchaseHook, address _onKeyCancelHook, address _onValidKeyHook, address _onTokenURIHook ) external; /** * Allows a Lock manager to give a collection of users a key with no charge. * Each key may be assigned a different expiration date. * @dev Throws if called by other than a Lock manager * @param _recipients An array of receiving addresses * @param _expirationTimestamps An array of expiration Timestamps for the keys being granted */ function grantKeys( address[] calldata _recipients, uint[] calldata _expirationTimestamps, address[] calldata _keyManagers ) external; /** * @dev Purchase function * @param _values array of tokens amount to pay for this purchase >= the current keyPrice - any applicable discount * (_values is ignored when using ETH) * @param _recipients array of addresses of the recipients of the purchased key * @param _referrers array of addresses of the users making the referral * @param _keyManagers optional array of addresses to grant managing rights to a specific address on creation * @param _data array of arbitrary data populated by the front-end which initiated the sale * @notice when called for an existing and non-expired key, the `_keyManager` param will be ignored * @dev Setting _value to keyPrice exactly doubles as a security feature. That way if the lock owner increases the * price while my transaction is pending I can't be charged more than I expected (only applicable to ERC-20 when more * than keyPrice is approved for spending). */ function purchase( uint256[] calldata _values, address[] calldata _recipients, address[] calldata _referrers, address[] calldata _keyManagers, bytes[] calldata _data ) external payable; /** * @dev Extend function * @param _value the number of tokens to pay for this purchase >= the current keyPrice - any applicable discount * (_value is ignored when using ETH) * @param _tokenId the id of the key to extend * @param _referrer address of the user making the referral * @param _data arbitrary data populated by the front-end which initiated the sale * @dev Throws if lock is disabled or key does not exist for _recipient. Throws if _recipient == address(0). */ function extend( uint _value, uint _tokenId, address _referrer, bytes calldata _data ) external payable; /** * Merge existing keys * @param _tokenIdFrom the id of the token to substract time from * @param _tokenIdTo the id of the destination token to add time * @param _amount the amount of time to transfer (in seconds) */ function mergeKeys(uint _tokenIdFrom, uint _tokenIdTo, uint _amount) external; /** * Deactivate an existing key * @param _tokenId the id of token to burn * @notice the key will be expired and ownership records will be destroyed */ function burn(uint _tokenId) external; /** * @param _gasRefundValue price in wei or token in smallest price unit * @dev Set the value to be refunded to the sender on purchase */ function setGasRefundValue(uint256 _gasRefundValue) external; /** * _gasRefundValue price in wei or token in smallest price unit * @dev Returns the value/rpice to be refunded to the sender on purchase */ function gasRefundValue() external view returns (uint256 _gasRefundValue); /** * @notice returns the minimum price paid for a purchase with these params. * @dev this considers any discount from Unlock or the OnKeyPurchase hook. */ function purchasePriceFor( address _recipient, address _referrer, bytes calldata _data ) external view returns (uint); /** * Allow a Lock manager to change the transfer fee. * @dev Throws if called by other than a Lock manager * @param _transferFeeBasisPoints The new transfer fee in basis-points(bps). * Ex: 200 bps = 2% */ function updateTransferFee( uint _transferFeeBasisPoints ) external; /** * Determines how much of a fee would need to be paid in order to * transfer to another account. This is pro-rated so the fee goes * down overtime. * @dev Throws if _tokenId does not have a valid key * @param _tokenId The id of the key check the transfer fee for. * @param _time The amount of time to calculate the fee for. * @return The transfer fee in seconds. */ function getTransferFee( uint _tokenId, uint _time ) external view returns (uint); /** * @dev Invoked by a Lock manager to expire the user's key * and perform a refund and cancellation of the key * @param _tokenId The key id we wish to refund to * @param _amount The amount to refund to the key-owner * @dev Throws if called by other than a Lock manager * @dev Throws if _keyOwner does not have a valid key */ function expireAndRefundFor( uint _tokenId, uint _amount ) external; /** * @dev allows the key manager to expire a given tokenId * and send a refund to the keyOwner based on the amount of time remaining. * @param _tokenId The id of the key to cancel. */ function cancelAndRefund(uint _tokenId) external; /** * Allow a Lock manager to change the refund penalty. * @dev Throws if called by other than a Lock manager * @param _freeTrialLength The new duration of free trials for this lock * @param _refundPenaltyBasisPoints The new refund penaly in basis-points(bps) */ function updateRefundPenalty( uint _freeTrialLength, uint _refundPenaltyBasisPoints ) external; /** * @dev Determines how much of a refund a key owner would receive if they issued * @param _keyOwner The key owner to get the refund value for. * a cancelAndRefund block.timestamp. * Note that due to the time required to mine a tx, the actual refund amount will be lower * than what the user reads from this call. */ function getCancelAndRefundValue( address _keyOwner ) external view returns (uint refund); function addKeyGranter(address account) external; function addLockManager(address account) external; function isKeyGranter(address account) external view returns (bool); function isLockManager(address account) external view returns (bool); function onKeyPurchaseHook() external view returns(address); function onKeyCancelHook() external view returns(address); function onValidKeyHook() external view returns(bool); function onTokenURIHook() external view returns(string memory); function revokeKeyGranter(address _granter) external; function renounceLockManager() external; /** * @dev Change the maximum number of keys the lock can edit * @param _maxNumberOfKeys uint the maximum number of keys */ function setMaxNumberOfKeys (uint _maxNumberOfKeys) external; /** * Set the maximum number of keys a specific address can use * @param _maxKeysPerAddress the maximum amount of key a user can own */ function setMaxKeysPerAddress (uint _maxKeysPerAddress) external; /** * @return the maximum number of key allowed for a single address */ function maxKeysPerAddress() external view returns (uint); ///=================================================================== /// Auto-generated getter functions from public state variables function beneficiary() external view returns (address ); function expirationDuration() external view returns (uint256 ); function freeTrialLength() external view returns (uint256 ); function keyPrice() external view returns (uint256 ); function maxNumberOfKeys() external view returns (uint256 ); function refundPenaltyBasisPoints() external view returns (uint256 ); function tokenAddress() external view returns (address ); function transferFeeBasisPoints() external view returns (uint256 ); function unlockProtocol() external view returns (address ); function keyManagerOf(uint) external view returns (address ); ///=================================================================== /** * @notice Allows the key owner to safely share their key (parent key) by * transferring a portion of the remaining time to a new key (child key). * @dev Throws if key is not valid. * @dev Throws if `_to` is the zero address * @param _to The recipient of the shared key * @param _tokenId the key to share * @param _timeShared The amount of time shared * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256('onERC721Received(address,address,uint,bytes)'))`. * @dev Emit Transfer event */ function shareKey( address _to, uint _tokenId, uint _timeShared ) external; /** * @notice Update transfer and cancel rights for a given key * @param _tokenId The id of the key to assign rights for * @param _keyManager The address to assign the rights to for the given key */ function setKeyManagerOf( uint _tokenId, address _keyManager ) external; /** * Check if a certain key is valid * @param _tokenId the id of the key to check validity * @notice this makes use of the onValidKeyHook if it is set */ function isValidKey( uint _tokenId ) external view returns (bool); /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); ///=================================================================== /// From ERC165.sol function supportsInterface(bytes4 interfaceId) external view returns (bool); ///=================================================================== /// From ERC-721 /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address _owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return operator The approved address for this NFT, or the zero address if there is none */ function getApproved(uint256 _tokenId) external view returns (address operator); /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _operator operator address to set the approval * @param _approved representing the status of the approval to be set * @notice disabled when transfers are disabled */ function setApprovalForAll(address _operator, bool _approved) external; /** * @dev Tells whether an operator is approved by a given keyManager * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); /** * Innherited from Open Zeppelin AccessControl.sol */ function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); /** * @notice An ERC-20 style transfer. * @param _value sends a token with _value * expirationDuration (the amount of time remaining on a standard purchase). * @dev The typical use case would be to call this with _value 1, which is on par with calling `transferFrom`. If the user * has more than `expirationDuration` time remaining this may use the `shareKey` function to send some but not all of the token. */ function transfer( address _to, uint _value ) external returns (bool success); /** `owner()` is provided as an helper to mimick the `Ownable` contract ABI. * The `Ownable` logic is used by many 3rd party services to determine * contract ownership - e.g. who is allowed to edit metadata on Opensea. * * @notice This logic is NOT used internally by the Unlock Protocol and is made * available only as a convenience helper. */ function owner() external view returns (address); function setOwner(address account) external; function isOwner(address account) external returns (bool); /** * Migrate data from the previous single owner => key mapping to * the new data structure w multiple tokens. * @param _calldata an ABI-encoded representation of the params (v10: the number of records to migrate as `uint`) * @dev when all record schemas are sucessfully upgraded, this function will update the `schemaVersion` * variable to the latest/current lock version */ function migrate(bytes calldata _calldata) external; /** * Returns the version number of the data schema currently used by the lock * @notice if this is different from `publicLockVersion`, then the ability to purchase, grant * or extend keys is disabled. * @dev will return 0 if no ;igration has ever been run */ function schemaVersion() external view returns (uint); /** * Set the schema version to the latest * @notice only lock manager call call this */ function updateSchemaVersion() external; /** * Renew a given token * @notice only works for non-free, expiring, ERC20 locks * @param _tokenId the ID fo the token to renew * @param _referrer the address of the person to be granted UDT */ function renewMembershipFor( uint _tokenId, address _referrer ) external; } // 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 (last updated v4.5.0) (utils/Base64.sol) pragma solidity ^0.8.0; /** * @dev Provides a set of functions to operate with Base64 strings. * * _Available since v4.5._ */ library Base64 { /** * @dev Base64 Encoding/Decoding Table */ string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @dev Converts a `bytes` to its Bytes64 `string` representation. */ function encode(bytes memory data) internal pure returns (string memory) { /** * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol */ if (data.length == 0) return ""; // Loads the table into memory string memory table = _TABLE; // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter // and split into 4 numbers of 6 bits. // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up // - `data.length + 2` -> Round up // - `/ 3` -> Number of 3-bytes chunks // - `4 *` -> 4 characters for each chunk string memory result = new string(4 * ((data.length + 2) / 3)); assembly { // Prepare the lookup table (skip the first "length" byte) let tablePtr := add(table, 1) // Prepare result pointer, jump over length let resultPtr := add(result, 32) // Run over the input, 3 bytes at a time for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) { } { // Advance 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // To write each character, shift the 3 bytes (18 bits) chunk // 4 times in blocks of 6 bits for each character (18, 12, 6, 0) // and apply logical AND with 0x3F which is the number of // the previous character in the ASCII table prior to the Base64 Table // The result is then added to the table to get the character to write, // and finally write it in the result pointer but with a left shift // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) // Advance mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) // Advance } // When data `bytes` is not exactly 3 bytes long // it is padded with `=` characters at the end switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) } case 2 { mstore8(sub(resultPtr, 1), 0x3d) } } return result; } } // 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 pragma solidity >=0.5.17 <0.9.0; /** * A very basic layer contract that's initialized with different version of a layer * and then serves a layer based on an index. */ contract Layer { string[] private _layers; constructor(string[] memory layers) { _layers = layers; } function getLayerCount() external view returns (uint256 length) { return _layers.length; } function getLayer(uint256 index) external view returns (string memory) { return _layers[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.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 // https://aa.usno.navy.mil/faq/JD_formula.html // 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,,) = _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,) = _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) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,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) = _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) = _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) = _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) = _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,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _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,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _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; } }
see https:github.com/unlock-protocol/unlock/blob/master/smart-contracts/contracts/interfaces/hooks/IHook.sol uint timeOfDay = 0; string memory kind = ""; (, , , uint hour, , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp); if (hour <= 8) { timeOfDay = 0; 0 => night } else if (hour <= 17) { timeOfDay = 1; 1 => day } else if (hour <= 21) { timeOfDay = 2; 2 => sunset } else { timeOfDay = 0; 0 => night } If the calling contract is the avatar contract if (lockAddress == _avatarLock) { kind = "avatars"; uint weapon = 0; Check if there is a mapping! if (avatarsWeapons[keyId] > 0) { If there is one, let's check the owner and make sure it's the correct one IPublicLock weaponLock = IPublicLock(_weaponLock); TODO change me in v10! uint weaponExpiration = weaponLock.keyExpirationTimestampFor(owner); address weaponOwner = weaponLock.ownerOf(keyId); if (weaponExpiration > block.timestamp && weaponOwner == owner) { weapon = avatarsWeapons[keyId]; } } image = string( abi.encodePacked( _ipfsHash, "/", kind, "/", Strings.toString(keyId), "-", Strings.toString(weapon), "-", Strings.toString(timeOfDay) ) ); } else if (lockAddress == _weaponLock) { kind = "weapons"; image = string( abi.encodePacked( _ipfsHash, "/", kind, "/", Strings.toString(keyId) ) ); } create the json that includes the image We need to include more properties! render the base64 encoded json metadata
function tokenURI( ) external view returns (string memory) { string memory image = "QmYkkshevBxHg7XwdP1pw6A4T82xzD8G2RpLDFo6KDy3zm"; string memory json = string( ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode(bytes(abi.encodePacked(json))) ) ); }
572,692
[ 1, 5946, 2333, 30, 6662, 18, 832, 19, 26226, 17, 8373, 19, 26226, 19, 10721, 19, 7525, 19, 26416, 17, 16351, 87, 19, 16351, 87, 19, 15898, 19, 10468, 19, 45, 5394, 18, 18281, 2254, 813, 17263, 273, 374, 31, 533, 3778, 3846, 273, 1408, 31, 261, 16, 269, 269, 2254, 6126, 16, 269, 262, 273, 605, 601, 18465, 52, 5161, 38, 69, 4487, 5096, 9313, 18, 5508, 774, 5096, 12, 2629, 18, 5508, 1769, 309, 261, 12091, 1648, 1725, 13, 288, 377, 813, 17263, 273, 374, 31, 225, 374, 516, 290, 750, 289, 469, 309, 261, 12091, 1648, 8043, 13, 288, 377, 813, 17263, 273, 404, 31, 225, 404, 516, 2548, 289, 469, 309, 261, 12091, 1648, 9035, 13, 288, 377, 813, 17263, 273, 576, 31, 225, 576, 516, 13887, 542, 289, 469, 288, 377, 813, 17263, 273, 374, 31, 225, 374, 516, 290, 750, 289, 225, 971, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1147, 3098, 12, 203, 565, 262, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 203, 3639, 533, 3778, 1316, 273, 315, 53, 81, 61, 79, 7904, 580, 90, 38, 92, 44, 75, 27, 60, 3623, 52, 21, 14921, 26, 37, 24, 56, 11149, 92, 94, 40, 28, 43, 22, 54, 84, 48, 4577, 83, 26, 47, 40, 93, 23, 94, 81, 14432, 203, 203, 203, 203, 203, 203, 203, 203, 203, 3639, 533, 3778, 1163, 273, 533, 12, 203, 3639, 11272, 203, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 315, 892, 30, 3685, 19, 1977, 31, 1969, 1105, 16, 3113, 203, 10792, 3360, 1105, 18, 3015, 12, 3890, 12, 21457, 18, 3015, 4420, 329, 12, 1977, 20349, 203, 7734, 262, 203, 5411, 11272, 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 ]
pragma solidity ^0.5.12; /* * @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 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 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; } } /** * @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. * * 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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 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 {ERC20Mintable}. * * 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; 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(_msgSender(), 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 amount) public 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 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 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 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 { 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, "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 { 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 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] = _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 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()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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"); } } } /** * @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); } } library ERC20WithFees { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Calls transferFrom on the token, returning the value transferred /// after fees. function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) { uint256 balancesBefore = token.balanceOf(to); token.safeTransferFrom(from, to, value); uint256 balancesAfter = token.balanceOf(to); return Math.min(value, balancesAfter.sub(balancesBefore)); } } /** * @dev Optional functions from the ERC20 standard. */ 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: 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; } } /** * @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(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); 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), "Roles: account is the zero address"); return role.bearer[account]; } } contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @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, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ 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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @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). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "Republic Token"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() ERC20Burnable() ERC20Pausable() ERC20Detailed(_name, _symbol, _decimals) public { _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { // Note: The deployed version has no revert reason /* solium-disable-next-line error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; modifier onlyPendingOwner() { require(_msgSender() == pendingOwner, "Claimable: caller is not the pending owner"); _; } function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = address(0); /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "LinkedList: already in list"); require(isInList(self, target) || target == NULL, "LinkedList: not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "LinkedList: already in list"); require(isInList(self, target) || target == NULL, "LinkedList: not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "LinkedList: not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].previous; } } contract CanReclaimTokens is Ownable { mapping(address => bool) private recoverableTokensBlacklist; function blacklistRecoverableToken(address _token) public { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require(!recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable"); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).transfer(msg.sender, ERC20(_token).balanceOf(address(this))); } } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Claimable, CanReclaimTokens { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address payable owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor( string memory _VERSION, RenToken _ren ) public { VERSION = _VERSION; ren = _ren; blacklistRecoverableToken(address(ren)); } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address payable _darknodeOwner, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner(), bond), "DarknodeRegistryStore: bond transfer failed"); } /// @notice Updates the bond of a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require(decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased"); darknodeRegistry[darknodeID].bond = decreasedBond; require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed"); } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address payable) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) { return darknodeRegistry[darknodeID].publicKey; } } interface IDarknodePaymentStore { } interface IDarknodePayment { function changeCycle() external returns (uint256); function store() external returns (IDarknodePaymentStore); } interface IDarknodeSlasher { } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Claimable, CanReclaimTokens { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocktime; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// The Darknode Payment contract for changing cycle IDarknodePayment public darknodePayment; /// Darknode Slasher allows darknodes to vote on bond slashing. IDarknodeSlasher public slasher; IDarknodeSlasher public nextSlasher; /// @notice Emitted when a darknode is registered. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address indexed _operator, address indexed _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered(address indexed _operator, address indexed _darknodeID); /// @notice Emitted when a refund has been made. /// @param _operator The owner of the darknode. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address indexed _operator, uint256 _amount); /// @notice Emitted when a darknode's bond is slashed. /// @param _operator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed(address indexed _operator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 _previousMinimumBond, uint256 _nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval); event LogSlasherUpdated(address _previousSlasher, address _nextSlasher); event LogDarknodePaymentUpdated(IDarknodePayment _previousDarknodePayment, IDarknodePayment _nextDarknodePayment); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner"); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered"); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch"); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable"); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require(address(slasher) == msg.sender, "DarknodeRegistry: must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs. constructor( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocktime: block.timestamp }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { // Use the current minimum bond as the darknode's bond. uint256 bond = minimumBond; // Transfer bond to store require(ren.transferFrom(msg.sender, address(store), bond), "DarknodeRegistry: bond transfer failed"); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, bond, _publicKey, currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocktime == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner(), "DarknodeRegistry: not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } if (address(darknodePayment) != address(0x0)) { darknodePayment.changeCycle(); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistry _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); } /// @notice Allows the contract owner to update the address of the /// darknode payment contract. /// @param _darknodePayment The address of the Darknode Payment /// contract. function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner { require(address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address"); IDarknodePayment previousDarknodePayment = darknodePayment; darknodePayment = _darknodePayment; emit LogDarknodePaymentUpdated(previousDarknodePayment, darknodePayment); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { require(address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address"); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash(address _guilty, address _challenger, uint256 _percentage) external onlySlasher { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 reward = penalty.div(2); if (reward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Distribute the remaining bond into the darknode payment reward pool require(address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address"); require(ren.transfer(address(darknodePayment.store()), reward), "DarknodeRegistry: reward transfer failed"); require(ren.transfer(_challenger, reward), "DarknodeRegistry: reward transfer failed"); } emit LogDarknodeSlashed(store.darknodeOwner(_guilty), _guilty, _challenger, _percentage); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN require(ren.transfer(darknodeOwner, amount), "DarknodeRegistry: bond transfer failed"); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address payable) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocktime; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocktime; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocktime.add(minimumEpochInterval)); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(msg.sender, _darknodeID); } } /// @notice DarknodePaymentStore is responsible for tracking balances which have /// been allocated to the darknodes. It is also responsible for holding /// the tokens to be paid out to darknodes. contract DarknodePaymentStore is Claimable { using SafeMath for uint256; using SafeERC20 for ERC20; using ERC20WithFees for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Mapping of darknode -> token -> balance mapping(address => mapping(address => uint256)) public darknodeBalances; /// @notice Mapping of token -> lockedAmount mapping(address => uint256) public lockedBalances; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor( string memory _VERSION ) public { VERSION = _VERSION; } /// @notice Allow direct ETH payments to be made to the DarknodePaymentStore. function () external payable { } /// @notice Get the total balance of the contract for a particular token /// /// @param _token The token to check balance of /// @return The total balance of the contract function totalBalance(address _token) public view returns (uint256) { if (_token == ETHEREUM) { return address(this).balance; } else { return ERC20(_token).balanceOf(address(this)); } } /// @notice Get the available balance of the contract for a particular token /// This is the free amount which has not yet been allocated to /// darknodes. /// /// @param _token The token to check balance of /// @return The available balance of the contract function availableBalance(address _token) public view returns (uint256) { return totalBalance(_token).sub(lockedBalances[_token]); } /// @notice Increments the amount of funds allocated to a particular /// darknode. /// /// @param _darknode The address of the darknode to increase balance of /// @param _token The token which the balance should be incremented /// @param _amount The amount that the balance should be incremented by function incrementDarknodeBalance(address _darknode, address _token, uint256 _amount) external onlyOwner { require(_amount > 0, "DarknodePaymentStore: invalid amount"); require(availableBalance(_token) >= _amount, "DarknodePaymentStore: insufficient contract balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(_amount); lockedBalances[_token] = lockedBalances[_token].add(_amount); } /// @notice Transfers an amount out of balance to a specified address /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer /// @param _amount The amount to transfer /// @param _recipient The address to withdraw it to function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner { require(darknodeBalances[_darknode][_token] >= _amount, "DarknodePaymentStore: insufficient darknode balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount); lockedBalances[_token] = lockedBalances[_token].sub(_amount); if (_token == ETHEREUM) { _recipient.transfer(_amount); } else { ERC20(_token).safeTransfer(_recipient, _amount); } } } /// @notice DarknodePayment is responsible for paying off darknodes for their /// computation. contract DarknodePayment is Claimable { using SafeMath for uint256; using SafeERC20 for ERC20; using ERC20WithFees for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; // Passed in as a constructor parameter. /// @notice DarknodePaymentStore is the storage contract for darknode /// payments. DarknodePaymentStore public store; // Passed in as a constructor parameter. /// @notice The address that can call changeCycle() // This defaults to the owner but should be changed to the DarknodeRegistry. address public cycleChanger; uint256 public currentCycle; uint256 public previousCycle; /// @notice The list of tokens that will be registered next cycle. /// We only update the shareCount at the change of cycle to /// prevent the number of shares from changing. address[] public pendingTokens; /// @notice The list of tokens which are already registered and rewards can /// be claimed for. address[] public registeredTokens; /// @notice Mapping from token -> index. Index starts from 1. 0 means not in /// list. mapping(address => uint256) public registeredTokenIndex; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for all darknodes to claim into /// their account. mapping(address => uint256) public unclaimedRewards; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for each darknode. mapping(address => uint256) public previousCycleRewardShare; /// @notice The time that the current cycle started. uint256 public cycleStartTime; /// @notice The staged payout percentage to the darknodes per cycle uint256 public nextCyclePayoutPercent; /// @notice The current cycle payout percentage to the darknodes uint256 public currentCyclePayoutPercent; /// @notice Mapping of darknode -> cycle -> already_claimed /// Used to keep track of which darknodes have already claimed their /// rewards. mapping(address => mapping(uint256 => bool)) public rewardClaimed; /// @notice Emitted when a darknode claims their share of reward /// @param _darknode The darknode which claimed /// @param _cycle The cycle that the darknode claimed for event LogDarknodeClaim(address indexed _darknode, uint256 _cycle); /// @notice Emitted when someone pays the DarknodePayment contract /// @param _payer The darknode which claimed /// @param _amount The cycle that the darknode claimed for /// @param _token The address of the token that was transferred event LogPaymentReceived(address indexed _payer, uint256 _amount, address indexed _token); /// @notice Emitted when a darknode calls withdraw /// @param _payee The address of the darknode which withdrew /// @param _value The amount of DAI withdrawn /// @param _token The address of the token that was withdrawn event LogDarknodeWithdrew(address indexed _payee, uint256 _value, address indexed _token); /// @notice Emitted when the payout percent changes /// @param _newPercent The new percent /// @param _oldPercent The old percent event LogPayoutPercentChanged(uint256 _newPercent, uint256 _oldPercent); /// @notice Emitted when the CycleChanger address changes /// @param _newCycleChanger The new CycleChanger /// @param _oldCycleChanger The old CycleChanger event LogCycleChangerChanged(address _newCycleChanger, address _oldCycleChanger); /// @notice Emitted when a new token is registered /// @param _token The token that was registered event LogTokenRegistered(address _token); /// @notice Emitted when a token is deregistered /// @param _token The token that was deregistered event LogTokenDeregistered(address _token); /// @notice Emitted when the DarknodeRegistry is updated. /// @param _previousDarknodeRegistry The address of the old registry. /// @param _nextDarknodeRegistry The address of the new registry. event LogDarknodeRegistryUpdated(DarknodeRegistry _previousDarknodeRegistry, DarknodeRegistry _nextDarknodeRegistry); /// @notice Restrict a function registered dark nodes to call a function. modifier onlyDarknode(address _darknode) { require(darknodeRegistry.isRegistered(_darknode), "DarknodePayment: darknode is not registered"); _; } /// @notice Restrict a function to have a valid percentage modifier validPercent(uint256 _percent) { require(_percent <= 100, "DarknodePayment: invalid percentage"); _; } /// @notice The contract constructor. Starts the current cycle using the /// time of deploy. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract /// @param _darknodePaymentStore The address of the DarknodePaymentStore /// contract constructor( string memory _VERSION, DarknodeRegistry _darknodeRegistry, DarknodePaymentStore _darknodePaymentStore, uint256 _cyclePayoutPercent ) public validPercent(_cyclePayoutPercent) { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; store = _darknodePaymentStore; nextCyclePayoutPercent = _cyclePayoutPercent; // Default the cycleChanger to owner cycleChanger = msg.sender; // Start the current cycle (currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch(); currentCyclePayoutPercent = nextCyclePayoutPercent; } /// @notice Allows the contract owner to update the address of the /// darknode registry contract. /// @param _darknodeRegistry The address of the Darknode Registry /// contract. function updateDarknodeRegistry(DarknodeRegistry _darknodeRegistry) external onlyOwner { require(address(_darknodeRegistry) != address(0x0), "DarknodePayment: invalid Darknode Registry address"); DarknodeRegistry previousDarknodeRegistry = darknodeRegistry; darknodeRegistry = _darknodeRegistry; emit LogDarknodeRegistryUpdated(previousDarknodeRegistry, darknodeRegistry); } /// @notice Transfers the funds allocated to the darknode to the darknode /// owner. /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer function withdraw(address _darknode, address _token) public { address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode); require(darknodeOwner != address(0x0), "DarknodePayment: invalid darknode owner"); uint256 amount = store.darknodeBalances(_darknode, _token); require(amount > 0, "DarknodePayment: nothing to withdraw"); store.transfer(_darknode, _token, amount, darknodeOwner); emit LogDarknodeWithdrew(_darknode, amount, _token); } function withdrawMultiple(address _darknode, address[] calldata _tokens) external { for (uint i = 0; i < _tokens.length; i++) { withdraw(_darknode, _tokens[i]); } } /// @notice Forward all payments to the DarknodePaymentStore. function () external payable { address(store).transfer(msg.value); emit LogPaymentReceived(msg.sender, msg.value, ETHEREUM); } /// @notice The current balance of the contract available as reward for the /// current cycle function currentCycleRewardPool(address _token) external view returns (uint256) { uint256 total = store.availableBalance(_token).sub(unclaimedRewards[_token]); return total.div(100).mul(currentCyclePayoutPercent); } function darknodeBalances(address _darknodeID, address _token) external view returns (uint256) { return store.darknodeBalances(_darknodeID, _token); } /// @notice Changes the current cycle. function changeCycle() external returns (uint256) { require(msg.sender == cycleChanger, "DarknodePayment: not cycle changer"); // Snapshot balances for the past cycle uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { _snapshotBalance(registeredTokens[i]); } // Start a new cycle previousCycle = currentCycle; (currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch(); currentCyclePayoutPercent = nextCyclePayoutPercent; // Update the list of registeredTokens _updateTokenList(); return currentCycle; } /// @notice Deposits token into the contract to be paid to the Darknodes /// /// @param _value The amount of token deposit in the token's smallest unit. /// @param _token The token address function deposit(uint256 _value, address _token) external payable { uint256 receivedValue; if (_token == ETHEREUM) { require(_value == msg.value, "DarknodePayment: mismatched deposit value"); receivedValue = msg.value; address(store).transfer(msg.value); } else { require(msg.value == 0, "DarknodePayment: unexpected ether transfer"); // Forward the funds to the store receivedValue = ERC20(_token).safeTransferFromWithFees(msg.sender, address(store), _value); } emit LogPaymentReceived(msg.sender, receivedValue, _token); } /// @notice Forwards any tokens that have been sent to the DarknodePayment contract /// probably by mistake, to the DarknodePaymentStore. /// /// @param _token The token address function forward(address _token) external { if (_token == ETHEREUM) { // Its unlikely that ETH will need to be forwarded, but it is // possible. For example - if ETH had already been sent to the // contract's address before it was deployed, or if funds are sent // to it as part of a contract's self-destruct. address(store).transfer(address(this).balance); } else { ERC20(_token).safeTransfer(address(store), ERC20(_token).balanceOf(address(this))); } } /// @notice Claims the rewards allocated to the darknode last epoch. /// @param _darknode The address of the darknode to claim function claim(address _darknode) external onlyDarknode(_darknode) { require(darknodeRegistry.isRegisteredInPreviousEpoch(_darknode), "DarknodePayment: cannot claim for this epoch"); // Claim share of rewards allocated for last cycle _claimDarknodeReward(_darknode); emit LogDarknodeClaim(_darknode, previousCycle); } /// @notice Adds tokens to be payable. Registration is pending until next /// cycle. /// /// @param _token The address of the token to be registered. function registerToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] == 0, "DarknodePayment: token already registered"); require(!tokenPendingRegistration(_token), "DarknodePayment: token already pending registration"); pendingTokens.push(_token); } function tokenPendingRegistration(address _token) public view returns (bool) { uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { if (pendingTokens[i] == _token) { return true; } } return false; } /// @notice Removes a token from the list of supported tokens. /// Deregistration is pending until next cycle. /// /// @param _token The address of the token to be deregistered. function deregisterToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] > 0, "DarknodePayment: token not registered"); _deregisterToken(_token); } /// @notice Updates the CycleChanger contract address. /// /// @param _addr The new CycleChanger contract address. function updateCycleChanger(address _addr) external onlyOwner { require(_addr != address(0), "DarknodePayment: invalid contract address"); emit LogCycleChangerChanged(_addr, cycleChanger); cycleChanger = _addr; } /// @notice Updates payout percentage /// /// @param _percent The percentage of payout for darknodes. function updatePayoutPercentage(uint256 _percent) external onlyOwner validPercent(_percent) { uint256 oldPayoutPercent = nextCyclePayoutPercent; nextCyclePayoutPercent = _percent; emit LogPayoutPercentChanged(nextCyclePayoutPercent, oldPayoutPercent); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodePaymentStore. /// /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodePayment _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another DarknodePaymentStore. function claimStoreOwnership() external { store.claimOwnership(); } /// @notice Claims the darknode reward for all registered tokens into /// darknodeBalances in the DarknodePaymentStore. /// Rewards can only be claimed once per cycle. /// /// @param _darknode The address to the darknode to claim rewards for function _claimDarknodeReward(address _darknode) private { require(!rewardClaimed[_darknode][previousCycle], "DarknodePayment: reward already claimed"); rewardClaimed[_darknode][previousCycle] = true; uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = registeredTokens[i]; // Only increment balance if shares were allocated last cycle if (previousCycleRewardShare[token] > 0) { unclaimedRewards[token] = unclaimedRewards[token].sub(previousCycleRewardShare[token]); store.incrementDarknodeBalance(_darknode, token, previousCycleRewardShare[token]); } } } /// @notice Snapshots the current balance of the tokens, for all registered /// tokens. /// /// @param _token The address the token to snapshot. function _snapshotBalance(address _token) private { uint256 shareCount = darknodeRegistry.numDarknodesPreviousEpoch(); if (shareCount == 0) { unclaimedRewards[_token] = 0; previousCycleRewardShare[_token] = 0; } else { // Lock up the current balance for darknode reward allocation uint256 total = store.availableBalance(_token); unclaimedRewards[_token] = total.div(100).mul(currentCyclePayoutPercent); previousCycleRewardShare[_token] = unclaimedRewards[_token].div(shareCount); } } /// @notice Deregisters a token, removing it from the list of /// registeredTokens. /// /// @param _token The address of the token to deregister. function _deregisterToken(address _token) private { address lastToken = registeredTokens[registeredTokens.length.sub(1)]; uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1); // Move the last token to _token's position and update it's index registeredTokens[deletedTokenIndex] = lastToken; registeredTokenIndex[lastToken] = registeredTokenIndex[_token]; // Decreasing the length will clean up the storage for us // So we don't need to manually delete the element registeredTokens.length = registeredTokens.length.sub(1); registeredTokenIndex[_token] = 0; emit LogTokenDeregistered(_token); } /// @notice Updates the list of registeredTokens adding tokens that are to be registered. /// The list of tokens that are pending registration are emptied afterwards. function _updateTokenList() private { // Register tokens uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = pendingTokens[i]; registeredTokens.push(token); registeredTokenIndex[token] = registeredTokens.length; emit LogTokenRegistered(token); } pendingTokens.length = 0; } }
@notice Transfers the funds allocated to the darknode to the darknode owner. @param _darknode The address of the darknode @param _token Which token to transfer
function withdraw(address _darknode, address _token) public { address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode); require(darknodeOwner != address(0x0), "DarknodePayment: invalid darknode owner"); uint256 amount = store.darknodeBalances(_darknode, _token); require(amount > 0, "DarknodePayment: nothing to withdraw"); store.transfer(_darknode, _token, amount, darknodeOwner); emit LogDarknodeWithdrew(_darknode, amount, _token); }
7,310,798
[ 1, 1429, 18881, 326, 284, 19156, 11977, 358, 326, 23433, 2159, 358, 326, 23433, 2159, 540, 3410, 18, 225, 389, 25045, 2159, 1021, 1758, 434, 326, 23433, 2159, 225, 389, 2316, 21918, 1147, 358, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 12, 2867, 389, 25045, 2159, 16, 1758, 389, 2316, 13, 1071, 288, 203, 3639, 1758, 8843, 429, 23433, 2159, 5541, 273, 23433, 2159, 4243, 18, 588, 40, 1313, 2159, 5541, 24899, 25045, 2159, 1769, 203, 3639, 2583, 12, 25045, 2159, 5541, 480, 1758, 12, 20, 92, 20, 3631, 315, 40, 1313, 2159, 6032, 30, 2057, 23433, 2159, 3410, 8863, 203, 203, 3639, 2254, 5034, 3844, 273, 1707, 18, 25045, 2159, 38, 26488, 24899, 25045, 2159, 16, 389, 2316, 1769, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 40, 1313, 2159, 6032, 30, 5083, 358, 598, 9446, 8863, 203, 203, 3639, 1707, 18, 13866, 24899, 25045, 2159, 16, 389, 2316, 16, 3844, 16, 23433, 2159, 5541, 1769, 203, 3639, 3626, 1827, 40, 1313, 2159, 1190, 72, 16052, 24899, 25045, 2159, 16, 3844, 16, 389, 2316, 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 ]
pragma solidity ^0.5.2; /* * * WELCOME TO THE SUSTAINABLE UPSWEEP NETWORK * * upsweep.net * * Gambling with low gas fees, no edge and no leaks. * * * _19^^^^0^^^^1_ * .18'' ``2. * .17' * .16' Here's to the `3. * .15' unfolding `4. * :: of hope. :: * :: ................... :: * :: :: * `14. @author .5' * `13. symmetricproof .6' * `12. .7' * `11.. ..8' * ^10........9^ * '''' * * /* @title The Upsweep Network; a social and sustainable circle of bets. */ contract UpsweepV1 { uint public elapsed; uint public timeout; uint public lastId; uint public counter; bool public closed; struct Player { bool revealOnce; bool claimed; bool gotHonour; uint8 i; bytes32 commit; } mapping(uint => mapping (address => Player)) public player; mapping(uint => uint8[20]) public balancesById; mapping(uint => uint8[20]) public bottleneckById; address payable public owner = msg.sender; uint public ticketPrice = 100000000000000000; mapping(uint => uint) public honour; event FirstBlock(uint); event LastBlock(uint); event Join(uint); event Reveal(uint seat, uint indexed gameId); event NewId(uint); modifier onlyBy(address _account) { require( msg.sender == _account, "Sender not authorized." ); _; } modifier circleIsPrivate(bool _closed) { require( _closed == true, "Game is in progress." ); _; } modifier circleIsPublic(bool _closed) { require( _closed == false, "Next game has not started." ); _; } modifier onlyAfter(uint _time) { require( block.number > _time, "Function called too early." ); _; } modifier onlyBefore(uint _time) { require( block.number <= _time, "Function called too late." ); _; } modifier ticketIsAffordable(uint _amount) { require( msg.value >= _amount, "Not enough Ether provided." ); _; if (msg.value > _amount) msg.sender.transfer(msg.value - _amount); } /** * @dev pick a number and cast the hash to the network. * @param _hash is the keccak256 output for the address of the message sender+ * the number + a passphrase */ function join(bytes32 _hash) public payable circleIsPublic(closed) ticketIsAffordable(ticketPrice) returns (uint gameId) { //the circle is only open to 40 players. require( counter < 40, "Game is full." ); //timer starts when the first ticket of the game is sold if (counter == 0) { elapsed = block.number; emit FirstBlock(block.number); } player[lastId][msg.sender].commit = _hash; //when the game is full, timer stops and the countdown to reveal begins //NO MORE COMMITS ARE RECEIVED. if (counter == 39) { closed = true; uint temp = sub(block.number,elapsed); timeout = add(temp,block.number); emit LastBlock(timeout); } counter++; emit Join(counter); return lastId; } /** * @notice get a refund and exit the game before it begins */ function abandon() public circleIsPublic(closed) returns (bool success) { bytes32 commit = player[lastId][msg.sender].commit; require( commit != 0, "Player was not in the game." ); player[lastId][msg.sender].commit = 0; counter --; if (counter == 0) { elapsed = 0; emit FirstBlock(0); } emit Join(counter); msg.sender.transfer(ticketPrice); return true; } /** * @notice to make your bet legal, you must reveal the corresponding number * @dev a new hash is computed to verify authenticity of the bet * @param i is the number (between 0 and 19) * @param passphrase to prevent brute-force validation */ function reveal( uint8 i, string memory passphrase ) public circleIsPrivate(closed) onlyBefore(timeout) returns (bool success) { bool status = player[lastId][msg.sender].revealOnce; require( status == false, "Player already revealed." ); bytes32 commit = player[lastId][msg.sender].commit; //hash is recalculated to verify authenticity bytes32 hash = keccak256( abi.encodePacked(msg.sender,i,passphrase) ); require( hash == commit, "Hashes don't match." ); player[lastId][msg.sender].revealOnce = true; player[lastId][msg.sender].i = i; //contribution is credited to the chosen number balancesById[lastId][i] ++; //the list of players inside this numbers grows by one bottleneckById[lastId][i] ++; counter--; //last player to reveal must pay extra gas fees to update the game if (counter == 0) { timeout = 0; updateBalances(); } emit Reveal(i,lastId); return true; } /** * @notice distributes rewards fairly. * @dev the circle has no head or foot, node 19 passes to node 0 only if node 0 is not empty. * To successfully distribute contributions, the function loops through all numbers and * identifies the first empty number, from there the chain of transfers begins. * */ function updateBalances() public circleIsPrivate(closed) onlyAfter(timeout) returns (bool success) { // identify the first empty number. for (uint8 i = 0; i < 20; i++) { if (balancesById[lastId][i] == 0) { // start chain of transfers from the next number. uint j = i + 1; for (uint8 a = 0; a < 19; a++) { if (j == 20) j = 0; if (j == 19) { if (balancesById[lastId][0] > 0) { uint8 temp = balancesById[lastId][19]; balancesById[lastId][19] = 0; balancesById[lastId][0] += temp; j = 0; } else { j = 1; } } else { if (balancesById[lastId][j + 1] > 0) { uint8 temp = balancesById[lastId][j]; balancesById[lastId][j] = 0; balancesById[lastId][j + 1] += temp; j += 1; } else { j += 2; } } } // will break when all balances are updated. break; } } // reset variables and start a new game. closed = false; if (timeout > 0) timeout = 0; elapsed = 0; // players that reveal are rewarded the ticket value of those // that don't reveal. if (counter > 0) { uint total = mul(counter, ticketPrice); uint among = sub(40,counter); honour[lastId] = div(total,among); counter = 0; } lastId ++; emit NewId(lastId); return true; } /** * @notice accumulated rewards are already allocated in specific numbers, if players can * prove they picked that "lucky" number, they are allowed to withdraw the accumulated * ether. * * If there is more than one player in a given number, the reward is split equally. * * @param gameId only attempt to withdraw rewards from a valid game, otherwise the transaction * will fail. */ function withdraw(uint gameId) public returns (bool success) { bool status = player[gameId][msg.sender].revealOnce; require( status == true, "Player has not revealed." ); bool claim = player[gameId][msg.sender].claimed; require( claim == false, "Player already claimed." ); uint8 index = player[gameId][msg.sender].i; require( balancesById[gameId][index] > 0, "Player didn't won." ); player[gameId][msg.sender].claimed = true; uint temp = uint(balancesById[gameId][index]); uint among = uint(bottleneckById[gameId][index]); uint total = mul(temp, ticketPrice); uint payout = div(total, among); msg.sender.transfer(payout); return true; } function microTip() public payable returns (bool success) { owner.transfer(msg.value); return true; } function changeOwner(address payable _newOwner) public onlyBy(owner) returns (bool success) { owner = _newOwner; return true; } function getHonour(uint _gameId) public returns (bool success) { bool status = player[_gameId][msg.sender].gotHonour; require( status == false, "Player already claimed honour." ); bool revealed = player[_gameId][msg.sender].revealOnce; require( revealed == true, "Player has not revealed." ); player[_gameId][msg.sender].gotHonour = true; msg.sender.transfer(honour[_gameId]); return true; } /** * @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) { // 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; } /** * @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; } }
reset variables and start a new game.
closed = false;
1,831,134
[ 1, 6208, 3152, 471, 787, 279, 394, 7920, 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 ]
[ 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, 0 ]
[ 1, 3639, 4375, 273, 629, 31, 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, -100, -100, -100, -100, -100 ]