Forkchoice Ethereum Mainnet

Address Contract Verified

Address 0xB9ce243fFaDb1f69828688Eacb244e784C5fDB16
Balance 0 ETH
Nonce 1
Code Size 10833 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

10833 bytes
0x6101406040526004361015610012575f80fd5b5f803560e01c80630e093430146123935780631069f3b514612283578063189062871461224c5780633a5d5982146122235780633f138d4b146121e9578063429692a7146121cc578063441a3e7014611fc85780635312ea8e14611e4a57806353fd88bf14611b7f57806360f13b3f14611b3757806366d0d269146116225780636c106f2e146115dd578063715018a61461158357806374f0314f146115655780637822be4a1461153c5780637b0472f01461113f5780637da470ea14610fbb57806381fb1fb414610f705780638385eae014610f465780638da5cb5b14610f1f57806393f1a40b14610e915780639622aaa414610e5d578063978bfab014610d9157806398969e8214610c4c578063a98b3a6d14610c13578063b3f0067414610bea578063b6b2a7a514610bca578063c1e3bd3e14610b7a578063cc430ced14610b5a578063ccd34cd514610b37578063d7098154146109b1578063e7a7f65c1461095e578063ebf5cd5b146102c1578063efdcd974146102245763f2fde38b1461019c575f80fd5b34610221576020366003190112610221576101b5612496565b6101bd6128e3565b6001600160a01b0316801561020d5781546001600160a01b03198116821783556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b631e4fbdf760e01b82526004829052602482fd5b80fd5b50346102215760203660031901126102215761023e612496565b6102466128e3565b6001600160a01b03168015610270576bffffffffffffffffffffffff60a01b600754161760075580f35b60405162461bcd60e51b815260206004820152602360248201527f4665652072656365697665722063616e6e6f74206265207a65726f206164647260448201526265737360e81b6064820152608490fd5b5034610221576101a0366003190112610221576102dc612496565b6102e4612480565b9060c435604435608435610144356001600160a01b0385161561090e576001600160a01b038616156108bd5742606435106108795760643582111561082a576103316103e8851115612777565b6103416103e860e43511156127cf565b82156107da57610104351561078b578015806107465761016435156106f65761018435156106b1576106a7575b6020936040519261037f86856125e4565b8884525f36813760405194610393866125c7565b60018060a01b038816865260018060a01b0389168787015260408601526064356060860152608085015260643560a08501528760c08501528760e085015260a43561010085015261012084015260e4356101408401526101043561016084015261012435610180840152866101a084015260016101c08401526101e0830152610164356102008301526101843561022083015260643561024083015285610260830152610280820152600254600160401b8110156106935780600161045b920160025561251d565b61067f57815181546001600160a01b039182166001600160a01b03199182161783558484015160018401805491909316911617905560408201516002820155606082015160038201556080820151600482015560a0820151600582015560c0820151600682015560e0820151600782015561010082015160088201556101208201516009820155610140820151600a820155610160820151600b820155610180820151600c8201556101a0820151600d8201805460ff191691151560ff1691909117815561028091601391610546906101c0860151815461ff00191690151560081b61ff0016179055565b6101e0840151600e820155610200840151600f820155610220840151601082015561024084015160118201556102608401516012820155019101519081519167ffffffffffffffff831161066b57600160401b831161066b5783908254848455808510610643575b5001908652828620865b8381106106285750505050600254925f19840193841161061457604080516001600160a01b03948516815293909116918301919091527f907cf7e059fc0289bbe6cfc7a038b9cf2f0a7ae781f7656e0d95c29bc13117da91a280f35b634e487b7160e01b85526011600452602485fd5b82516001600160a01b031682820155918401916001016105b8565b83895284838a2091820191015b81811061065d57506105ae565b898155869350600101610650565b634e487b7160e01b87526041600452602487fd5b634e487b7160e01b86526004869052602486fd5b634e487b7160e01b86526041600452602486fd5b5062093a8061036e565b60405162461bcd60e51b815260206004820152601d60248201527f57696e6e657220636f756e74206d75737420626520706f7369746976650000006044820152606490fd5b60405162461bcd60e51b815260206004820152602260248201527f5469636b65747320706572207374616b65206d75737420626520706f73697469604482015261766560f01b6064820152608490fd5b60405162461bcd60e51b815260206004820152601e60248201527f4472617720696e74657276616c206d75737420626520706f73697469766500006044820152606490fd5b60405162461bcd60e51b815260206004820152602160248201527f4d696e207374616b6520616d6f756e74206d75737420626520706f73697469766044820152606560f81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602260248201527f52657761726420706572207365636f6e64206d75737420626520706f73697469604482015261766560f01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602160248201527f456e642074696d65206d7573742062652061667465722073746172742074696d6044820152606560f81b6064820152608490fd5b606460405162461bcd60e51b815260206004820152602060248201527f53746172742074696d65206d75737420626520696e20746865206675747572656044820152fd5b60405162461bcd60e51b815260206004820152602360248201527f52657761726420746f6b656e2063616e6e6f74206265207a65726f206164647260448201526265737360e81b6064820152608490fd5b60405162461bcd60e51b815260206004820152602260248201527f5374616b6520746f6b656e2063616e6e6f74206265207a65726f206164647265604482015261737360f01b6064820152608490fd5b50346102215760403660031901126102215760406004359161097e612480565b9261098c6002548210612664565b81526005602052209060018060a01b03165f52602052602060405f2054604051908152f35b5034610221576020366003190112610221576004356109ce612944565b6109db6002548210612664565b6109e48161251d565b50828390601383018054925b838110610b01575b505015610acd57828452600360209081526040808620335f9081529252902060050180549092600882901c60ff16610a905761010093610a3f610a5d94601284015461299a565b94859361ff00191617905533906001808060a01b0391015416612909565b6040519081527f256642a903d86ec186d0ad895b74bdbe7f9e5a72db568f4c4d58c2fa38b39e1c60203392a36001805580f35b60405162461bcd60e51b8152602060048201526015602482015274416c726561647920636c61696d6564207072697a6560581b6044820152606490fd5b60405162461bcd60e51b815260206004820152600c60248201526b2737ba1030903bb4b73732b960a11b6044820152606490fd5b610b0b818361254d565b905460039190911b1c6001600160a01b03163314610b2b576001016109f0565b50505060015f806109f8565b50346102215780600319360112610221576020604051670de0b6b3a76400008152f35b503461022157602036600319011261022157610b77600435612827565b80f35b503461022157602036600319011261022157610bb26040610bc692600435610ba56002548210612664565b81526004602052206126a6565b6040519182916020835260208301906124e1565b0390f35b503461022157806003193601126102215750602062093a80604051908152f35b50346102215780600319360112610221576007546040516001600160a01b039091168152602090f35b50346102215760203660031901126102215760206011610c41600435610c3c6002548210612664565b61251d565b500154604051908152f35b503461022157604036600319011261022157600435610c69612480565b610c766002548310612664565b610c7f8261251d565b509183526003602052604083209060018060a01b03165f5260205260405f2091600682015491600581015480421180610d84575b610ce6575b6020610cde866001670de0b6b3a7640000610cd4898454612562565b04910154906128d6565b604051908152f35b610d00610d0b9160048401544281105f14610d7d576128d6565b600283015490612562565b90670de0b6b3a7640000820291808304670de0b6b3a76400001490151715610d695760070154610d3a9161299a565b8201809211610d555750816001670de0b6b3a7640000610cb8565b634e487b7160e01b81526011600452602490fd5b634e487b7160e01b83526011600452602483fd5b50426128d6565b5060078201541515610cb3565b50346102215761014036600319011261022157600435606435608435610db56128e3565b610dc26002548410612664565b610dcb8361251d565b5091610ddb6103e8821115612777565b610de96103e88311156127cf565b610df284612827565b602435600284015560443560088401556009830155600a82015560a435600b82015560c435600c82015560e435600e82015561010435600f8201556010610124359101557fdfc6dcf27ce9b06323e51aa357be4568ae42dfa29228c97d2f4e020f94fbad2b8280a280f35b503461022157602036600319011261022157610bc6610bb26013610e8a600435610c3c6002548210612664565b50016126a6565b5034610221576040366003190112610221576040610ead612480565b9160043581526003602052209060018060a01b03165f5260205260e060405f2060ff815491600181015490600281015460038201549060056004840154930154936040519687526020870152604086015260608501526080840152818116151560a084015260081c16151560c0820152f35b5034610221578060031936011261022157546040516001600160a01b039091168152602090f35b50346102215760203660031901126102215760406020916004358152600683522054604051908152f35b503461022157610f7f366124cb565b91908152600460205260408120908154831015610221576020610fa2848461254d565b905460405160039290921b1c6001600160a01b03168152f35b503461022157602036600319011261022157600435906002548210156102215750600f60ff600e600d600c600b600a600960086007600660056004600361100360129f61251d565b509e8f9e8f9d8e9d8e9d8e9d8e9d8e9d8e9d8e9d8e9d8e9d8e9d8e9d8e60018060a01b039054169e60018060a01b036001820154166101005260028101546101205201549e01549e01549e01549e01549e01549e01549e01549e01549e01549e01549e01549f01549f6010810154608052601181015460c052015460e05260405160a05260a0515261010051602060a051015261012051604060a0510152606060a0510152608060a051015260a08051015260c060a051015260e060a051015261010060a051015261012060a051015261014060a051015261016060a051015261018060a051015281811615156101a060a051015260081c1615156101c060a05101526101e060a051015261020060a051015260805161022060a051015260c05161024060a051015260e05161026060a051015261028060a051f35b50346102215761114e366124cb565b611156612944565b6111636002548310612664565b61116c8261251d565b5061118c60ff600d830154611185828260081c166126f9565b161561273a565b600381015442106114f75760048101544210156114c157600b810154821061147c57600c8101548061142b575b506111c383612827565b82845260036020526040842060018060a01b0333165f5260205260405f2061122560018060a01b03835416604051906323b872dd60e01b6020830152336024830152306044830152856064830152606482526112206084836125e4565b6129b8565b611241612710611239600985015486612562565b0480946128d6565b9280611409575b508054156113a4575b670de0b6b3a7640000611283600f8401546201518060088601540490811561139b575b61127e9087612562565b612562565b04600282018054908282018092116113875781905585875260056020526040872060018060a01b0333165f5260205260405f2055848652600660205260408620549081018091116113735784865260066020526040862055805483810180911161137357670de0b6b3a7640000611304826001938555600686015490612562565b0491015560078101805490838201809211611373575560328202908282046032148315171561061457601201606481549204820180921161061457556040519081527f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a1560203392a36001805580f35b634e487b7160e01b86526011600452602486fd5b634e487b7160e01b88526011600452602488fd5b60019150611274565b42600382015560088201544201804211611373576004820155838552600460205260408520805490600160401b82101561066b57906113e89160018201815561254d565b81546001600160a01b0360039290921b91821b19163390911b179055611251565b825460075461142592916001600160a01b039182169116612909565b5f611248565b8211611437575f6111b9565b60405162461bcd60e51b815260206004820152601e60248201527f416d6f756e74206d6f7265207468616e206d6178696d756d207374616b6500006044820152606490fd5b60405162461bcd60e51b815260206004820152601e60248201527f416d6f756e74206c657373207468616e206d696e696d756d207374616b6500006044820152606490fd5b60405162461bcd60e51b815260206004820152600e60248201526d11985c9b481a185cc8195b99195960921b6044820152606490fd5b60405162461bcd60e51b815260206004820152601860248201527f4661726d20686173206e6f7420737461727465642079657400000000000000006044820152606490fd5b50346102215760203660031901126102215760206012610c41600435610c3c6002548210612664565b50346102215780600319360112610221576020604051620151808152f35b503461022157806003193601126102215761159c6128e3565b80546001600160a01b03198116825581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b50346102215760403660031901126102215760406115f9612480565b9160043581526005602052209060018060a01b03165f52602052602060405f2054604051908152f35b50346102215760203660031901126102215761163c612944565b61164b60025460043510612664565b61165660043561251d565b509061167060ff600d840154611185828260081c166126f9565b6011820154600e8301548101809111611b23574210611ae65760043581526006602052604081205415611aa85760128201805460011c90601084015490600435845260046020526040842054918281115f14611aa25750815b6116d28361261e565b926116dc8261261e565b865b838110611a8d575060043587526006602052604087205492875b8381106117ef5750505050506013850194825167ffffffffffffffff811161069357600160401b81116106935786548188558082106117c9575b50602084019686526020862096865b8281106117ac57505050907f48092fddd56a35f453ebe8fc79dd0e1c79880dc7307e3163e5d7986f37f6f6d092916011429101556117808482546128d6565b9055611797604051916040835260408301906124e1565b92602082015280600435930390a26001805580f35b81516001600160a01b0316818a0155602090910190600101611741565b878752816020882091820191015b8181106117e45750611732565b8781556001016117d7565b604080514260208201908152449282019290925233606090811b6bffffffffffffffffffffffff1916908201526074810183905261183a81609481015b03601f1981018352826125e4565b51902061184782846128d6565b908115611a7957066004358a52600460205261187160408b2061186a8387612650565b519061254d565b60018060a01b0391549060031b1c166004358b52600560205260408b2060018060a01b0382165f5260205260405f2054670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a6557876118cc9161299a565b670de0b6b3a764000060405160208101906119188161182c898844428892909160749492845260208401526bffffffffffffffffffffffff199060601b16604083015260548201520190565b5190200610156119775761192c838a612650565b525b61193882846128d6565b5f198101908111611963579061195c6119546001949387612650565b519186612650565b52016116f8565b634e487b7160e01b8b52601160045260248bfd5b508980805b8581106119a157505061198f838a612650565b6001600160a01b03909116905261192e565b6119c4818e9d9c9b9a99989796959f9e604090600435815260046020522061254d565b60018060a01b0391549060031b1c166004358d52600560205260408d2060018060a01b0382165f5260205260405f20548d805b878110611a38575b509f95969798999a9b9c9d9e9f1580611a2f575b611a22575b505060010161197c565b909350915060015f611a18565b50838111611a13565b838e611a4b8360018060a01b0392612650565b511614611a5a576001016119f7565b50600190505f6119ff565b634e487b7160e01b8c52601160045260248cfd5b634e487b7160e01b8b52601260045260248bfd5b8080611a9b60019385612650565b52016116de565b916116c9565b60405162461bcd60e51b8152602060048201526016602482015275139bc81d1a58dad95d1cc81a5b881d1a19481c1bdbdb60521b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274139bdd081d1a5b5948199bdc88191c985dc81e595d605a1b6044820152606490fd5b634e487b7160e01b82526011600452602482fd5b503461022157610b77611b65600d611b4e366124ac565b9290611b586128e3565b610c3c6002548210612664565b50019061ff00825491151560081b169061ff001916179055565b503461022157602036600319011261022157611c3a610280916060836004359260405190611bac826125c7565b80825280602083015280604083015280848301528060808301528060a08301528060c08301528060e08301528061010083015280610120830152806101408301528061016083015280610180830152806101a0830152806101c0830152806101e08301528061020083015280610220830152806102408301526102608201520152610c3c6002548210612664565b50611d35601360405192611c4d846125c7565b80546001600160a01b0390811685526001820154166020850152600281015460408501526003810154606085015260048101546080850152600581015460a0850152600681015460c0850152600781015460e08501526008808201546101008601526009820154610120860152600a820154610140860152600b820154610160860152600c820154610180860152600d82015460ff81811615156101a0880152911c1615156101c0850152600e8101546101e0850152600f810154610200850152601081015461022085015260118101546102408501526012810154610260850152016126a6565b82820152610bc66040519283926020845260018060a01b03815116602085015260018060a01b0360208201511660408501526040810151606085015260608101516080850152608081015160a085015260a081015160c085015260c081015160e085015260e08101516101008501526101008101516101208501526101208101516101408501526101408101516101608501526101608101516101808501526101808101516101a08501526101a081015115156101c08501526101c081015115156101e08501526101e08101516102008501526102008101516102208501526102208101516102408501526102408101516102608501526102608101518285015201516102a0808401526102c08301906124e1565b5034611fc4576020366003190112611fc457600435611e67612944565b611e746002548210612664565b611e7d8161251d565b505f8281526003602090815260408083203380855290835281842080548582556001820186905560029091018590558685526005845282852091855290835281842084905585845260069092529091205490939015611fbd5750815f52600660205260405f2054925f935b838552600660205260408520556007820180548280821115611fb457611f0d916128d6565b905b55600a8201548060011b90808204600214901517156106145790611f44612710611f3c611f5f9484612562565b0480926128d6565b92818492611f92575b505433906001600160a01b0316612909565b6040519081527fbb757047c2b5f3974fe26b7c10f732e7bce710b0952a71082702781e62ae059560203392a36001805580f35b8154600754611fae92916001600160a01b039182169116612909565b5f611f4d565b50508490611f0f565b925f611ee8565b5f80fd5b34611fc457611fd6366124cb565b611fde612944565b611feb6002548310612664565b611ff48261251d565b5090825f52600360205260405f2060018060a01b0333165f5260205260405f20918183541061218757600483015442106121425760076120cd9161203786612827565b845494670de0b6b3a764000061207d60068401928261205785548b612562565b04936120738961206d60018501978854906128d6565b9b6128d6565b8092555490612562565b049055612710612091600a83015486612562565b049461209d86866128d6565b9580612121575b5081546120bd90879033906001600160a01b0316612909565b80612101575b50019182546128d6565b90556040519081527ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b56860203392a360018055005b600182015461211b919033906001600160a01b0316612909565b866120c3565b8254845461213c92916001600160a01b039182169116612909565b876120a4565b60405162461bcd60e51b815260206004820152601760248201527f546f6b656e7320617265207374696c6c206c6f636b65640000000000000000006044820152606490fd5b60405162461bcd60e51b815260206004820152601f60248201527f576974686472617720616d6f756e7420657863656564732062616c616e6365006044820152606490fd5b34611fc4575f366003190112611fc4576020600254604051908152f35b34611fc4576040366003190112611fc457612221612205612496565b61220d6128e3565b6024359033906001600160a01b0316612909565b005b34611fc457612221612239600d611b4e366124ac565b50019060ff801983541691151516179055565b34611fc4576020366003190112611fc45760043561226d6002548210612664565b5f526006602052602060405f2054604051908152f35b34611fc4576040366003190112611fc45760043561229f612480565b905f60c06040516122af81612597565b8281528260208201528260408201528260608201528260808201528260a082015201526122df6002548210612664565b5f52600360205260405f209060018060a01b03165f5260205260e060405f206040519061230b82612597565b805491828152600182015491602082019283526002810154604083019081526003820154906060840191825260056004840154936080860194855201549460ff60c060a087019682891615158852019660081c161515865260405196875251602087015251604086015251606085015251608084015251151560a083015251151560c0820152f35b34611fc4575f366003190112611fc4576002545f805b82811061244b57506123ba9061261e565b905f805b82811061240a57836040518091602082016020835281518091526020604084019201905f5b8181106123f1575050500390f35b82518452859450602093840193909201916001016123e3565b60ff600d6124178361251d565b50015460081c1661242b575b6001016123be565b90612443818361243d60019488612650565b52612589565b919050612423565b60ff600d6124588361251d565b50015460081c1661246c575b6001016123a9565b90612478600191612589565b919050612464565b602435906001600160a01b0382168203611fc457565b600435906001600160a01b0382168203611fc457565b6040906003190112611fc457600435906024358015158103611fc45790565b6040906003190112611fc4576004359060243590565b90602080835192838152019201905f5b8181106124fe5750505090565b82516001600160a01b03168452602093840193909201916001016124f1565b6002548110156125395760025f52601460205f20910201905f90565b634e487b7160e01b5f52603260045260245ffd5b8054821015612539575f5260205f2001905f90565b8181029291811591840414171561257557565b634e487b7160e01b5f52601160045260245ffd5b5f1981146125755760010190565b60e0810190811067ffffffffffffffff8211176125b357604052565b634e487b7160e01b5f52604160045260245ffd5b6102a0810190811067ffffffffffffffff8211176125b357604052565b90601f8019910116810190811067ffffffffffffffff8211176125b357604052565b67ffffffffffffffff81116125b35760051b60200190565b9061262882612606565b61263560405191826125e4565b8281528092612646601f1991612606565b0190602036910137565b80518210156125395760209160051b010190565b1561266b57565b60405162461bcd60e51b815260206004820152601360248201527211985c9b48191bd95cc81b9bdd08195e1a5cdd606a1b6044820152606490fd5b90604051918281549182825260208201905f5260205f20925f5b8181106126d75750506126d5925003836125e4565b565b84546001600160a01b03168352600194850194879450602090930192016126c0565b1561270057565b60405162461bcd60e51b81526020600482015260126024820152714661726d206973206e6f742061637469766560701b6044820152606490fd5b1561274157565b60405162461bcd60e51b815260206004820152600e60248201526d11985c9b481a5cc81c185d5cd95960921b6044820152606490fd5b1561277e57565b60405162461bcd60e51b815260206004820152602360248201527f4465706f736974206665652063616e6e6f74206265206d6f7265207468616e2060448201526231302560e81b6064820152608490fd5b156127d657565b60405162461bcd60e51b8152602060048201526024808201527f5769746864726177206665652063616e6e6f74206265206d6f7265207468616e6044820152632031302560e01b6064820152608490fd5b6128309061251d565b50600581019081544211156128d25760078101549081156128cb576004810154428110156128c157612865905b8454906128d6565b80156128bb5761287c600691600284015490612562565b910190815492670de0b6b3a7640000820291808304670de0b6b3a76400001490151715612575576128ac9161299a565b82018092116125755755429055565b50505050565b506128654261285d565b5050429055565b5050565b9190820391821161257557565b5f546001600160a01b031633036128f657565b63118cdaa760e01b5f523360045260245ffd5b60405163a9059cbb60e01b60208201526001600160a01b0390921660248301526044808301939093529181526126d5916112206064836125e4565b600260015414612955576002600155565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b81156129a4570490565b634e487b7160e01b5f52601260045260245ffd5b905f602091828151910182855af115612a10575f513d612a0757506001600160a01b0381163b155b6129e75750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b600114156129e0565b6040513d5f823e3d90fdfea2646970667358221220482b6ba041037e76fab5109a7b92ecf0f22514e1d4b283ee8276d8cac706043764736f6c634300081a0033

