Address Contract Verified
Address
0x2E98c7181F2Ea81926734e19a02BF6f708764B69
Balance
0 ETH
Nonce
1
Code Size
16113 bytes
Creator
0xc570F1B8...C6f2 at tx 0xeb0d96ba...37f0e9
Indexed Transactions
0
Contract Bytecode
16113 bytes
0x6080806040526004361015610012575f80fd5b5f905f3560e01c90816301ffc9a714612ef857508063041d443e14612ebe578063079fe40e14612e9857806311bccc8414612e5c5780631fe543e314612db957806322dcd13e14612d9c57806323972aef14612cb1578063248a9ca314612c7e57806324c88a7014612c465780632f2ff15d14612b6a5780632fce844614612b40578063313ce56714612b03578063325fd7e914612abe578063330a308f1461270757806336568abe146126665780633998a6811461264a5780633b7ed7341461260a5780633f4ba83a1461256f57806354fd4d50146125105780635c975abb146124ee57806366c74034146123e557806367f082b0146123ca5780636f4f28371461235757806372cf6e341461233c57806373bd45001461230257806375d0c0dc146122a357806379ba5097146121b557806381eff7901461219957806382e0f38d146120945780638456cb591461203c5780638910ce0b146120225780638bcb9cf914611f115780638da5cb5b14611ee85780638db1afb114611e005780638ea9811714611cfe5780639010d07c14611cca57806391d1485414611c8057806394751f9e14611bda57806398d7113814611b5c5780639eccacf614611b36578063a217fddf14611b1c578063a54c120c14611aff578063b24451241461188e578063bf1e4ad01461184a578063c1c9d95314611783578063c1e3bd3e146116e0578063c9c35826146116a5578063ca15c8731461167b578063cadefed31461162e578063ce148e3d146114f1578063d1cfcd0d1461146f578063d45573f614611436578063d51075c1146113df578063d547741f14611398578063d70981541461126d578063dbff4e301461122a578063e2ba58d41461120b578063e4dafec914611050578063e8ac90de1461055b578063eb13554f14610534578063ec474191146104ee578063ed647d21146104b3578063f2fde38b146103b0578063f63074a114610392578063f7da5ef714610368578063fb14ea64146103245763fbf14086146102ff575f80fd5b346103215780600319360112610321576020604051670de0b6b3a76400008152f35b80fd5b503461032157806003193601126103215760206040516001600160a01b037f00000000000000000000000056b74759b9c5e2415a1dc73c261d79fc4acc79ce168152f35b50346103215760203660031901126103215760406020916004358152600a83522054604051908152f35b503461032157806003193601126103215760206040516207a1208152f35b5034610321576020366003190112610321576103ca612ff1565b6001600160a01b0360015460081c169081330361046f576001600160a01b03169033821461042b57816001600160a01b031960025416176002557fed8889f560326eb138920d842192f0eb3dd22b4f139c87a2c57538e05bae12788380a380f35b606460405162461bcd60e51b815260206004820152601760248201527f43616e6e6f74207472616e7366657220746f2073656c660000000000000000006044820152fd5b606460405162461bcd60e51b815260206004820152601660248201527f4f6e6c792063616c6c61626c65206279206f776e6572000000000000000000006044820152fd5b503461032157806003193601126103215760206040517f8daeab030adbfe0a5e9b6dd23a1c298a598e75269eced97b13136690e45a55f08152f35b5034610321576040366003190112610321576001600160a01b036040610512613007565b92600435815260086020522091165f52602052602060405f2054604051908152f35b503461032157806003193601126103215760206001600160a01b03600e5416604051908152f35b50346103215760203660031901126103215760043567ffffffffffffffff811161104c57806004016101606003198336030112611048577f186b684b5b4a3fd78fe68f385d558ec599346451ea9615d30d7820029c6f15c483526004602052604083206001600160a01b0333165f5260205260ff60405f20541615610f65576105e261364d565b6105ec8180613468565b905015610f3d5760448201916106028383613468565b905015610f155760c481013591670de0b6b3a76400008310610f065760e48201359182158015610efa575b610eeb5761012481013593610e104201804211610ed757851115610ec8576301e133804201804211610ed7578511610ec8576101048201359480861015610eb95760065495868952600760205260408920976106898680613468565b9067ffffffffffffffff8211610ac65781906106a58c54613390565b601f8111610e66575b508c908d601f8411600114610e015792610df6575b50508160011b915f199060031b1c19161789555b6106e46024860187613468565b60018b939293019067ffffffffffffffff8111610de2576107058254613390565b8d601f8211610d99575b9050938d601f8311600114610d2e5761074495909183610d23575b50508160011b915f199060031b1c19161790555b86613468565b60028a019167ffffffffffffffff8211610ac65781906107648454613390565b601f8111610cd0575b508c908d601f8411600114610c6b5792610c60575b50508160011b915f199060031b1c19161790555b6107a36064850186613468565b60038a019167ffffffffffffffff8211610ac65781906107c38454613390565b601f8111610c0d575b508c908d601f8411600114610ba85792610b9d575b50508160011b915f199060031b1c19161790555b6108026084850186613468565b60048a019167ffffffffffffffff8211610ac65781906108228454613390565b601f8111610b4a575b508c908d601f8411600114610ae55792610ada575b50508160011b915f199060031b1c19161790555b61086160a4850186613468565b60058a019167ffffffffffffffff8211610ac65781906108818454613390565b601f8111610a73575b508c908d601f8411600114610a0e5792610a03575b50508160011b915f199060031b1c19161790555b826009890155600b8801946101448654950135918215158093036109ff576001998997600160b81b6109b89576ff0000000000000000000000000000000000000000000060ff60b81b1960089667ffffffffffffffff8f7fde408bb31867d871f295687c66f36421badf16940f6e31d50cf6f217bd4ecf4d9e6001600160a01b031973ffffffff000000000000000000000000000000007fffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffffff9360801b1691161716911617166fffffffffffffffff00000000000000008a60401b16179160b01b1617179055016001600160a01b0333166001600160a01b031982541617905580613468565b95909286604051946080865281608087015260a08601378960a0888601015260208401526040830152606082015260a0813395601f80199101168101030190a30160065580f35b8a80fd5b013590505f8061089f565b925090601f19841685845260208420935b818110610a5b5750908460019594939210610a42575b505050811b0190556108b3565b01355f19600384901b60f8161c191690555f8080610a35565b91936020600181928787013581550195019201610a1f565b909150838d5260208d20601f840160051c81019160208510610abc575b849392918f91601f0160051c0191905b828210610aae57505061088a565b81558493506001018e610aa0565b9091508190610a90565b60248c634e487b7160e01b81526041600452fd5b013590505f80610840565b925090601f19841685845260208420935b818110610b325750908460019594939210610b19575b505050811b019055610854565b01355f19600384901b60f8161c191690555f8080610b0c565b91936020600181928787013581550195019201610af6565b909150838d5260208d20601f840160051c81019160208510610b93575b849392918f91601f0160051c0191905b828210610b8557505061082b565b81558493506001018e610b77565b9091508190610b67565b013590505f806107e1565b925090601f19841685845260208420935b818110610bf55750908460019594939210610bdc575b505050811b0190556107f5565b01355f19600384901b60f8161c191690555f8080610bcf565b91936020600181928787013581550195019201610bb9565b909150838d5260208d20601f840160051c81019160208510610c56575b849392918f91601f0160051c0191905b828210610c485750506107cc565b81558493506001018e610c3a565b9091508190610c2a565b013590505f80610782565b925090601f19841685845260208420935b818110610cb85750908460019594939210610c9f575b505050811b019055610796565b01355f19600384901b60f8161c191690555f8080610c92565b91936020600181928787013581550195019201610c7c565b909150838d5260208d20601f840160051c81019160208510610d19575b849392918f91601f0160051c0191905b828210610d0b57505061076d565b81558493506001018e610cfd565b9091508190610ced565b013590505f8061072a565b91929394601f19841685845260208420935b818110610d8157509160019391856107449897969410610d68575b505050811b01905561073e565b01355f19600384901b60f8161c191690555f8080610d5b565b91936020600181928787013581550195019201610d40565b80846020925220601f830160051c81019160208410610dd8575b601f0160051c01908e905b828110610dcb575061070f565b9081558e90600101610dbe565b9091508190610db3565b60248d634e487b7160e01b81526041600452fd5b013590505f806106c3565b925090601f1984168d845260208420935b818110610e4e5750908460019594939210610e35575b505050811b0189556106d7565b01355f19600384901b60f8161c191690555f8080610e28565b91936020600181928787013581550195019201610e12565b9091508b8d5260208d20601f840160051c81019160208510610eaf575b849392918f91601f0160051c0191905b828210610ea15750506106ae565b81558493506001018e610e93565b9091508190610e83565b60048863536a71af60e01b8152fd5b60048763536a71af60e01b8152fd5b602488634e487b7160e01b81526011600452fd5b60048663162908e360e11b8152fd5b506207a120831161062d565b60048563162908e360e11b8152fd5b6004847fa0f47550000000000000000000000000000000000000000000000000000000008152fd5b6004837f1ff3ed9d000000000000000000000000000000000000000000000000000000008152fd5b6110446020611024601186610f7933613bfb565b90603785610fa67f186b684b5b4a3fd78fe68f385d558ec599346451ea9615d30d7820029c6f15c4613cee565b6040519788957f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000828801528051918291018588015e8501907f206973206d697373696e6720726f6c652000000000000000000000000000000084830152805192839101604883015e010190838201520301601f19810183528261312c565b60405191829162461bcd60e51b835260206004840152602483019061301d565b0390fd5b8280fd5b5080fd5b5034610321576020366003190112610321576004356006548110156111fc5781526007602052604090206009810154600b82015460078301546001600160a01b03169060068401549060088501546001600160a01b0316916110b1866133c8565b946110be600188016133c8565b966110cb600282016133c8565b916110d8600383016133c8565b906110e5600484016133c8565b926005016110f2906133c8565b936040519a8b9a6102408c526102408c0161110c9161301d565b8b810360208d015261111d9161301d565b8a810360408c015261112e9161301d565b9060608a01528560801c63ffffffff1660808a015267ffffffffffffffff861660a08a01528560401c67ffffffffffffffff1660c08a01528560b01c60ff16151560e08a01528881036101008a01526111869161301d565b8781036101208901526111989161301d565b8681036101408801526111aa9161301d565b938260a01c60ff1615156101608701526101808601526101a08501528060b81c60ff1615156101c08501528060a81c60ff1615156101e085015260c01c60ff1615156102008401526102208301520390f35b60048263c57b876d60e01b8152fd5b503461032157806003193601126103215760206040516301e133808152f35b50346103215760203660031901126103215760043590600c548210156103215760206001600160a01b0361125d846130cb565b90549060031b1c16604051908152f35b5034610321576020366003190112610321576004356006548110156111fc576112946135fa565b808252600760205260408220600b81015460ff8160c01c166113895760a01c60ff1615611048576001600160a01b03600782015416330361136157600c016001600160a01b0333165f528060205260ff60405f205416611339576001600160a01b0333165f5260205260405f20600160ff1982541617905533907fbfb36529287d5a1dcbfbbc958f0a7337a1f5bca269edc737da0be1be702f22518380a36001815580f35b6004837fc2356312000000000000000000000000000000000000000000000000000000008152fd5b6004837f618c7242000000000000000000000000000000000000000000000000000000008152fd5b600484630e0b363d60e41b8152fd5b5034610321576040366003190112610321576113dc6004356113b8613007565b906113d76113d2825f526004602052600160405f20015490565b613af8565b613b43565b80f35b5034610321576040366003190112610321576113f9612ff1565b6001600160a01b031681526009602052604081208054602435929083101561032157602061142784846130f7565b90549060031b1c604051908152f35b5034610321578060031936011261032157600e54600f54604080516001600160a01b0390931683526020830191909152819081015b0390f35b5034610321576020366003190112610321576004356006548110156111fc5781604091606093526007602052206006810154600b6114b1600984015483613119565b9201549060ff8260a01c169182156114d9575b50604051928352602083015215156040820152f35b60401c67ffffffffffffffff1642101591505f6114c4565b50346103215760603660031901126103215761150b612ff1565b604435906001600160a01b0382169081830361162a5761153c6001600160a01b0392611535613aa1565b151561316a565b166001600160a01b037f00000000000000000000000056b74759b9c5e2415a1dc73c261d79fc4acc79ce1681146115e65760405163a9059cbb60e01b81526001600160a01b0392909216600483015260248035908301526020908290604490829086905af180156115db576115af575080f35b6115d09060203d6020116115d4575b6115c8818361312c565b810190613378565b5080f35b503d6115be565b6040513d84823e3d90fd5b606460405162461bcd60e51b815260206004820152601a60248201527f43616e6e6f74207265636f766572204e414e4120746f6b656e730000000000006044820152fd5b8380fd5b5034610321576060366003190112610321576004359060065482101561166c5761146b611660604435602435856132c3565b60405191829182613089565b8063c57b876d60e01b60049252fd5b50346103215760203660031901126103215760406020916004358152600583522054604051908152f35b503461032157806003193601126103215760206040517f186b684b5b4a3fd78fe68f385d558ec599346451ea9615d30d7820029c6f15c48152f35b5034610321576020366003190112610321576004356006548110156111fc57808252600760205260ff600b60408420015460c01c16611774578152600760205260066040822001604051918260208354918281520192825260208220915b8181106117555761146b856116608187038261312c565b82546001600160a01b031684526020909301926001928301920161173e565b600482630e0b363d60e41b8152fd5b5034610321576020366003190112610321576004356117a06139ac565b6006548110156111fc578082526007602052600b6040832001805460ff8160c01c16156118065761ffff60b81b19600160b81b91161790557f24c40b40784710f6a31393c3661c4537875b1183c1014c85d59a4561a739c75d602060405160018152a280f35b606460405162461bcd60e51b815260206004820152601260248201527f526166666c65206e6f742064656c6574656400000000000000000000000000006044820152fd5b503461032157806003193601126103215760206040516001600160a01b037f00000000000000000000000056b74759b9c5e2415a1dc73c261d79fc4acc79ce168152f35b5034611a565760c0366003190112611a56576004356024359060643560ff8116809103611a56576118bd6135fa565b6118c561364d565b600654821015611af057815f526007602052600b60405f20015460ff8160c01c16611ae15760b81c60ff1615611ab957815f52600760205260405f20600b81015467ffffffffffffffff8160401c16421015611a91578415611a825763ffffffff61193486600685015461310c565b9160801c1610611a5a5783600961194c920154613119565b906001600160a01b037f00000000000000000000000056b74759b9c5e2415a1dc73c261d79fc4acc79ce1690813b15611a56575f9160e4839260405194859384927fd505accf0000000000000000000000000000000000000000000000000000000084523360048501523060248501528860448501526044356064850152608484015260843560a484015260a43560c48401525af18015611a4b57611a34575b506119f69061369d565b611a0182338361389f565b6040519182527fd0dd2854ead3f00ed4d2a97d8efad0e6b6b93f2cdafa6da62bf260033728e8eb60203393a36001815580f35b611a419194505f9061312c565b5f926119f66119ec565b6040513d5f823e3d90fd5b5f80fd5b7f88bd2941000000000000000000000000000000000000000000000000000000005f5260045ffd5b63162908e360e11b5f5260045ffd5b7f502fd88d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f2ae47f73000000000000000000000000000000000000000000000000000000005f5260045ffd5b630e0b363d60e41b5f5260045ffd5b63c57b876d60e01b5f5260045ffd5b34611a56575f366003190112611a56576020600654604051908152f35b34611a56575f366003190112611a565760206040515f8152f35b34611a56575f366003190112611a565760206001600160a01b0360035416604051908152f35b34611a56576020366003190112611a56576001600160a01b03611b7d612ff1565b165f52600960205260405f206040519081602082549182815201915f5260205f20905f5b818110611bc45761146b85611bb88187038261312c565b60405191829182613050565b8254845260209093019260019283019201611ba1565b34611a56576040366003190112611a5657600435611bf6613041565b611bfe6139ac565b600654821015611af057815f526007602052600b60405f20019060ff825460c01c16611ae1577f24c40b40784710f6a31393c3661c4537875b1183c1014c85d59a4561a739c75d91602091151590805460ff60b81b1977ff00000000000000000000000000000000000000000000008460b81b169116179055604051908152a2005b34611a56576040366003190112611a5657611c99613007565b6004355f5260046020526001600160a01b0360405f2091165f52602052602060ff60405f2054166040519015158152f35b34611a56576040366003190112611a56576004355f52600560205260206001600160a01b0361125d60243560405f206130f7565b34611a56576020366003190112611a5657611d17612ff1565b6001600160a01b0360015460081c16908133141580611deb575b611dab576001600160a01b03168015611d83576020817fd1a6a14209a385a964d036e404cb5cfb71f4000cdb03c9366292430787261be6926001600160a01b03196003541617600355604051908152a1005b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b506001600160a01b0360035416907f061db9c1000000000000000000000000000000000000000000000000000000005f523360045260245260445260645ffd5b506001600160a01b0360035416331415611d31565b34611a56576040366003190112611a5657611e19612ff1565b602435611e24613aa1565b6001600160a01b03821691611e3a83151561316a565b6103e88211611ea4577fd8149d5d7695ec014cad0238fa3120dfa5fa8330c3d19b451f2bdc7587f37d84926001600160a01b0319600e541617600e5581600f55611e9f60405192839283602090939291936001600160a01b0360408201951681520152565b0390a1005b606460405162461bcd60e51b815260206004820152600c60248201527f46656520746f6f206869676800000000000000000000000000000000000000006044820152fd5b34611a56575f366003190112611a565760206001600160a01b0360015460081c16604051908152f35b34611a56576040366003190112611a5657611f2a612ff1565b611f32613041565b600654611f3e816131cd565b925f926001600160a01b035f9216915b838110611f97578585611f60816131cd565b915f5b828110611f78576040518061146b8682613050565b80611f85600192846131ff565b51611f9082876131ff565b5201611f63565b805f52600760205260405f20836001600160a01b03600883015416149081611ffe575b50611fc8575b600101611f4e565b84905f198214611fea5780611fe2600180940197896131ff565b529050611fc0565b634e487b7160e01b5f52601160045260245ffd5b839150811561200f575b5087611fba565b60ff9150600b015460c01c161587612008565b34611a565761146b61166061203636612fdb565b90613220565b34611a56575f366003190112611a5657612054613aa1565b61205c61364d565b600160ff19815416176001557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b34611a56576040366003190112611a56576004358015158103611a56576120b9613041565b906006546120c6816131cd565b925f925f9115915b8381106121175785856120e0816131cd565b915f5b8281106120f8576040518061146b8682613050565b80612105600192846131ff565b5161211082876131ff565b52016120e3565b805f52600760205260405f20826001918580612188575b612180575b8161216d575b50612166575b61214c575b6001016120ce565b936001818661215c83948a6131ff565b5201949050612144565b505f61213f565b60ff9150600b015460b81c161588612139565b5f9250612133565b5060ff600b82015460c01c1661212e565b34611a56575f366003190112611a56576020604051610e108152f35b34611a56575f366003190112611a56576002546001600160a01b038116330361225f576001600160a01b03196001549174ffffffffffffffffffffffffffffffffffffffff003360081b167fffffffffffffffffffffff0000000000000000000000000000000000000000ff841617600155166002556001600160a01b03339160081c167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b606460405162461bcd60e51b815260206004820152601660248201527f4d7573742062652070726f706f736564206f776e6572000000000000000000006044820152fd5b34611a56575f366003190112611a565761146b6040516122c460408261312c565b600e81527f5472696265526166666c65735632000000000000000000000000000000000000602082015260405191829160208352602083019061301d565b34611a56575f366003190112611a565760206040517f5b4b8088d200445bfb44acef5ae68c0906d30def45a3f841c2e4c6f0a2b1e9148152f35b34611a56575f366003190112611a5657602060405160018152f35b34611a56576020366003190112611a56577f299d17e95023f496e0ffc4909cff1a61f74bb5eb18de6f900f4155bfa1b3b33360206001600160a01b0361239b612ff1565b6123a3613aa1565b166123af81151561316a565b806001600160a01b03196010541617601055604051908152a1005b34611a56575f366003190112611a5657602060405160028152f35b34611a56576020366003190112611a56576004356124016139ac565b600654811015611af057805f52600760205260405f20600b81019081549060ff8260a01c16159081156124c6575b50156124825761ffff60b81b1916780100000000000000000000000000000000000000000000000017905533907f8cdff5921279206684dbbd35fbeaef8aaff873c39399773df75ce32a75218e8f5f80a3005b606460405162461bcd60e51b815260206004820152601d60248201527f43616e6e6f742064656c65746520756e636c61696d6564207072697a650000006044820152fd5b600c91506001600160a01b0380600783015416165f520160205260ff60405f2054168461242f565b34611a56575f366003190112611a5657602060ff600154166040519015158152f35b34611a56575f366003190112611a565761146b60405161253160408261312c565b600581527f322e312e30000000000000000000000000000000000000000000000000000000602082015260405191829160208352602083019061301d565b34611a56575f366003190112611a5657612587613aa1565b60015460ff8116156125c65760ff19166001557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b606460405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f74207061757365640000000000000000000000006044820152fd5b34611a56575f366003190112611a5657602060405163ffffffff7f0000000000000000000000000000000000000000000000000000000000030d40168152f35b34611a56575f366003190112611a565760206040516103e88152f35b34611a56576040366003190112611a565761267f613007565b336001600160a01b0382160361269d5761269b90600435613b43565b005b608460405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c6600000000000000000000000000000000006064820152fd5b34611a56576020366003190112611a56576004356127236139ac565b600654811015611af057805f52600760205260405f2090600b8201805460ff8160c01c16611ae15767ffffffffffffffff8160401c164210612a965760ff8160a01c16612a6e5760ff8160a81c16612a4657600684015415612a1e5760ff8160b81c1615611ab9577fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff16750100000000000000000000000000000000000000000017905560035460405192906001600160a01b03166020840167ffffffffffffffff811185821017612a0a576040527f000000000000000000000000000000000000000000000000000000000000000115158452604051937f92fd133800000000000000000000000000000000000000000000000000000000602086015251151560248501526024845261285860448561312c565b6040519360c085019185831067ffffffffffffffff841117612a0a5761ffff956020936040527f787d74caea10b2b357790d5b5247c2f63d1d91572a9846f780606e4d953677ae81525f848201917f8daeab030adbfe0a5e9b6dd23a1c298a598e75269eced97b13136690e45a55f0835261297a60408201956002875263ffffffff60608401817f0000000000000000000000000000000000000000000000000000000000030d401681528160808601916001835260a087019485526040519e8f9b8c9a8b997f9b1c385e000000000000000000000000000000000000000000000000000000008b528f60048c01525160248b01525160448a01525116606488015251166084860152511660a48401525160c060c484015260e483019061301d565b03925af1928315611a4b575f936129d5575b50600a83910155815f52600a6020528060405f2055805f52600b6020528160405f20557f8c2dafc78f35b04e83725aad7a5993b7642b4229aef392ad4317c15d91b882b65f80a3005b92506020833d602011612a02575b816129f06020938361312c565b81010312611a5657600a92519261298c565b3d91506129e3565b634e487b7160e01b5f52604160045260245ffd5b7f95b0d1da000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fbf08457d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f0ee0b2ce000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fe94eb8ec000000000000000000000000000000000000000000000000000000005f5260045ffd5b34611a56576040366003190112611a5657612ad7613007565b6004355f5260086020526001600160a01b0360405f2091165f52602052602060405f2054604051908152f35b34611a56575f366003190112611a5657602060405160ff7f0000000000000000000000000000000000000000000000000000000000000012168152f35b34611a56576020366003190112611a56576004355f52600b602052602060405f2054604051908152f35b34611a56576040366003190112611a565761269b600435612b89613007565b90612ba36113d2825f526004602052600160405f20015490565b805f52600460205260405f206001600160a01b0383165f5260205260ff60405f20541615612be7575b5f5260056020526001600160a01b0360405f20911690613d9d565b805f52600460205260405f206001600160a01b0383165f5260205260405f20600160ff19825416179055336001600160a01b038316827f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d5f80a4612bcc565b34611a56576020366003190112611a56576001600160a01b03612c67612ff1565b165f52600d602052602060405f2054604051908152f35b34611a56576020366003190112611a56576020612ca96004355f526004602052600160405f20015490565b604051908152f35b34611a5657612cbf36612fdb565b90612cc86135fa565b612cd061364d565b600654811015611af057805f526007602052600b60405f20015460ff8160c01c16611ae15760b81c60ff1615611ab957805f52600760205260405f20600b81015467ffffffffffffffff8160401c16421015611a91578315611a825763ffffffff612d3f85600685015461310c565b9160801c1610611a5a57612d5a836009612d5f930154613119565b61369d565b612d6a82338361389f565b6040519182527fd0dd2854ead3f00ed4d2a97d8efad0e6b6b93f2cdafa6da62bf260033728e8eb60203393a360015f55005b34611a56575f366003190112611a56576020600f54604051908152f35b34611a56576040366003190112611a565760243567ffffffffffffffff8111611a565736602382011215611a5657806004013567ffffffffffffffff8111611a56573660248260051b84010111611a56576001600160a01b0360035416803303612e2d5750602461269b920160043561349b565b7f1cf993f4000000000000000000000000000000000000000000000000000000005f523360045260245260445ffd5b34611a56575f366003190112611a565760206040517f000000000000000000000000000000000000000000000000000000000000000115158152f35b34611a56575f366003190112611a565760206001600160a01b0360105416604051908152f35b34611a56575f366003190112611a565760206040517f787d74caea10b2b357790d5b5247c2f63d1d91572a9846f780606e4d953677ae8152f35b34611a56576020366003190112611a5657600435907fffffffff000000000000000000000000000000000000000000000000000000008216809203611a5657817f01ffc9a70000000000000000000000000000000000000000000000000000000060209314908115612f6c575b5015158152f35b907f5a05180f000000000000000000000000000000000000000000000000000000008214918215612fa0575b505083612f65565b7f7965db0b000000000000000000000000000000000000000000000000000000001491508115612fd3575b508380612f98565b905083612fcb565b6040906003190112611a56576004359060243590565b600435906001600160a01b0382168203611a5657565b602435906001600160a01b0382168203611a5657565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b602435908115158203611a5657565b60206040818301928281528451809452019201905f5b8181106130735750505090565b8251845260209384019390920191600101613066565b60206040818301928281528451809452019201905f5b8181106130ac5750505090565b82516001600160a01b031684526020938401939092019160010161309f565b600c548110156130e357600c5f5260205f2001905f90565b634e487b7160e01b5f52603260045260245ffd5b80548210156130e3575f5260205f2001905f90565b91908201809211611fea57565b81810292918115918404141715611fea57565b90601f8019910116810190811067ffffffffffffffff821117612a0a57604052565b67ffffffffffffffff8111612a0a57601f01601f191660200190565b1561317157565b606460405162461bcd60e51b815260206004820152601160248201527f496e76616c696420726563697069656e740000000000000000000000000000006044820152fd5b67ffffffffffffffff8111612a0a5760051b60200190565b906131d7826131b5565b6131e4604051918261312c565b82815280926131f5601f19916131b5565b0190602036910137565b80518210156130e35760209160051b010190565b91908203918211611fea57565b90600c5490818310156132a85781613238828561310c565b111561329857505b61325261324d8383613213565b6131cd565b91805b8281106132625750505090565b806001600160a01b036132766001936130cb565b90549060031b1c1661329161328b8584613213565b876131ff565b5201613255565b6132a391508261310c565b613240565b5050506040516132b960208261312c565b5f81525f36813790565b5f52600760205260405f2060ff600b82015460c01c16611ae157600601918254908183101561336657816132f7828561310c565b11156133555750905b61330d61324d8284613213565b92815b83811061331e575050505090565b806001600160a01b03613333600193856130f7565b90549060031b1c1661334e6133488684613213565b886131ff565b5201613310565b61336091508261310c565b90613300565b505050506040516132b960208261312c565b90816020910312611a5657518015158103611a565790565b90600182811c921680156133be575b60208310146133aa57565b634e487b7160e01b5f52602260045260245ffd5b91607f169161339f565b9060405191825f8254926133db84613390565b80845293600181169081156134465750600114613402575b506134009250038361312c565b565b90505f9291925260205f20905f915b81831061342a575050906020613400928201015f6133f3565b6020919350806001915483858901015201910190918492613411565b90506020925061340094915060ff191682840152151560051b8201015f6133f3565b903590601e1981360301821215611a56570180359067ffffffffffffffff8211611a5657602001918136038313611a5657565b9190915f52600a60205260405f205490815f52600760205260405f2092600b84019160ff835460a01c1680156135ee575b6135e757156130e357600684019081549081156135d3576007926001600160a01b03926134fb923506906130f7565b90549060031b1c1693016001600160a01b0384166001600160a01b0319825416179055740100000000000000000000000000000000000000007fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff825416179055600c5468010000000000000000811015612a0a578060016135819201600c55600c6130f7565b81549060031b906001600160a01b0385831b921b1916179055815f52600d60205260405f20600181540190557fa32be17495f4ca52a36e64b567f7ee15d108becc107da2b4fa1b755b50d86d045f80a3565b634e487b7160e01b5f52601260045260245ffd5b5050505050565b506006850154156134cc565b60025f54146136095760025f55565b606460405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152fd5b60ff6001541661365957565b606460405162461bcd60e51b815260206004820152601060248201527f5061757361626c653a20706175736564000000000000000000000000000000006044820152fd5b6127106136ac600f5483613119565b04906136b88282613213565b916001600160a01b037f00000000000000000000000056b74759b9c5e2415a1dc73c261d79fc4acc79ce1691604051907f23b872dd00000000000000000000000000000000000000000000000000000000825233600483015230602483015260448201526020816064815f875af1908115611a4b575f91613880575b50156137a6578015158061386c575b613801575b50811515806137ed575b61375a575050565b60105460405163a9059cbb60e01b81526001600160a01b0390911660048201526024810192909252602090829060449082905f905af1908115611a4b575f916137ce575b50156137a657565b7f90b8ec18000000000000000000000000000000000000000000000000000000005f5260045ffd5b6137e7915060203d6020116115d4576115c8818361312c565b5f61379e565b506001600160a01b03601054161515613752565b600e5460405163a9059cbb60e01b81526001600160a01b03909116600482015260248101919091526020816044815f865af1908115611a4b575f9161384d575b50156137a6575f613748565b613866915060203d6020116115d4576115c8818361312c565b5f613841565b506001600160a01b03600e54161515613743565b613899915060203d6020116115d4576115c8818361312c565b5f613734565b91825f52600760205260405f2060065f9101905b828110613966575050825f52600860205260405f206001600160a01b0383165f5260205260405f206138e682825461310c565b9055825f52600860205260405f206001600160a01b0383165f5260205260405f205414613911575050565b6001600160a01b03165f52600960205260405f2080549068010000000000000000821015612a0a578161394c916001613962940181556130f7565b819391549060031b91821b915f19901b19161790565b9055565b81549068010000000000000000821015612a0a5761398b8260018094018555846130f7565b81549060031b906001600160a01b03808916831b921b1916179055016138b3565b335f9081527f32615df824d18e40df3386b088be77f6bc88dac475c5a327c95c1c8f64f9dc85602052604090205460ff16156139e457565b611044602061102460116139f733613bfb565b603784613a237f5b4b8088d200445bfb44acef5ae68c0906d30def45a3f841c2e4c6f0a2b1e914613cee565b6040519687947f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000828701528051918291018587015e8401907f206973206d697373696e6720726f6c652000000000000000000000000000000084830152805192839101604883015e01015f838201520301601f19810183528261312c565b335f9081527f17ef568e3e12ab5b9c7254a8d58478811de00f9e6eb34345acd53bf8fd09d3ec602052604090205460ff1615613ad957565b61104460206110246011613aec33613bfb565b603784613a235f613cee565b805f52600460205260405f206001600160a01b0333165f5260205260ff60405f20541615613b235750565b6020611024601161104493603784613a23613b3d33613bfb565b93613cee565b90613b8b91805f52600460205260405f206001600160a01b0383165f5260205260ff60405f205416613b8e575b5f5260056020526001600160a01b0360405f20911690613df6565b50565b805f52600460205260405f206001600160a01b0383165f5260205260405f2060ff198154169055336001600160a01b038316827ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b5f80a4613b70565b9081518110156130e3570160200190565b613c05602a61314e565b90613c13604051928361312c565b602a8252613c21602a61314e565b6020830190601f19013682378251156130e357603090538151600110156130e3576078602183015360295b60018111613ca05750613c5c5790565b606460405162461bcd60e51b815260206004820152602060248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152fd5b90600f811660108110156130e3577f3031323334353637383961626364656600000000000000000000000000000000901a613cdb8385613bea565b5360041c908015611fea575f1901613c4c565b613cf8604261314e565b90613d06604051928361312c565b60428252613d14604261314e565b6020830190601f19013682378251156130e357603090538151600110156130e3576078602183015360415b60018111613d4f5750613c5c5790565b90600f811660108110156130e3577f3031323334353637383961626364656600000000000000000000000000000000901a613d8a8385613bea565b5360041c908015611fea575f1901613d3f565b6001810190825f528160205260405f2054155f14613def57805468010000000000000000811015612a0a57613ddc61394c8260018794018555846130f7565b905554915f5260205260405f2055600190565b5050505f90565b906001820191815f528260205260405f20548015155f14613eb3575f198101818111611fea5782545f19810191908211611fea57808203613e7e575b50505080548015613e6a575f190190613e4b82826130f7565b8154905f199060031b1b19169055555f526020525f6040812055600190565b634e487b7160e01b5f52603160045260245ffd5b613e9e613e8e61394c93866130f7565b90549060031b1c928392866130f7565b90555f528360205260405f20555f8080613e32565b505050505f9056fea26469706673582212206bf5416be48edd03c388b8bae535ab8fca2b4ee97a31da2bb457afd27683f23d64736f6c634300081e0033
Verified Source Code Full Match
Compiler: v0.8.30+commit.73712a01
EVM: cancun
Optimization: Yes (1000 runs)
ConfirmedOwner.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ConfirmedOwnerWithProposal} from "./ConfirmedOwnerWithProposal.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwner is ConfirmedOwnerWithProposal {
constructor(address newOwner) ConfirmedOwnerWithProposal(newOwner, address(0)) {}
}
ConfirmedOwnerWithProposal.sol 68 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IOwnable} from "../interfaces/IOwnable.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwnerWithProposal is IOwnable {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
constructor(address newOwner, address pendingOwner) {
// solhint-disable-next-line gas-custom-errors
require(newOwner != address(0), "Cannot set owner to zero");
s_owner = newOwner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/// @notice Allows an owner to begin transferring ownership to a new address.
function transferOwnership(address to) public override onlyOwner {
_transferOwnership(to);
}
/// @notice Allows an ownership transfer to be completed by the recipient.
function acceptOwnership() external override {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/// @notice Get the current owner
function owner() public view override returns (address) {
return s_owner;
}
/// @notice validate, transfer ownership, and emit relevant events
function _transferOwnership(address to) private {
// solhint-disable-next-line gas-custom-errors
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/// @notice validate access
function _validateOwnership() internal view {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_owner, "Only callable by owner");
}
/// @notice Reverts if called by anyone other than the contract owner.
modifier onlyOwner() {
_validateOwnership();
_;
}
}
IOwnable.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOwnable {
function owner() external returns (address);
function transferOwnership(address recipient) external;
function acceptOwnership() external;
}
VRFConsumerBaseV2Plus.sol 165 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {IVRFCoordinatorV2Plus} from "./interfaces/IVRFCoordinatorV2Plus.sol";
import {IVRFMigratableConsumerV2Plus} from "./interfaces/IVRFMigratableConsumerV2Plus.sol";
import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinatorV2Plus.
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBaseV2Plus, and can
* @dev initialize VRFConsumerBaseV2Plus's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumerV2Plus is VRFConsumerBaseV2Plus {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _subOwner)
* @dev VRFConsumerBaseV2Plus(_vrfCoordinator, _subOwner) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create a subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords, extraArgs),
* @dev see (IVRFCoordinatorV2Plus for a description of the arguments).
*
* @dev Once the VRFCoordinatorV2Plus has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBaseV2Plus.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2Plus is IVRFMigratableConsumerV2Plus, ConfirmedOwner {
error OnlyCoordinatorCanFulfill(address have, address want);
error OnlyOwnerOrCoordinator(address have, address owner, address coordinator);
error ZeroAddress();
// s_vrfCoordinator should be used by consumers to make requests to vrfCoordinator
// so that coordinator reference is updated after migration
IVRFCoordinatorV2Plus public s_vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) ConfirmedOwner(msg.sender) {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2Plus expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
// solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external {
if (msg.sender != address(s_vrfCoordinator)) {
revert OnlyCoordinatorCanFulfill(msg.sender, address(s_vrfCoordinator));
}
fulfillRandomWords(requestId, randomWords);
}
/**
* @inheritdoc IVRFMigratableConsumerV2Plus
*/
function setCoordinator(address _vrfCoordinator) external override onlyOwnerOrCoordinator {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
emit CoordinatorSet(_vrfCoordinator);
}
modifier onlyOwnerOrCoordinator() {
if (msg.sender != owner() && msg.sender != address(s_vrfCoordinator)) {
revert OnlyOwnerOrCoordinator(msg.sender, owner(), address(s_vrfCoordinator));
}
_;
}
}
IVRFCoordinatorV2Plus.sol 36 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";
// Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
// This interface is supported by subsequent versions of VRFCoordinatorV2Plus
interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
/**
* @notice Request a set of random words.
* @param req - a struct containing following fields for randomness request:
* keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* requestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* extraArgs - abi-encoded extra args
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(VRFV2PlusClient.RandomWordsRequest calldata req) external returns (uint256 requestId);
}
IVRFMigratableConsumerV2Plus.sol 13 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFMigratableConsumerV2Plus interface defines the
/// @notice method required to be implemented by all V2Plus consumers.
/// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
interface IVRFMigratableConsumerV2Plus {
event CoordinatorSet(address vrfCoordinator);
/// @notice Sets the VRF Coordinator address
/// @notice This method should only be callable by the coordinator or contract owner
function setCoordinator(address vrfCoordinator) external;
}
IVRFSubscriptionV2Plus.sol 98 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFSubscriptionV2Plus interface defines the subscription
/// @notice related methods implemented by the V2Plus coordinator.
interface IVRFSubscriptionV2Plus {
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint256 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint256 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint256 subId, address to) external;
/**
* @notice Accept subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint256 subId) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription with LINK, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
* @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
* @dev to send Native with the call, for example:
* @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
*/
function createSubscription() external returns (uint256 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return nativeBalance - native balance of the subscription in wei.
* @return reqCount - Requests count of subscription.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(
uint256 subId
)
external
view
returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
/*
* @notice Check to see if there exists a request commitment consumers
* for all consumers and keyhashes for a given sub.
* @param subId - ID of the subscription
* @return true if there exists at least one unfulfilled request for the subscription, false
* otherwise.
*/
function pendingRequestExists(uint256 subId) external view returns (bool);
/**
* @notice Paginate through all active VRF subscriptions.
* @param startIndex index of the subscription to start from
* @param maxCount maximum number of subscriptions to return, 0 to return all
* @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
* @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
*/
function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
/**
* @notice Fund a subscription with native.
* @param subId - ID of the subscription
* @notice This method expects msg.value to be greater than or equal to 0.
*/
function fundSubscriptionWithNative(uint256 subId) external payable;
}
VRFV2PlusClient.sol 24 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// End consumer library.
library VRFV2PlusClient {
// extraArgs will evolve to support new features
bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
struct ExtraArgsV1 {
bool nativePayment;
}
struct RandomWordsRequest {
bytes32 keyHash;
uint256 subId;
uint16 requestConfirmations;
uint32 callbackGasLimit;
uint32 numWords;
bytes extraArgs;
}
function _argsToBytes(ExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
}
}
AccessControl.sol 248 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.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:
*
* ```solidity
* 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}:
*
* ```solidity
* 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. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
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);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @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 virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.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 virtual 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.
*
* May emit a {RoleGranted} event.
*/
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.
*
* May emit a {RoleRevoked} event.
*/
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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
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.
*
* May emit a {RoleGranted} event.
*
* [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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
AccessControlEnumerable.sol 64 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).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 virtual 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 virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
IAccessControl.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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;
}
IAccessControlEnumerable.sol 31 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @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);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
Pausable.sol 105 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/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.
*/
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 Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
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());
}
}
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 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount) external returns (bool);
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` 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].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
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);
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
ERC165.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
EnumerableSet.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
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.
*
* ```solidity
* 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.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
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;
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) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// 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;
/// @solidity memory-safe-assembly
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 in 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;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
RaffleV2.sol 841 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
/**
* @title TribeRafflesV2
* @notice Advanced on-chain raffle system with Chainlink VRF and EIP-2612 support
* @dev Gas-optimized contract with enhanced security and modern Solidity features
* @custom:version 2.1.0
* @custom:security-contact [email protected]
*/
contract TribeRafflesV2 is
Context,
ERC165,
ReentrancyGuard,
Pausable,
VRFConsumerBaseV2Plus,
AccessControlEnumerable
{
// ============================================================================
// CONSTANTS & IMMUTABLES
// ============================================================================
/// @dev Role identifier for raffle administrators
bytes32 public constant RAFFLE_ADMIN_ROLE = keccak256("RAFFLE_ADMIN_ROLE");
/// @dev Role identifier for raffle creators
bytes32 public constant RAFFLE_CREATOR_ROLE = keccak256("RAFFLE_CREATOR_ROLE");
/// @dev Chainlink VRF confirmation blocks
uint16 public constant REQUEST_CONFIRMATIONS = 2;
/// @dev Number of random words requested from VRF
uint32 public constant NUM_WORDS = 1;
/// @dev Minimum entry cost (1 NANA token)
uint256 public constant MIN_ENTRY_COST = 1e18;
/// @dev Minimum raffle duration
uint256 public constant MIN_RAFFLE_DURATION = 1 hours;
/// @dev Maximum raffle duration
uint256 public constant MAX_RAFFLE_DURATION = 365 days;
/// @dev Maximum entries per raffle for gas optimization
uint256 public constant MAX_ENTRIES_PER_RAFFLE = 500000;
/// @dev Maximum platform fee (10%)
uint256 public constant MAX_PLATFORM_FEE = 1000;
/// @dev NANA token contract
IERC20 public immutable nana;
/// @dev NANA token with permit functionality
IERC20Permit public immutable nanaPermit;
/// @dev NANA token decimals
uint8 public immutable decimals;
/// @dev Chainlink VRF subscription ID
uint256 public immutable vrfSubscriptionId;
/// @dev Chainlink VRF key hash
bytes32 public immutable vrfKeyHash;
/// @dev Chainlink VRF callback gas limit
uint32 public immutable vrfCallbackGasLimit;
/// @dev Whether to use native payment for VRF
bool public immutable useNativePayment;
// ============================================================================
// STORAGE
// ============================================================================
/// @dev Main raffle data structure with optimized storage layout
struct Raffle {
string name; // Raffle title
string description; // Detailed description
string prize; // Prize description
string prizeTier; // Prize tier (standard, premium, etc.)
string category; // Category (crypto, nft, etc.)
string metadata; // Additional metadata (IPFS hash, etc.)
address[] entries; // Array of participant addresses
address winner; // Winner address (zero if not drawn)
address createdBy; // Creator address
uint256 costPerEntry; // Cost per entry in NANA tokens
uint256 vrfRequestId; // Chainlink VRF request ID
uint64 startTime; // Start timestamp (packed)
uint64 endTime; // End timestamp (packed)
uint32 maxEntries; // Maximum allowed entries (packed)
bool drawn; // Whether winner has been drawn
bool pendingDraw; // Whether draw is pending VRF response
bool featured; // Whether raffle is featured
bool isActive; // Whether raffle accepts entries
bool deleted; // Whether raffle is soft-deleted
mapping(address => bool) claimed; // Prize claim status per winner
}
/// @dev Input structure for creating raffles with validation
struct RaffleInput {
string name; // Raffle title (required)
string description; // Detailed description (optional)
string prize; // Prize description (required)
string prizeTier; // Prize tier classification
string category; // Raffle category
string metadata; // Additional metadata
uint256 costPerEntry; // Entry cost in NANA tokens
uint256 maxEntries; // Maximum entries allowed
uint256 startTime; // Start timestamp
uint256 endTime; // End timestamp
bool featured; // Featured status
}
/// @dev Current raffle count (also serves as next raffle ID)
uint256 public raffleCount;
/// @dev Mapping from raffle ID to raffle data
mapping(uint256 => Raffle) private _raffles;
/// @dev Mapping from raffle ID to user address to entry count
mapping(uint256 => mapping(address => uint256)) public userEntries;
/// @dev Mapping from user address to array of raffle IDs they've entered
mapping(address => uint256[]) public userRaffles;
/// @dev Mapping from VRF request ID to raffle ID
mapping(uint256 => uint256) public vrfRequestToRaffle;
/// @dev Mapping from raffle ID to VRF request ID
mapping(uint256 => uint256) public raffleToVrfRequest;
/// @dev Array of all winner addresses for historical tracking
address[] public allWinners;
/// @dev Mapping from address to total number of wins
mapping(address => uint256) public winsByAddress;
/// @dev Platform fee recipient address
address public platformFeeRecipient;
/// @dev Platform fee in basis points (100 = 1%)
uint256 public platformFeeBps;
/// @dev Primary sale recipient for raffle proceeds
address public primarySaleRecipient;
// ============================================================================
// EVENTS
// ============================================================================
event RaffleCreated(
uint256 indexed raffleId,
string name,
uint256 costPerEntry,
uint256 maxEntries,
uint256 endTime,
address indexed creator
);
event Entered(uint256 indexed raffleId, address indexed user, uint256 amount);
event WinnerDrawRequested(uint256 indexed raffleId, uint256 indexed requestId);
event WinnerDrawn(uint256 indexed raffleId, address indexed winner);
event PrizeClaimed(uint256 indexed raffleId, address indexed winner);
event RaffleStatusChanged(uint256 indexed raffleId, bool isActive);
event RaffleDeleted(uint256 indexed raffleId, address indexed admin);
event PlatformFeeUpdated(address recipient, uint256 feeBps);
event PrimarySaleRecipientUpdated(address recipient);
// ============================================================================
// ERRORS
// ============================================================================
error NameEmpty();
error PrizeEmpty();
error NotWinner();
error PrizeAlreadyClaimed();
error InvalidEntry();
error TransferFailed();
error RaffleIsDeleted();
error RaffleNotExists();
error RaffleNotActive();
error RaffleEnded();
error InvalidAmount();
error ExceedsMaxEntries();
error InvalidTimeRange();
error NoEntries();
error WinnerAlreadyDrawn();
error DrawAlreadyRequested();
error RaffleNotEnded();
// ============================================================================
// CONSTRUCTOR
// ============================================================================
constructor(
address _nana,
address _vrfCoordinator,
uint256 _vrfSubscriptionId,
bytes32 _vrfKeyHash,
uint32 _vrfCallbackGasLimit,
bool _useNativePayment
) VRFConsumerBaseV2Plus(_vrfCoordinator) {
require(_nana != address(0), "Invalid NANA address");
require(_vrfCoordinator != address(0), "Invalid VRF coordinator");
require(_vrfSubscriptionId > 0, "Invalid subscription ID");
require(_vrfKeyHash != bytes32(0), "Invalid key hash");
require(_vrfCallbackGasLimit > 0, "Invalid callback gas limit");
nana = IERC20(_nana);
nanaPermit = IERC20Permit(_nana);
decimals = IERC20Metadata(_nana).decimals();
vrfSubscriptionId = _vrfSubscriptionId;
vrfKeyHash = _vrfKeyHash;
vrfCallbackGasLimit = _vrfCallbackGasLimit;
useNativePayment = _useNativePayment;
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(RAFFLE_ADMIN_ROLE, msg.sender);
_grantRole(RAFFLE_CREATOR_ROLE, msg.sender);
platformFeeRecipient = msg.sender;
primarySaleRecipient = msg.sender;
platformFeeBps = 250; // 2.5% default
}
// ============================================================================
// MODIFIERS
// ============================================================================
modifier raffleExists(uint256 raffleId) {
if (raffleId >= raffleCount) revert RaffleNotExists();
_;
}
modifier raffleActive(uint256 raffleId) {
Raffle storage r = _raffles[raffleId];
if (r.deleted) revert RaffleIsDeleted();
if (!r.isActive) revert RaffleNotActive();
_;
}
modifier notPaused() {
_requireNotPaused();
_;
}
// ============================================================================
// CORE RAFFLE FUNCTIONS
// ============================================================================
/**
* @notice Create a new raffle
* @param input Raffle parameters
*/
function createRaffle(RaffleInput calldata input)
external
onlyRole(RAFFLE_CREATOR_ROLE)
notPaused
{
if (bytes(input.name).length == 0) revert NameEmpty();
if (bytes(input.prize).length == 0) revert PrizeEmpty();
if (input.costPerEntry < MIN_ENTRY_COST) revert InvalidAmount();
if (input.maxEntries == 0 || input.maxEntries > MAX_ENTRIES_PER_RAFFLE) revert InvalidAmount();
if (input.endTime <= block.timestamp + MIN_RAFFLE_DURATION) revert InvalidTimeRange();
if (input.endTime > block.timestamp + MAX_RAFFLE_DURATION) revert InvalidTimeRange();
if (input.startTime >= input.endTime) revert InvalidTimeRange();
uint256 currentId = raffleCount;
Raffle storage r = _raffles[currentId];
r.name = input.name;
r.description = input.description;
r.prize = input.prize;
r.prizeTier = input.prizeTier;
r.category = input.category;
r.metadata = input.metadata;
r.costPerEntry = input.costPerEntry;
r.maxEntries = uint32(input.maxEntries);
r.startTime = uint64(input.startTime);
r.endTime = uint64(input.endTime);
r.featured = input.featured;
r.isActive = true;
r.createdBy = msg.sender;
emit RaffleCreated(
currentId,
input.name,
input.costPerEntry,
input.maxEntries,
input.endTime,
msg.sender
);
unchecked {
raffleCount = currentId + 1;
}
}
/**
* @notice Enter a raffle with standard approval
* @param raffleId The raffle to enter
* @param amount Number of entries
*/
function enter(uint256 raffleId, uint256 amount)
external
nonReentrant
notPaused
raffleExists(raffleId)
raffleActive(raffleId)
{
Raffle storage r = _raffles[raffleId];
if (block.timestamp >= r.endTime) revert RaffleEnded();
if (amount == 0) revert InvalidAmount();
if (r.entries.length + amount > r.maxEntries) revert ExceedsMaxEntries();
uint256 totalCost = r.costPerEntry * amount;
_processPayment(totalCost);
_addEntries(raffleId, msg.sender, amount);
emit Entered(raffleId, msg.sender, amount);
}
/**
* @notice Enter a raffle using EIP-2612 permit (single transaction)
* @param raffleId The raffle to enter
* @param amount Number of entries
* @param deadline Permit deadline
* @param v Permit signature v
* @param r Permit signature r
* @param s Permit signature s
*/
function enterWithPermit(
uint256 raffleId,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant notPaused raffleExists(raffleId) raffleActive(raffleId) {
Raffle storage raffle = _raffles[raffleId];
if (block.timestamp >= raffle.endTime) revert RaffleEnded();
if (amount == 0) revert InvalidAmount();
if (raffle.entries.length + amount > raffle.maxEntries) revert ExceedsMaxEntries();
uint256 totalCost = raffle.costPerEntry * amount;
nanaPermit.permit(msg.sender, address(this), totalCost, deadline, v, r, s);
_processPayment(totalCost);
_addEntries(raffleId, msg.sender, amount);
emit Entered(raffleId, msg.sender, amount);
}
/**
* @notice Request winner draw using Chainlink VRF
* @param raffleId The raffle to draw winner for
*/
function requestDrawWinner(uint256 raffleId)
external
onlyRole(RAFFLE_ADMIN_ROLE)
raffleExists(raffleId)
{
Raffle storage r = _raffles[raffleId];
if (r.deleted) revert RaffleIsDeleted();
if (block.timestamp < r.endTime) revert RaffleNotEnded();
if (r.drawn) revert WinnerAlreadyDrawn();
if (r.pendingDraw) revert DrawAlreadyRequested();
if (r.entries.length == 0) revert NoEntries();
if (!r.isActive) revert RaffleNotActive();
r.pendingDraw = true;
uint256 requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: vrfKeyHash,
subId: vrfSubscriptionId,
requestConfirmations: REQUEST_CONFIRMATIONS,
callbackGasLimit: vrfCallbackGasLimit,
numWords: NUM_WORDS,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({ nativePayment: useNativePayment })
)
})
);
r.vrfRequestId = requestId;
vrfRequestToRaffle[requestId] = raffleId;
raffleToVrfRequest[raffleId] = requestId;
emit WinnerDrawRequested(raffleId, requestId);
}
/**
* @notice Claim prize (winner only)
* @param raffleId The raffle to claim prize from
*/
function claimPrize(uint256 raffleId) external raffleExists(raffleId) nonReentrant {
Raffle storage r = _raffles[raffleId];
if (r.deleted) revert RaffleIsDeleted();
if (!r.drawn) revert();
if (msg.sender != r.winner) revert NotWinner();
if (r.claimed[msg.sender]) revert PrizeAlreadyClaimed();
r.claimed[msg.sender] = true;
emit PrizeClaimed(raffleId, msg.sender);
}
// ============================================================================
// ADMIN FUNCTIONS
// ============================================================================
/**
* @notice Set raffle status (admin only)
*/
function setRaffleStatus(uint256 raffleId, bool isActive)
external
onlyRole(RAFFLE_ADMIN_ROLE)
raffleExists(raffleId)
{
Raffle storage r = _raffles[raffleId];
if (r.deleted) revert RaffleIsDeleted();
r.isActive = isActive;
emit RaffleStatusChanged(raffleId, isActive);
}
/**
* @notice Delete raffle (admin only)
*/
function deleteRaffle(uint256 raffleId)
external
onlyRole(RAFFLE_ADMIN_ROLE)
raffleExists(raffleId)
{
Raffle storage r = _raffles[raffleId];
require(!r.drawn || r.claimed[r.winner], "Cannot delete unclaimed prize");
r.deleted = true;
r.isActive = false;
emit RaffleDeleted(raffleId, msg.sender);
}
/**
* @notice Restore deleted raffle (admin only)
*/
function restoreRaffle(uint256 raffleId)
external
onlyRole(RAFFLE_ADMIN_ROLE)
raffleExists(raffleId)
{
Raffle storage r = _raffles[raffleId];
require(r.deleted, "Raffle not deleted");
r.deleted = false;
r.isActive = true;
emit RaffleStatusChanged(raffleId, true);
}
/**
* @notice Set platform fee (admin only)
*/
function setPlatformFee(address recipient, uint256 feeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(recipient != address(0), "Invalid recipient");
require(feeBps <= MAX_PLATFORM_FEE, "Fee too high"); // Max 10%
platformFeeRecipient = recipient;
platformFeeBps = feeBps;
emit PlatformFeeUpdated(recipient, feeBps);
}
/**
* @notice Set primary sale recipient (admin only)
*/
function setPrimarySaleRecipient(address recipient)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(recipient != address(0), "Invalid recipient");
primarySaleRecipient = recipient;
emit PrimarySaleRecipientUpdated(recipient);
}
/**
* @notice Pause contract (admin only)
*/
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
/**
* @notice Unpause contract (admin only)
*/
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
// ============================================================================
// VIEW FUNCTIONS
// ============================================================================
/**
* @notice Get raffle information
*/
function getRaffle(uint256 raffleId) external view raffleExists(raffleId) returns (
string memory name,
string memory description,
string memory prize,
uint256 costPerEntry,
uint256 maxEntries,
uint256 startTime,
uint256 endTime,
bool featured,
string memory prizeTier,
string memory category,
string memory metadata,
bool drawn,
address winner,
uint256 totalEntries,
bool isActive,
bool pendingDraw,
bool deleted,
address createdBy
) {
Raffle storage r = _raffles[raffleId];
return (
r.name, r.description, r.prize, r.costPerEntry,
r.maxEntries, r.startTime, r.endTime, r.featured,
r.prizeTier, r.category, r.metadata, r.drawn, r.winner,
r.entries.length, r.isActive, r.pendingDraw, r.deleted, r.createdBy
);
}
/**
* @notice Get all raffle IDs
*/
function getAllRaffleIds(bool onlyActive, bool includeDeleted)
external
view
returns (uint256[] memory)
{
uint256[] memory ids = new uint256[](raffleCount);
uint256 count;
for (uint256 i; i < raffleCount;) {
Raffle storage r = _raffles[i];
bool include = true;
if (!includeDeleted && r.deleted) include = false;
if (onlyActive && !r.isActive) include = false;
if (include) {
ids[count] = i;
unchecked { ++count; }
}
unchecked { ++i; }
}
uint256[] memory result = new uint256[](count);
for (uint256 j; j < count;) {
result[j] = ids[j];
unchecked { ++j; }
}
return result;
}
/**
* @notice Get raffle participants (paginated)
*/
function getParticipantsPaginated(uint256 raffleId, uint256 offset, uint256 limit)
external
view
raffleExists(raffleId)
returns (address[] memory)
{
Raffle storage r = _raffles[raffleId];
if (r.deleted) revert RaffleIsDeleted();
uint256 total = r.entries.length;
if (offset >= total) return new address[](0);
uint256 end = offset + limit > total ? total : offset + limit;
address[] memory page = new address[](end - offset);
for (uint256 i = offset; i < end; i++) {
page[i - offset] = r.entries[i];
}
return page;
}
/**
* @notice Get all participants for a raffle
*/
function getParticipants(uint256 raffleId)
external
view
raffleExists(raffleId)
returns (address[] memory)
{
if (_raffles[raffleId].deleted) revert RaffleIsDeleted();
return _raffles[raffleId].entries;
}
/**
* @notice Get user's entry count for a raffle
*/
function getUserEntryCount(uint256 raffleId, address user)
external
view
returns (uint256)
{
return userEntries[raffleId][user];
}
/**
* @notice Get all raffles created by a user
*/
function getUserRaffles(address user) external view returns (uint256[] memory) {
return userRaffles[user];
}
/**
* @notice Get raffles by creator
*/
function getRafflesByCreator(address creator, bool includeDeleted)
external
view
returns (uint256[] memory)
{
uint256[] memory temp = new uint256[](raffleCount);
uint256 count = 0;
for (uint256 i = 0; i < raffleCount; i++) {
Raffle storage r = _raffles[i];
if (r.createdBy == creator && (includeDeleted || !r.deleted)) {
temp[count++] = i;
}
}
uint256[] memory result = new uint256[](count);
for (uint256 j = 0; j < count; j++) {
result[j] = temp[j];
}
return result;
}
/**
* @notice Get all winners (paginated)
*/
function getAllWinners(uint256 offset, uint256 limit)
external
view
returns (address[] memory)
{
uint256 total = allWinners.length;
if (offset >= total) return new address[](0);
uint256 end = offset + limit > total ? total : offset + limit;
address[] memory page = new address[](end - offset);
for (uint256 i = offset; i < end; i++) {
page[i - offset] = allWinners[i];
}
return page;
}
/**
* @notice Get platform fee info
*/
function getPlatformFeeInfo() external view returns (address, uint256) {
return (platformFeeRecipient, platformFeeBps);
}
/**
* @notice Get detailed raffle statistics
* @param raffleId Raffle ID
* @return totalValue Total value of all entries
* @return totalEntries Total number of entries
* @return isCompleted Whether the raffle is completed
*/
function getRaffleStats(uint256 raffleId)
external
view
raffleExists(raffleId)
returns (
uint256 totalValue,
uint256 totalEntries,
bool isCompleted
)
{
Raffle storage r = _raffles[raffleId];
totalValue = r.entries.length * r.costPerEntry;
totalEntries = r.entries.length;
isCompleted = r.drawn || block.timestamp >= r.endTime;
}
// ============================================================================
// INTERNAL FUNCTIONS
// ============================================================================
/**
* @notice Process payment with platform fee
*/
function _processPayment(uint256 totalCost) internal {
uint256 platformFee = (totalCost * platformFeeBps) / 10000;
uint256 saleProceeds = totalCost - platformFee;
if (!nana.transferFrom(msg.sender, address(this), totalCost)) {
revert TransferFailed();
}
if (platformFee > 0 && platformFeeRecipient != address(0)) {
if (!nana.transfer(platformFeeRecipient, platformFee)) {
revert TransferFailed();
}
}
if (saleProceeds > 0 && primarySaleRecipient != address(0)) {
if (!nana.transfer(primarySaleRecipient, saleProceeds)) {
revert TransferFailed();
}
}
}
/**
* @notice Add entries to raffle
*/
function _addEntries(uint256 raffleId, address user, uint256 amount) internal {
Raffle storage raffle = _raffles[raffleId];
for (uint256 i; i < amount;) {
raffle.entries.push(user);
unchecked { ++i; }
}
userEntries[raffleId][user] += amount;
// Only add to userRaffles if first entry
if (userEntries[raffleId][user] == amount) {
userRaffles[user].push(raffleId);
}
}
/**
* @notice Chainlink VRF callback
*/
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords)
internal
override
{
uint256 raffleId = vrfRequestToRaffle[requestId];
Raffle storage r = _raffles[raffleId];
if (r.drawn || r.entries.length == 0) return;
uint256 winnerIndex = randomWords[0] % r.entries.length;
address winner = r.entries[winnerIndex];
r.winner = winner;
r.drawn = true;
r.pendingDraw = false;
allWinners.push(winner);
unchecked {
winsByAddress[winner]++;
}
emit WinnerDrawn(raffleId, winner);
}
// ============================================================================
// ERC165 SUPPORT
// ============================================================================
/**
* @notice Check if contract supports a given interface
* @param interfaceId The interface identifier
* @return True if interface is supported
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, AccessControlEnumerable)
returns (bool)
{
return
interfaceId == type(IERC165).interfaceId ||
super.supportsInterface(interfaceId);
}
// ============================================================================
// ENHANCED FEATURES
// ============================================================================
/**
* @notice Get contract version
* @return Version string
*/
function version() external pure returns (string memory) {
return "2.1.0";
}
/**
* @notice Get contract name
* @return Contract name
*/
function contractName() external pure returns (string memory) {
return "TribeRafflesV2";
}
/**
* @notice Emergency function to recover stuck tokens (admin only)
* @param token Token address to recover
* @param amount Amount to recover
* @param to Recipient address
*/
function emergencyTokenRecovery(
address token,
uint256 amount,
address to
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(to != address(0), "Invalid recipient");
require(token != address(nana), "Cannot recover NANA tokens");
IERC20(token).transfer(to, amount);
}
}
Read Contract
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
MAX_ENTRIES_PER_RAFFLE 0xf63074a1 → uint256
MAX_PLATFORM_FEE 0x3998a681 → uint256
MAX_RAFFLE_DURATION 0xe2ba58d4 → uint256
MIN_ENTRY_COST 0xfbf14086 → uint256
MIN_RAFFLE_DURATION 0x81eff790 → uint256
NUM_WORDS 0x72cf6e34 → uint32
RAFFLE_ADMIN_ROLE 0x73bd4500 → bytes32
RAFFLE_CREATOR_ROLE 0xc9c35826 → bytes32
REQUEST_CONFIRMATIONS 0x67f082b0 → uint16
allWinners 0xdbff4e30 → address
contractName 0x75d0c0dc → string
decimals 0x313ce567 → uint8
getAllRaffleIds 0x82e0f38d → uint256[]
getAllWinners 0x8910ce0b → address[]
getParticipants 0xc1e3bd3e → address[]
getParticipantsPaginated 0xcadefed3 → address[]
getPlatformFeeInfo 0xd45573f6 → address, uint256
getRaffle 0xe4dafec9 → string, string, string, uint256, uint256, uint256, uint256, bool, string, string, string, bool, address, uint256, bool, bool, bool, address
getRaffleStats 0xd1cfcd0d → uint256, uint256, bool
getRafflesByCreator 0x8bcb9cf9 → uint256[]
getRoleAdmin 0x248a9ca3 → bytes32
getRoleMember 0x9010d07c → address
getRoleMemberCount 0xca15c873 → uint256
getUserEntryCount 0x325fd7e9 → uint256
getUserRaffles 0x98d71138 → uint256[]
hasRole 0x91d14854 → bool
nana 0xbf1e4ad0 → address
nanaPermit 0xfb14ea64 → address
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
platformFeeBps 0x22dcd13e → uint256
platformFeeRecipient 0xeb13554f → address
primarySaleRecipient 0x079fe40e → address
raffleCount 0xa54c120c → uint256
raffleToVrfRequest 0x2fce8446 → uint256
s_vrfCoordinator 0x9eccacf6 → address
supportsInterface 0x01ffc9a7 → bool
useNativePayment 0x11bccc84 → bool
userEntries 0xec474191 → uint256
userRaffles 0xd51075c1 → uint256
version 0x54fd4d50 → string
vrfCallbackGasLimit 0x3b7ed734 → uint32
vrfKeyHash 0x041d443e → bytes32
vrfRequestToRaffle 0xf7da5ef7 → uint256
vrfSubscriptionId 0xed647d21 → uint256
winsByAddress 0x24c88a70 → uint256
Write Contract 20 functions
These functions modify contract state and require a wallet transaction to execute.
acceptOwnership 0x79ba5097
No parameters
claimPrize 0xd7098154
uint256 raffleId
createRaffle 0xb25f37f9
tuple input
deleteRaffle 0x66c74034
uint256 raffleId
emergencyTokenRecovery 0xce148e3d
address token
uint256 amount
address to
enter 0x23972aef
uint256 raffleId
uint256 amount
enterWithPermit 0xb2445124
uint256 raffleId
uint256 amount
uint256 deadline
uint8 v
bytes32 r
bytes32 s
grantRole 0x2f2ff15d
bytes32 role
address account
pause 0x8456cb59
No parameters
rawFulfillRandomWords 0x1fe543e3
uint256 requestId
uint256[] randomWords
renounceRole 0x36568abe
bytes32 role
address account
requestDrawWinner 0x330a308f
uint256 raffleId
restoreRaffle 0xc1c9d953
uint256 raffleId
revokeRole 0xd547741f
bytes32 role
address account
setCoordinator 0x8ea98117
address _vrfCoordinator
setPlatformFee 0x8db1afb1
address recipient
uint256 feeBps
setPrimarySaleRecipient 0x6f4f2837
address recipient
setRaffleStatus 0x94751f9e
uint256 raffleId
bool isActive
transferOwnership 0xf2fde38b
address to
unpause 0x3f4ba83a
No parameters
Recent Transactions
No transactions found for this address