Verified Source Code Full Match

Compiler: v0.8.26+commit.8a97fa7a EVM: cancun Optimization: Yes (200 runs)
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
ReentrancyGuard.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

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() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @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 Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 198 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}
SafeMath.sol 215 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/SafeMath.sol)

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 generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction 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;
        }
    }
}
lotteryfarm.sol 744 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";

/**
 * @title LotteryFarm
 * @dev A staking contract that implements a lottery system where users can win prizes.
 * Users stake tokens for a specified period and earn lottery tickets (1 ticket per day staked).
 * A drawing is performed every 7 days (configurable) where winners are randomly selected.
 */
contract LotteryFarm is Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using SafeMath for uint256;

    // Structs
    struct UserInfo {
        uint256 amount;           // How many tokens the user has staked
        uint256 rewardDebt;       // Reward debt
        uint256 ticketCount;      // How many lottery tickets the user has
        uint256 stakeTime;        // When the user staked
        uint256 unlockTime;       // When the user can withdraw
        bool hasUnlockedTokens;   // Whether the user has tokens ready to unlock
        bool hasClaimed;          // Whether the user has claimed their prize
    }

    struct Farm {
        address stakeToken;       // Address of token to stake
        address rewardToken;      // Address of token to reward
        uint256 rewardPerSecond;  // Reward per second
        uint256 startTime;        // Start time of the farm
        uint256 endTime;          // End time of the farm
        uint256 lastRewardTime;   // Last timestamp reward was calculated
        uint256 accRewardPerShare;// Accumulated rewards per share, times 1e18
        uint256 totalStaked;      // Total tokens staked
        uint256 lockDuration;     // Duration in seconds tokens are locked
        uint256 depositFee;       // Deposit fee (if any)
        uint256 withdrawFee;      // Withdraw fee (if any)
        uint256 minStakeAmount;   // Minimum amount to stake
        uint256 maxStakeAmount;   // Maximum amount to stake (0 = no limit)
        bool paused;              // Is the farm paused?
        bool active;              // Is the farm active?
        uint256 drawInterval;     // Interval between lottery draws in seconds (default 7 days)
        uint256 ticketsPerStake;  // Number of tickets per day of staking per token
        uint256 winnerCount;      // Number of winners per draw
        uint256 lastDrawTime;     // Last time a draw was performed
        uint256 prizePool;        // Current prize pool amount
        address[] currentWinners; // Current winners of the draw
    }

    // Events
    event Deposit(address indexed user, uint256 indexed farmId, uint256 amount);
    event Withdraw(address indexed user, uint256 indexed farmId, uint256 amount);
    event EmergencyWithdraw(address indexed user, uint256 indexed farmId, uint256 amount);
    event FarmCreated(uint256 indexed farmId, address stakeToken, address rewardToken);
    event FarmUpdated(uint256 indexed farmId);
    event LotteryDrawPerformed(uint256 indexed farmId, address[] winners, uint256 prizeAmount);
    event PrizeClaimed(address indexed user, uint256 indexed farmId, uint256 amount);

    // State variables
    Farm[] public farms;
    mapping(uint256 => mapping(address => UserInfo)) public userInfo;
    mapping(uint256 => address[]) public participants;
    mapping(uint256 => mapping(address => uint256)) public userTicketsMap;
    mapping(uint256 => uint256) public totalTickets;

    // Fee receiver address
    address public feeReceiver;
    
    // Constants
    uint256 public constant SECONDS_PER_DAY = 86400;
    uint256 public constant DEFAULT_DRAW_INTERVAL = 7 * SECONDS_PER_DAY;
    uint256 public constant PRECISION_FACTOR = 1e18;

    /**
     * @dev Constructor
     * @param _feeReceiver Address to receive fees
     */
    constructor(address _feeReceiver) Ownable(msg.sender) {
        require(_feeReceiver != address(0), "Fee receiver cannot be zero address");
        feeReceiver = _feeReceiver;
    }

    /**
     * @dev Create a new farm
     * @param _stakeToken Stake token address
     * @param _rewardToken Reward token address
     * @param _rewardPerSecond Reward tokens per second
     * @param _startTime Start time of the farm
     * @param _endTime End time of the farm
     * @param _lockDuration Duration in seconds tokens are locked
     * @param _depositFee Deposit fee (percentage with 2 decimals, e.g. 100 = 1%)
     * @param _withdrawFee Withdraw fee (percentage with 2 decimals, e.g. 100 = 1%)
     * @param _minStakeAmount Minimum amount to stake
     * @param _maxStakeAmount Maximum amount to stake (0 = no limit)
     * @param _drawInterval Interval between draws in seconds
     * @param _ticketsPerStake Number of tickets per day of staking per token
     * @param _winnerCount Number of winners per draw
     */
    function createFarm(
        address _stakeToken,
        address _rewardToken,
        uint256 _rewardPerSecond,
        uint256 _startTime,
        uint256 _endTime,
        uint256 _lockDuration,
        uint256 _depositFee,
        uint256 _withdrawFee,
        uint256 _minStakeAmount,
        uint256 _maxStakeAmount,
        uint256 _drawInterval,
        uint256 _ticketsPerStake,
        uint256 _winnerCount
    ) external {
        require(_stakeToken != address(0), "Stake token cannot be zero address");
        require(_rewardToken != address(0), "Reward token cannot be zero address");
        require(_startTime >= block.timestamp, "Start time must be in the future");
        require(_endTime > _startTime, "End time must be after start time");
        require(_depositFee <= 1000, "Deposit fee cannot be more than 10%");
        require(_withdrawFee <= 1000, "Withdraw fee cannot be more than 10%");
        require(_rewardPerSecond > 0, "Reward per second must be positive");
        require(_minStakeAmount > 0, "Min stake amount must be positive");
        require(_drawInterval > 0, "Draw interval must be positive");
        require(_ticketsPerStake > 0, "Tickets per stake must be positive");
        require(_winnerCount > 0, "Winner count must be positive");
        
        // Set default draw interval if not specified
        uint256 drawInterval = _drawInterval > 0 ? _drawInterval : DEFAULT_DRAW_INTERVAL;
        
        // Create new farm
        farms.push(
            Farm({
                stakeToken: _stakeToken,
                rewardToken: _rewardToken,
                rewardPerSecond: _rewardPerSecond,
                startTime: _startTime,
                endTime: _endTime,
                lastRewardTime: _startTime,
                accRewardPerShare: 0,
                totalStaked: 0,
                lockDuration: _lockDuration,
                depositFee: _depositFee,
                withdrawFee: _withdrawFee,
                minStakeAmount: _minStakeAmount,
                maxStakeAmount: _maxStakeAmount,
                paused: false,
                active: true,
                drawInterval: drawInterval,
                ticketsPerStake: _ticketsPerStake,
                winnerCount: _winnerCount,
                lastDrawTime: _startTime,
                prizePool: 0,
                currentWinners: new address[](0)
            })
        );
        
        uint256 farmId = farms.length - 1;
        emit FarmCreated(farmId, _stakeToken, _rewardToken);
    }

    /**
     * @dev Stake tokens in a farm
     * @param _farmId Farm ID
     * @param _amount Amount to stake
     */
    function stake(uint256 _farmId, uint256 _amount) external nonReentrant {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        require(farm.active, "Farm is not active");
        require(!farm.paused, "Farm is paused");
        require(block.timestamp >= farm.startTime, "Farm has not started yet");
        require(block.timestamp < farm.endTime, "Farm has ended");
        require(_amount >= farm.minStakeAmount, "Amount less than minimum stake");
        
        if (farm.maxStakeAmount > 0) {
            require(_amount <= farm.maxStakeAmount, "Amount more than maximum stake");
        }
        
        // Update the farm
        updateFarm(_farmId);
        
        // Get user info
        UserInfo storage user = userInfo[_farmId][msg.sender];
        
        // Transfer tokens
        IERC20(farm.stakeToken).safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        
        // Calculate deposit fee
        uint256 depositFee = _amount.mul(farm.depositFee).div(10000);
        uint256 amountAfterFee = _amount.sub(depositFee);
        
        // Transfer fee to fee receiver if applicable
        if (depositFee > 0) {
            IERC20(farm.stakeToken).safeTransfer(feeReceiver, depositFee);
        }
        
        // Update user info
        if (user.amount == 0) {
            // First time staking
            user.stakeTime = block.timestamp;
            user.unlockTime = block.timestamp.add(farm.lockDuration);
            
            // Add user to participants list
            participants[_farmId].push(msg.sender);
        }
        
        // Calculate new ticket count for user
        uint256 newTickets = calculateTickets(farm.ticketsPerStake, amountAfterFee, farm.lockDuration);
        user.ticketCount = user.ticketCount.add(newTickets);
        userTicketsMap[_farmId][msg.sender] = user.ticketCount;
        totalTickets[_farmId] = totalTickets[_farmId].add(newTickets);
        
        // Update user amount and reward debt
        user.amount = user.amount.add(amountAfterFee);
        user.rewardDebt = user.amount.mul(farm.accRewardPerShare).div(PRECISION_FACTOR);
        
        // Update farm total staked
        farm.totalStaked = farm.totalStaked.add(amountAfterFee);
        
        // Add to prize pool (50% of staking amount goes to prize pool)
        uint256 prizeContribution = amountAfterFee.mul(50).div(100);
        farm.prizePool = farm.prizePool.add(prizeContribution);
        
        emit Deposit(msg.sender, _farmId, amountAfterFee);
    }

    /**
     * @dev Calculate tickets based on amount and duration
     * @param _ticketsPerStake Tickets per token per day
     * @param _amount Amount staked
     * @param _lockDuration Lock duration in seconds
     * @return Number of tickets
     */
    function calculateTickets(
        uint256 _ticketsPerStake,
        uint256 _amount,
        uint256 _lockDuration
    ) internal pure returns (uint256) {
        uint256 daysLocked = _lockDuration.div(SECONDS_PER_DAY);
        if (daysLocked == 0) daysLocked = 1; // Minimum 1 day even for no lock
        
        // Calculate tickets: amount * ticketsPerStake * daysLocked / 1e18
        return _amount.mul(_ticketsPerStake).mul(daysLocked).div(PRECISION_FACTOR);
    }

    /**
     * @dev Withdraw tokens from a farm
     * @param _farmId Farm ID
     * @param _amount Amount to withdraw
     */
    function withdraw(uint256 _farmId, uint256 _amount) external nonReentrant {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        UserInfo storage user = userInfo[_farmId][msg.sender];
        require(user.amount >= _amount, "Withdraw amount exceeds balance");
        require(block.timestamp >= user.unlockTime, "Tokens are still locked");
        
        // Update the farm
        updateFarm(_farmId);
        
        // Calculate pending reward
        uint256 userPendingReward = user.amount.mul(farm.accRewardPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
        
        // Update user info
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(farm.accRewardPerShare).div(PRECISION_FACTOR);
        
        // Calculate withdraw fee
        uint256 withdrawFee = _amount.mul(farm.withdrawFee).div(10000);
        uint256 amountAfterFee = _amount.sub(withdrawFee);
        
        // Transfer fee to fee receiver if applicable
        if (withdrawFee > 0) {
            IERC20(farm.stakeToken).safeTransfer(feeReceiver, withdrawFee);
        }
        
        // Transfer tokens back to user
        IERC20(farm.stakeToken).safeTransfer(address(msg.sender), amountAfterFee);
        
        // Transfer pending reward to user
        if (userPendingReward > 0) {
            IERC20(farm.rewardToken).safeTransfer(address(msg.sender), userPendingReward);
        }
        
        // Update farm total staked
        farm.totalStaked = farm.totalStaked.sub(_amount);
        
        emit Withdraw(msg.sender, _farmId, amountAfterFee);
    }

    /**
     * @dev Perform lottery draw for a farm
     * @param _farmId Farm ID
     */
    function performDraw(uint256 _farmId) external nonReentrant {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        require(farm.active, "Farm is not active");
        require(!farm.paused, "Farm is paused");
        require(
            block.timestamp >= farm.lastDrawTime.add(farm.drawInterval),
            "Not time for draw yet"
        );
        require(totalTickets[_farmId] > 0, "No tickets in the pool");
        
        // Get the prize amount (half the prize pool)
        uint256 prizeAmount = farm.prizePool.div(2);
        
        // Select winners
        address[] memory winners = selectWinners(_farmId, farm.winnerCount);
        farm.currentWinners = winners;
        
        // Update farm state
        farm.lastDrawTime = block.timestamp;
        farm.prizePool = farm.prizePool.sub(prizeAmount);
        
        emit LotteryDrawPerformed(_farmId, winners, prizeAmount);
    }

    /**
     * @dev Select winners randomly for a draw
     * @param _farmId Farm ID
     * @param _winnerCount Number of winners to select
     * @return Array of winner addresses
     */
    function selectWinners(uint256 _farmId, uint256 _winnerCount) internal view returns (address[] memory) {
        // Make sure we don't try to select more winners than participants
        uint256 participantCount = participants[_farmId].length;
        uint256 actualWinnerCount = _winnerCount > participantCount ? participantCount : _winnerCount;
        
        address[] memory winners = new address[](actualWinnerCount);
        uint256[] memory selectedIndices = new uint256[](participantCount);
        
        // Initialize array with sequential indices
        for (uint256 i = 0; i < participantCount; i++) {
            selectedIndices[i] = i;
        }
        
        // Select winners using Fisher-Yates shuffle algorithm
        uint256 ticketTotal = totalTickets[_farmId];
        
        for (uint256 i = 0; i < actualWinnerCount; i++) {
            // Generate random index
            uint256 randomIndex = uint256(keccak256(abi.encodePacked(
                block.timestamp,
                block.prevrandao,
                msg.sender,
                i
            ))) % (participantCount - i);
            
            // Get the participant at the random index
            address selected = participants[_farmId][selectedIndices[randomIndex]];
            
            // Adjust selection probability based on ticket count
            uint256 userTickets = userTicketsMap[_farmId][selected];
            uint256 probability = userTickets.mul(PRECISION_FACTOR).div(ticketTotal);
            
            // Roll for selection
            uint256 roll = uint256(keccak256(abi.encodePacked(
                block.timestamp,
                block.prevrandao,
                selected,
                i
            ))) % PRECISION_FACTOR;
            
            if (roll < probability) {
                // Selected!
                winners[i] = selected;
            } else {
                // Try next highest ticket holder
                uint256 maxTickets = 0;
                address maxTicketHolder = address(0);
                
                for (uint256 j = 0; j < participantCount; j++) {
                    address participant = participants[_farmId][j];
                    uint256 participantTickets = userTicketsMap[_farmId][participant];
                    
                    // Skip already selected winners
                    bool alreadySelected = false;
                    for (uint256 k = 0; k < i; k++) {
                        if (winners[k] == participant) {
                            alreadySelected = true;
                            break;
                        }
                    }
                    
                    if (!alreadySelected && participantTickets > maxTickets) {
                        maxTickets = participantTickets;
                        maxTicketHolder = participant;
                    }
                }
                
                winners[i] = maxTicketHolder;
            }
            
            // Swap the used index to the end to avoid reselection
            selectedIndices[randomIndex] = selectedIndices[participantCount - i - 1];
        }
        
        return winners;
    }

    /**
     * @dev Claim lottery prize
     * @param _farmId Farm ID
     */
    function claimPrize(uint256 _farmId) external nonReentrant {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        // Check if caller is a winner
        bool isWinner = false;
        for (uint256 i = 0; i < farm.currentWinners.length; i++) {
            if (farm.currentWinners[i] == msg.sender) {
                isWinner = true;
                break;
            }
        }
        
        require(isWinner, "Not a winner");
        
        UserInfo storage user = userInfo[_farmId][msg.sender];
        require(!user.hasClaimed, "Already claimed prize");
        
        // Calculate prize amount (split evenly among winners)
        uint256 prizeAmount = farm.prizePool.div(farm.currentWinners.length);
        
        // Mark as claimed
        user.hasClaimed = true;
        
        // Transfer prize
        IERC20(farm.rewardToken).safeTransfer(msg.sender, prizeAmount);
        
        emit PrizeClaimed(msg.sender, _farmId, prizeAmount);
    }

    /**
     * @dev Emergency withdraw without caring about rewards
     * @param _farmId Farm ID
     */
    function emergencyWithdraw(uint256 _farmId) external nonReentrant {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        UserInfo storage user = userInfo[_farmId][msg.sender];
        uint256 amount = user.amount;
        
        // Reset user info
        user.amount = 0;
        user.rewardDebt = 0;
        user.ticketCount = 0;
        userTicketsMap[_farmId][msg.sender] = 0;
        
        // Update total tickets
        totalTickets[_farmId] = totalTickets[_farmId] > user.ticketCount ? totalTickets[_farmId].sub(user.ticketCount) : 0;
        
        // Update farm total staked
        farm.totalStaked = farm.totalStaked > amount ? farm.totalStaked.sub(amount) : 0;
        
        // Transfer tokens back to user with emergency fee (higher than normal)
        uint256 emergencyFee = amount.mul(farm.withdrawFee.mul(2)).div(10000);
        uint256 amountAfterFee = amount.sub(emergencyFee);
        
        // Transfer fee to fee receiver if applicable
        if (emergencyFee > 0) {
            IERC20(farm.stakeToken).safeTransfer(feeReceiver, emergencyFee);
        }
        
        // Transfer tokens back to user
        IERC20(farm.stakeToken).safeTransfer(address(msg.sender), amountAfterFee);
        
        emit EmergencyWithdraw(msg.sender, _farmId, amountAfterFee);
    }

    /**
     * @dev Update farm rewards
     * @param _farmId Farm ID
     */
    function updateFarm(uint256 _farmId) public {
        Farm storage farm = farms[_farmId];
        
        if (block.timestamp <= farm.lastRewardTime) {
            return;
        }
        
        if (farm.totalStaked == 0) {
            farm.lastRewardTime = block.timestamp;
            return;
        }
        
        uint256 endTime = farm.endTime < block.timestamp ? farm.endTime : block.timestamp;
        uint256 timeElapsed = endTime.sub(farm.lastRewardTime);
        
        if (timeElapsed == 0) {
            return;
        }
        
        uint256 reward = timeElapsed.mul(farm.rewardPerSecond);
        farm.accRewardPerShare = farm.accRewardPerShare.add(
            reward.mul(PRECISION_FACTOR).div(farm.totalStaked)
        );
        farm.lastRewardTime = block.timestamp;
    }

    /**
     * @dev Update farm parameters
     * @param _farmId Farm ID
     * @param _rewardPerSecond New reward per second
     * @param _lockDuration New lock duration
     * @param _depositFee New deposit fee
     * @param _withdrawFee New withdraw fee
     * @param _minStakeAmount New minimum stake amount
     * @param _maxStakeAmount New maximum stake amount
     * @param _drawInterval New draw interval
     * @param _ticketsPerStake New tickets per stake
     * @param _winnerCount New winner count
     */
    function updateFarmParams(
        uint256 _farmId,
        uint256 _rewardPerSecond,
        uint256 _lockDuration,
        uint256 _depositFee,
        uint256 _withdrawFee,
        uint256 _minStakeAmount,
        uint256 _maxStakeAmount,
        uint256 _drawInterval,
        uint256 _ticketsPerStake,
        uint256 _winnerCount
    ) external onlyOwner {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        
        require(_depositFee <= 1000, "Deposit fee cannot be more than 10%");
        require(_withdrawFee <= 1000, "Withdraw fee cannot be more than 10%");
        
        // Update the farm
        updateFarm(_farmId);
        
        // Update farm parameters
        farm.rewardPerSecond = _rewardPerSecond;
        farm.lockDuration = _lockDuration;
        farm.depositFee = _depositFee;
        farm.withdrawFee = _withdrawFee;
        farm.minStakeAmount = _minStakeAmount;
        farm.maxStakeAmount = _maxStakeAmount;
        farm.drawInterval = _drawInterval;
        farm.ticketsPerStake = _ticketsPerStake;
        farm.winnerCount = _winnerCount;
        
        emit FarmUpdated(_farmId);
    }

    /**
     * @dev Pause farm
     * @param _farmId Farm ID
     * @param _paused Pause state
     */
    function pauseFarm(uint256 _farmId, bool _paused) external onlyOwner {
        require(_farmId < farms.length, "Farm does not exist");
        farms[_farmId].paused = _paused;
    }

    /**
     * @dev Set farm active status
     * @param _farmId Farm ID
     * @param _active Active state
     */
    function setFarmActive(uint256 _farmId, bool _active) external onlyOwner {
        require(_farmId < farms.length, "Farm does not exist");
        farms[_farmId].active = _active;
    }

    /**
     * @dev Set fee receiver
     * @param _feeReceiver Fee receiver address
     */
    function setFeeReceiver(address _feeReceiver) external onlyOwner {
        require(_feeReceiver != address(0), "Fee receiver cannot be zero address");
        feeReceiver = _feeReceiver;
    }

    /**
     * @dev Get farm count
     * @return Farm count
     */
    function getFarmCount() external view returns (uint256) {
        return farms.length;
    }

    /**
     * @dev Get active farms
     * @return Array of active farm IDs
     */
    function getActiveFarms() external view returns (uint256[] memory) {
        uint256 count = 0;
        
        // Count active farms
        for (uint256 i = 0; i < farms.length; i++) {
            if (farms[i].active) {
                count++;
            }
        }
        
        // Create array of active farm IDs
        uint256[] memory activeFarms = new uint256[](count);
        uint256 index = 0;
        
        for (uint256 i = 0; i < farms.length; i++) {
            if (farms[i].active) {
                activeFarms[index] = i;
                index++;
            }
        }
        
        return activeFarms;
    }

    /**
     * @dev Get pending reward for a user
     * @param _farmId Farm ID
     * @param _user User address
     * @return Pending reward
     */
    function pendingReward(uint256 _farmId, address _user) external view returns (uint256) {
        require(_farmId < farms.length, "Farm does not exist");
        Farm storage farm = farms[_farmId];
        UserInfo storage user = userInfo[_farmId][_user];
        
        uint256 accRewardPerShare = farm.accRewardPerShare;
        
        if (block.timestamp > farm.lastRewardTime && farm.totalStaked > 0) {
            uint256 endTime = farm.endTime < block.timestamp ? farm.endTime : block.timestamp;
            uint256 timeElapsed = endTime.sub(farm.lastRewardTime);
            uint256 reward = timeElapsed.mul(farm.rewardPerSecond);
            accRewardPerShare = accRewardPerShare.add(
                reward.mul(PRECISION_FACTOR).div(farm.totalStaked)
            );
        }
        
        return user.amount.mul(accRewardPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
    }

    /**
     * @dev Get prize pool for a farm
     * @param _farmId Farm ID
     * @return Prize pool amount
     */
    function getPrizePool(uint256 _farmId) external view returns (uint256) {
        require(_farmId < farms.length, "Farm does not exist");
        return farms[_farmId].prizePool;
    }

    /**
     * @dev Get last draw time for a farm
     * @param _farmId Farm ID
     * @return Last draw time
     */
    function getLastDrawTime(uint256 _farmId) external view returns (uint256) {
        require(_farmId < farms.length, "Farm does not exist");
        return farms[_farmId].lastDrawTime;
    }

    /**
     * @dev Get total tickets for a farm
     * @param _farmId Farm ID
     * @return Total tickets
     */
    function getTotalTickets(uint256 _farmId) external view returns (uint256) {
        require(_farmId < farms.length, "Farm does not exist");
        return totalTickets[_farmId];
    }

    /**
     * @dev Get user tickets for a farm
     * @param _farmId Farm ID
     * @param _user User address
     * @return User tickets
     */
    function getUserTickets(uint256 _farmId, address _user) external view returns (uint256) {
        require(_farmId < farms.length, "Farm does not exist");
        return userTicketsMap[_farmId][_user];
    }

    /**
     * @dev Get current winners for a farm
     * @param _farmId Farm ID
     * @return Array of winner addresses
     */
    function getCurrentWinners(uint256 _farmId) external view returns (address[] memory) {
        require(_farmId < farms.length, "Farm does not exist");
        return farms[_farmId].currentWinners;
    }

    /**
     * @dev Get farm by ID
     * @param _farmId Farm ID
     * @return Farm details
     */
    function getFarm(uint256 _farmId) external view returns (Farm memory) {
        require(_farmId < farms.length, "Farm does not exist");
        return farms[_farmId];
    }

    /**
     * @dev Get user info for a farm
     * @param _farmId Farm ID
     * @param _user User address
     * @return User info
     */
    function getUserInfo(uint256 _farmId, address _user) external view returns (UserInfo memory) {
        require(_farmId < farms.length, "Farm does not exist");
        return userInfo[_farmId][_user];
    }

    /**
     * @dev Get participants for a farm
     * @param _farmId Farm ID
     * @return Array of participant addresses
     */
    function getParticipants(uint256 _farmId) external view returns (address[] memory) {
        require(_farmId < farms.length, "Farm does not exist");
        return participants[_farmId];
    }

    /**
     * @dev Recover wrong tokens sent to the contract
     * @param _token Token address
     * @param _amount Amount to recover
     */
    function recoverWrongTokens(address _token, uint256 _amount) external onlyOwner {
        IERC20(_token).safeTransfer(address(msg.sender), _amount);
    }
} 

Read Contract

DEFAULT_DRAW_INTERVAL 0xb6b2a7a5 → uint256
PRECISION_FACTOR 0xccd34cd5 → uint256
SECONDS_PER_DAY 0x74f0314f → uint256
farms 0x7da470ea → address, address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool, uint256, uint256, uint256, uint256, uint256
feeReceiver 0xb3f00674 → address
getActiveFarms 0x0e093430 → uint256[]
getCurrentWinners 0x9622aaa4 → address[]
getFarm 0x53fd88bf → tuple
getFarmCount 0x429692a7 → uint256
getLastDrawTime 0xa98b3a6d → uint256
getParticipants 0xc1e3bd3e → address[]
getPrizePool 0x7822be4a → uint256
getTotalTickets 0x18906287 → uint256
getUserInfo 0x1069f3b5 → tuple
getUserTickets 0xe7a7f65c → uint256
owner 0x8da5cb5b → address
participants 0x81fb1fb4 → address
pendingReward 0x98969e82 → uint256
totalTickets 0x8385eae0 → uint256
userInfo 0x93f1a40b → uint256, uint256, uint256, uint256, uint256, bool, bool
userTicketsMap 0x6c106f2e → uint256

Write Contract 14 functions

These functions modify contract state and require a wallet transaction to execute.

claimPrize 0xd7098154
uint256 _farmId
createFarm 0xebf5cd5b
address _stakeToken
address _rewardToken
uint256 _rewardPerSecond
uint256 _startTime
uint256 _endTime
uint256 _lockDuration
uint256 _depositFee
uint256 _withdrawFee
uint256 _minStakeAmount
uint256 _maxStakeAmount
uint256 _drawInterval
uint256 _ticketsPerStake
uint256 _winnerCount
emergencyWithdraw 0x5312ea8e
uint256 _farmId
pauseFarm 0x3a5d5982
uint256 _farmId
bool _paused
performDraw 0x66d0d269
uint256 _farmId
recoverWrongTokens 0x3f138d4b
address _token
uint256 _amount
renounceOwnership 0x715018a6
No parameters
setFarmActive 0x60f13b3f
uint256 _farmId
bool _active
setFeeReceiver 0xefdcd974
address _feeReceiver
stake 0x7b0472f0
uint256 _farmId
uint256 _amount
transferOwnership 0xf2fde38b
address newOwner
updateFarm 0xcc430ced
uint256 _farmId
updateFarmParams 0x978bfab0
uint256 _farmId
uint256 _rewardPerSecond
uint256 _lockDuration
uint256 _depositFee
uint256 _withdrawFee
uint256 _minStakeAmount
uint256 _maxStakeAmount
uint256 _drawInterval
uint256 _ticketsPerStake
uint256 _winnerCount
withdraw 0x441a3e70
uint256 _farmId
uint256 _amount

Recent Transactions

No transactions found for this address