Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xa4108aA1Ec4967F8b52220a4f7e94A8201F2D906
Balance 0 ETH
Nonce 32
Code Size 13549 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

13549 bytes
0x60806040523480156200001157600080fd5b5060043610620001085760003560e01c80638690ff9811620000a3578063c9d194d5116200006e578063c9d194d51462000236578063df97174b1462000259578063f2b53307146200027c578063f7955637146200028657600080fd5b80638690ff9814620001d6578063aca6b1c114620001ed578063b56561fe1462000204578063bdda81d4146200020e57600080fd5b80630f21235711620000e45780630f212357146200017b5780636941db93146200019257806373b2054714620001a95780637dfb6f8614620001b357600080fd5b8062901153146200010d578063010315251462000126578063011b2174146200013d575b600080fd5b620001246200011e36600462001893565b6200029d565b005b620001246200013736600462001914565b620002b3565b620001696200014e36600462001979565b6001600160a01b031660009081526002602052604090205490565b60405190815260200160405180910390f35b620001246200018c366004620019db565b620002ce565b62000124620001a336600462001c29565b62000490565b6200016960055481565b62000169620001c436600462001dc5565b60036020526000908152604090205481565b62000124620001e736600462001e26565b62000825565b62000124620001fe36600462001f5f565b62000b7a565b6200016960045481565b620001697f677261766974792d6272696467652d6d61696e6e65740000000000000000000081565b620001696200024736600462001dc5565b60009081526003602052604090205490565b620001696200026a36600462001979565b60026020526000908152604090205481565b6200016960015481565b620001246200029736600462002005565b62000e69565b620002ac858585858562000f21565b5050505050565b620002c9620002c283620020bb565b826200107b565b505050565b60026000541415620002fd5760405162461bcd60e51b8152600401620002f49062002171565b60405180910390fd5b600260009081556040516370a0823160e01b81523060048201526001600160a01b038616906370a0823190602401602060405180830381865afa15801562000349573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200036f9190620021a8565b9050620003886001600160a01b038616333085620010e7565b6040516370a0823160e01b81523060048201526000906001600160a01b038716906370a0823190602401602060405180830381865afa158015620003d0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620003f69190620021a8565b905081811162000419576040516321739d9b60e01b815260040160405180910390fd5b60055462000429906001620021d8565b600555336001600160a01b0387167f9e9794dbf94b0a0aa31a480f5b38550eda7f89115ac8fbf4953fa4dd219900c98787620004668787620021f3565b6005546040516200047b949392919062002236565b60405180910390a35050600160005550505050565b60026000541415620004b65760405162461bcd60e51b8152600401620002f49062002171565b600260005560c08101514310620004e05760405163bcf37c2560e01b815260040160405180910390fd5b61010081015160e0820151600090815260036020526040902054106200053d5761010081015160e082015160009081526003602052604090819020549051629427e960e11b815260048101929092526024820152604401620002f4565b6200054a8484846200115a565b600154620005836200055c86620020bb565b7f677261766974792d6272696467652d6d61696e6e6574000000000000000000006200107b565b14620005a25760405163723a340360e01b815260040160405180910390fd5b60208101515181515114620005ca57604051634298a95160e11b815260040160405180910390fd5b80606001515181604001515114620005f557604051634829247960e01b815260040160405180910390fd5b60007f677261766974792d6272696467652d6d61696e6e657400000000000000000000681b1bd9da58d0d85b1b60ba1b836000015184602001518560400151866060015187608001518860a001518960c001518a60e001518b61010001516040516020016200066f9b9a9998979695949392919062002334565b6040516020818303038152906040528051906020012090506200069a8585858463aaaaaaaa62000f21565b5061010081015160e08201516000908152600360205260408120919091555b8151518110156200073d5762000728826080015183600001518381518110620006e657620006e6620023e4565b602002602001015184602001518481518110620007075762000707620023e4565b60200260200101516001600160a01b0316620011b39092919063ffffffff16565b806200073481620023fa565b915050620006b9565b5060006200075482608001518360a00151620011e5565b905060005b826040015151811015620007bb57620007a63384604001518381518110620007855762000785620023e4565b602002602001015185606001518481518110620007075762000707620023e4565b80620007b281620023fa565b91505062000759565b50600554620007cc906001620021d8565b600581905560e08301516101008401516040517f7c2bb24f8e1b3725cb613d7f11ef97d9745cc97a0e40f730621c052d684077a1936200081193929186919062002418565b60405180910390a150506001600055505050565b600260005414156200084b5760405162461bcd60e51b8152600401620002f49062002171565b600260008181556001600160a01b038416815260209190915260409020548311620008af576001600160a01b0382166000908152600260205260409081902054905163f7f920ad60e01b8152620002f4918591600401918252602082015260400190565b6001600160a01b038216600090815260026020526040902054620008d790620f4240620021d8565b8311156200091e576001600160a01b0382166000908152600260205260409081902054905163f7f920ad60e01b8152620002f4918591600401918252602082015260400190565b8043106200093f576040516308b9266360e11b815260040160405180910390fd5b6200094c8c8c8c6200115a565b6001546200095e6200055c8e620020bb565b146200097d5760405163723a340360e01b815260040160405180910390fd5b87861415806200098d5750878414155b15620009ac5760405163c1f97e3560e01b815260040160405180910390fd5b62000a2e8c8c8c7f677261766974792d6272696467652d6d61696e6e6574000000000000000000006f0e8e4c2dce6c2c6e8d2dedc84c2e8c6d60831b8e8e8e8e8e8e8e8e8e60405160200162000a0d9b9a99989796959493929190620024c1565b6040516020818303038152906040528051906020012063aaaaaaaa62000f21565b6001600160a01b0382166000908152600260205260408120849055805b8981101562000afa5762000aba89898381811062000a6d5762000a6d620023e4565b905060200201602081019062000a84919062001979565b8c8c8481811062000a995762000a99620023e4565b90506020020135866001600160a01b0316620011b39092919063ffffffff16565b86868281811062000acf5762000acf620023e4565b905060200201358262000ae39190620021d8565b91508062000af181620023fa565b91505062000a4b565b5062000b116001600160a01b0384163383620011b3565b5060055462000b22906001620021d8565b60058190556040519081526001600160a01b0383169084907f02c7e81975f8edb86e2a0c038b7b86a49c744236abf0f6177ff5afc6986ab7089060200160405180910390a35050600160005550505050505050505050565b826040013584604001351162000bb3576040805163e0e8edf360e01b8152818601356004820152908401356024820152604401620002f4565b62000bc66040840135620f4240620021d8565b8460400135111562000bfb576040805163e0e8edf360e01b8152818601356004820152908401356024820152604401620002f4565b62000c0a60208501856200253f565b905062000c1885806200253f565b905014158062000c33575062000c2f84806200253f565b1590505b1562000c525760405163c01ba0ab60e01b815260040160405180910390fd5b62000c5f8383836200115a565b6000805b62000c7260208701876200253f565b905081101562000cdc5762000c8b60208701876200253f565b8281811062000c9e5762000c9e620023e4565b905060200201358262000cb29190620021d8565b915063aaaaaaaa82111562000cc75762000cdc565b8062000cd381620023fa565b91505062000c63565b5063aaaaaaaa811162000d0f5760405162bfb6ab60e01b81526004810182905263aaaaaaaa6024820152604401620002f4565b60015462000d216200055c86620020bb565b1462000d405760405163723a340360e01b815260040160405180910390fd5b600062000d516200055c87620020bb565b905062000d668585858463aaaaaaaa62000f21565b60018190556040860135600455600062000d8760a088016080890162001979565b6001600160a01b03161415801562000da25750606086013515155b1562000dd55762000dd533606088013562000dc460a08a0160808b0162001979565b6001600160a01b03169190620011b3565b60055462000de5906001620021d8565b60058190556040870135907f76d08978c024a4bf8cbb30c67fd78fcaa1827cbc533e4e175f36d07e64ccf96a90606089013562000e2960a08b0160808c0162001979565b62000e358b806200253f565b62000e4460208e018e6200253f565b60405162000e5997969594939291906200258b565b60405180910390a2505050505050565b600030868686868660405162000e7f906200181e565b62000e9096959493929190620025de565b604051809103906000f08015801562000ead573d6000803e3d6000fd5b509050600554600162000ec19190620021d8565b60058190556040516001600160a01b038316917f82fe3a4fa49c6382d0c085746698ddbbafe6c2bf61285b19410644b5b26287c79162000f0f918c918c918c918c918c918c918c9162002631565b60405180910390a25050505050505050565b6000805b62000f3187806200253f565b9050811015620010475785858281811062000f505762000f50620023e4565b62000f6892602060609092020190810191506200268e565b60ff1615620010325762000fcd62000f8188806200253f565b8381811062000f945762000f94620023e4565b905060200201602081019062000fab919062001979565b8588888581811062000fc15762000fc1620023e4565b90506060020162001230565b62000feb57604051638baa579f60e01b815260040160405180910390fd5b62000ffa60208801886200253f565b828181106200100d576200100d620023e4565b9050602002013582620010219190620021d8565b915082821115620010325762001047565b806200103e81620023fa565b91505062000f25565b50818111620010735760405162bfb6ab60e01b81526004810182905260248101839052604401620002f4565b505050505050565b6000806918da1958dadc1bda5b9d60b21b60001b90506000838286604001518760000151886020015189606001518a60800151604051602001620010c69796959493929190620026ac565b60408051808303601f19018152919052805160209091012095945050505050565b6040516001600160a01b0380851660248301528316604482015260648101829052620011549085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152620012c5565b50505050565b6200116960208401846200253f565b90506200117784806200253f565b9050141580620011945750806200118f84806200253f565b905014155b15620002c95760405163c6617b7b60e01b815260040160405180910390fd5b6040516001600160a01b038316602482015260448101829052620002c990849063a9059cbb60e01b906064016200111c565b60606200122983836040518060400160405280601e81526020017f416464726573733a206c6f772d6c6576656c2063616c6c206661696c656400008152506200139e565b9392505050565b6040517f19457468657265756d205369676e6564204d6573736167653a0a3332000000006020820152603c81018390526000908190605c0160408051601f1981840301815291905280516020918201209150620012a790829062001297908601866200268e565b85602001358660400135620013b7565b6001600160a01b0316856001600160a01b0316149150509392505050565b60006200131c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166200139e9092919063ffffffff16565b805190915015620002c957808060200190518101906200133d91906200270c565b620002c95760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401620002f4565b6060620013af8484600085620013e3565b949350505050565b6000806000620013ca8787878762001515565b91509150620013d9816200160a565b5095945050505050565b606082471015620014465760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401620002f4565b843b620014965760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401620002f4565b600080866001600160a01b03168587604051620014b4919062002730565b60006040518083038185875af1925050503d8060008114620014f3576040519150601f19603f3d011682016040523d82523d6000602084013e620014f8565b606091505b50915091506200150a828286620017e0565b979650505050505050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156200154e575060009050600362001601565b8460ff16601b141580156200156757508460ff16601c14155b156200157a575060009050600462001601565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015620015cf573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116620015fa5760006001925092505062001601565b9150600090505b94509492505050565b60008160048111156200162157620016216200274e565b14156200162b5750565b60018160048111156200164257620016426200274e565b1415620016925760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401620002f4565b6002816004811115620016a957620016a96200274e565b1415620016f95760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401620002f4565b60038160048111156200171057620017106200274e565b14156200176b5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401620002f4565b60048160048111156200178257620017826200274e565b1415620017dd5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202776272076616c604482015261756560f01b6064820152608401620002f4565b50565b60608315620017f157508162001229565b825115620018025782518084602001fd5b8160405162461bcd60e51b8152600401620002f4919062002764565b610d3e806200277a83390190565b600060a082840312156200183f57600080fd5b50919050565b60008083601f8401126200185857600080fd5b5081356001600160401b038111156200187057600080fd5b6020830191508360206060830285010111156200188c57600080fd5b9250929050565b600080600080600060808688031215620018ac57600080fd5b85356001600160401b0380821115620018c457600080fd5b620018d289838a016200182c565b96506020880135915080821115620018e957600080fd5b50620018f88882890162001845565b9699909850959660408101359660609091013595509350505050565b600080604083850312156200192857600080fd5b82356001600160401b038111156200193f57600080fd5b6200194d858286016200182c565b95602094909401359450505050565b80356001600160a01b03811681146200197457600080fd5b919050565b6000602082840312156200198c57600080fd5b62001229826200195c565b60008083601f840112620019aa57600080fd5b5081356001600160401b03811115620019c257600080fd5b6020830191508360208285010111156200188c57600080fd5b60008060008060608587031215620019f257600080fd5b620019fd856200195c565b935060208501356001600160401b0381111562001a1957600080fd5b62001a278782880162001997565b9598909750949560400135949350505050565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b038111828210171562001a765762001a7662001a3a565b60405290565b604051601f8201601f191681016001600160401b038111828210171562001aa75762001aa762001a3a565b604052919050565b60006001600160401b0382111562001acb5762001acb62001a3a565b5060051b60200190565b600082601f83011262001ae757600080fd5b8135602062001b0062001afa8362001aaf565b62001a7c565b82815260059290921b8401810191818101908684111562001b2057600080fd5b8286015b8481101562001b3d578035835291830191830162001b24565b509695505050505050565b600082601f83011262001b5a57600080fd5b8135602062001b6d62001afa8362001aaf565b82815260059290921b8401810191818101908684111562001b8d57600080fd5b8286015b8481101562001b3d5762001ba5816200195c565b835291830191830162001b91565b600082601f83011262001bc557600080fd5b81356001600160401b0381111562001be15762001be162001a3a565b62001bf6601f8201601f191660200162001a7c565b81815284602083860101111562001c0c57600080fd5b816020850160208301376000918101602001919091529392505050565b6000806000806060858703121562001c4057600080fd5b84356001600160401b038082111562001c5857600080fd5b62001c66888389016200182c565b9550602087013591508082111562001c7d57600080fd5b62001c8b8883890162001845565b9095509350604087013591508082111562001ca557600080fd5b90860190610120828903121562001cbb57600080fd5b62001cc562001a50565b82358281111562001cd557600080fd5b62001ce38a82860162001ad5565b82525060208301358281111562001cf957600080fd5b62001d078a82860162001b48565b60208301525060408301358281111562001d2057600080fd5b62001d2e8a82860162001ad5565b60408301525060608301358281111562001d4757600080fd5b62001d558a82860162001b48565b60608301525062001d69608084016200195c565b608082015260a08301358281111562001d8157600080fd5b62001d8f8a82860162001bb3565b60a08301525060c083013560c082015260e083013560e08201526101009150818301358282015280935050505092959194509250565b60006020828403121562001dd857600080fd5b5035919050565b60008083601f84011262001df257600080fd5b5081356001600160401b0381111562001e0a57600080fd5b6020830191508360208260051b85010111156200188c57600080fd5b6000806000806000806000806000806000806101008d8f03121562001e4a57600080fd5b6001600160401b038d35111562001e6057600080fd5b62001e6f8e8e358f016200182c565b9b506001600160401b0360208e0135111562001e8a57600080fd5b62001e9c8e60208f01358f0162001845565b909b5099506001600160401b0360408e0135111562001eba57600080fd5b62001ecc8e60408f01358f0162001ddf565b90995097506001600160401b0360608e0135111562001eea57600080fd5b62001efc8e60608f01358f0162001ddf565b90975095506001600160401b0360808e0135111562001f1a57600080fd5b62001f2c8e60808f01358f0162001ddf565b909550935060a08d0135925062001f4660c08e016200195c565b915060e08d013590509295989b509295989b509295989b565b6000806000806060858703121562001f7657600080fd5b84356001600160401b038082111562001f8e57600080fd5b62001f9c888389016200182c565b9550602087013591508082111562001fb357600080fd5b62001fc1888389016200182c565b9450604087013591508082111562001fd857600080fd5b5062001fe78782880162001845565b95989497509550505050565b803560ff811681146200197457600080fd5b60008060008060008060006080888a0312156200202157600080fd5b87356001600160401b03808211156200203957600080fd5b620020478b838c0162001997565b909950975060208a01359150808211156200206157600080fd5b6200206f8b838c0162001997565b909750955060408a01359150808211156200208957600080fd5b50620020988a828b0162001997565b9094509250620020ad90506060890162001ff3565b905092959891949750929550565b600060a08236031215620020ce57600080fd5b60405160a081016001600160401b038282108183111715620020f457620020f462001a3a565b8160405284359150808211156200210a57600080fd5b620021183683870162001b48565b835260208501359150808211156200212f57600080fd5b506200213e3682860162001ad5565b602083015250604083013560408201526060830135606082015262002166608084016200195c565b608082015292915050565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b600060208284031215620021bb57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115620021ee57620021ee620021c2565b500190565b600082821015620022085762002208620021c2565b500390565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6060815260006200224c6060830186886200220d565b6020830194909452506040015292915050565b600081518084526020808501945080840160005b83811015620022915781518752958201959082019060010162002273565b509495945050505050565b600081518084526020808501945080840160005b83811015620022915781516001600160a01b031687529582019590820190600101620022b0565b60005b83811015620022f4578181015183820152602001620022da565b83811115620011545750506000910152565b6000815180845262002320816020860160208601620022d7565b601f01601f19169290920160200192915050565b60006101608d83528c6020840152806040840152620023568184018d6200225f565b905082810360608401526200236c818c6200229c565b9050828103608084015262002382818b6200225f565b905082810360a084015262002398818a6200229c565b6001600160a01b03891660c085015283810360e08501529050620023bd818862002306565b61010084019690965250506101208101929092526101409091015298975050505050505050565b634e487b7160e01b600052603260045260246000fd5b6000600019821415620024115762002411620021c2565b5060010190565b84815283602082015260806040820152600062002439608083018562002306565b905082606083015295945050505050565b81835260006001600160fb1b038311156200246457600080fd5b8260051b8083602087013760009401602001938452509192915050565b8183526000602080850194508260005b8581101562002291576001600160a01b03620024ad836200195c565b168752958201959082019060010162002491565b60006101008d83528c6020840152806040840152620024e48184018c8e6200244a565b90508281036060840152620024fb818a8c62002481565b905082810360808401526200251281888a6200244a565b60a084019690965250506001600160a01b039290921660c083015260e09091015298975050505050505050565b6000808335601e198436030181126200255757600080fd5b8301803591506001600160401b038211156200257257600080fd5b6020019150600581901b36038213156200188c57600080fd5b87815286602082015260018060a01b038616604082015260a060608201526000620025bb60a08301868862002481565b8281036080840152620025d08185876200244a565b9a9950505050505050505050565b6001600160a01b03871681526080602082018190526000906200260590830187896200220d565b82810360408401526200261a8186886200220d565b91505060ff83166060830152979650505050505050565b60a0815260006200264760a083018a8c6200220d565b82810360208401526200265c81898b6200220d565b90508281036040840152620026738187896200220d565b60ff9590951660608401525050608001529695505050505050565b600060208284031215620026a157600080fd5b620012298262001ff3565b87815286602082015285604082015260e060608201526000620026d360e08301876200229c565b8281036080840152620026e781876200225f565b60a084019590955250506001600160a01b039190911660c09091015295945050505050565b6000602082840312156200271f57600080fd5b815180151581146200122957600080fd5b6000825162002744818460208701620022d7565b9190910192915050565b634e487b7160e01b600052602160045260246000fd5b6020815260006200122960208301846200230656fe60806040526000196005553480156200001757600080fd5b5060405162000d3e38038062000d3e8339810160408190526200003a9162000307565b8251839083906200005390600390602085019062000194565b5080516200006990600490602084019062000194565b5050600680546001600160a01b038716610100026001600160a81b031990911660ff85161717905550600554620000a2908590620000ac565b505050506200040f565b6001600160a01b038216620001075760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015260640160405180910390fd5b80600260008282546200011b9190620003ab565b90915550506001600160a01b038216600090815260208190526040812080548392906200014a908490620003ab565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a35050565b828054620001a290620003d2565b90600052602060002090601f016020900481019282620001c6576000855562000211565b82601f10620001e157805160ff191683800117855562000211565b8280016001018555821562000211579182015b8281111562000211578251825591602001919060010190620001f4565b506200021f92915062000223565b5090565b5b808211156200021f576000815560010162000224565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200026257600080fd5b81516001600160401b03808211156200027f576200027f6200023a565b604051601f8301601f19908116603f01168101908282118183101715620002aa57620002aa6200023a565b81604052838152602092508683858801011115620002c757600080fd5b600091505b83821015620002eb5785820183015181830184015290820190620002cc565b83821115620002fd5760008385830101525b9695505050505050565b600080600080608085870312156200031e57600080fd5b84516001600160a01b03811681146200033657600080fd5b60208601519094506001600160401b03808211156200035457600080fd5b620003628883890162000250565b945060408701519150808211156200037957600080fd5b50620003888782880162000250565b925050606085015160ff81168114620003a057600080fd5b939692955090935050565b60008219821115620003cd57634e487b7160e01b600052601160045260246000fd5b500190565b600181811c90821680620003e757607f821691505b602082108114156200040957634e487b7160e01b600052602260045260246000fd5b50919050565b61091f806200041f6000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461012d57806370a082311461014057806395d89b4114610169578063a457c2d714610171578063a9059cbb14610184578063dd62ed3e1461019757600080fd5b806306fdde03146100ae578063095ea7b3146100cc57806318160ddd146100ef57806323b872dd14610105578063313ce56714610118575b600080fd5b6100b66101d0565b6040516100c3919061073d565b60405180910390f35b6100df6100da3660046107ae565b610262565b60405190151581526020016100c3565b6100f7610278565b6040519081526020016100c3565b6100df6101133660046107d8565b6102aa565b60065460405160ff90911681526020016100c3565b6100df61013b3660046107ae565b610359565b6100f761014e366004610814565b6001600160a01b031660009081526020819052604090205490565b6100b6610395565b6100df61017f3660046107ae565b6103a4565b6100df6101923660046107ae565b61043d565b6100f76101a5366004610836565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6060600380546101df90610869565b80601f016020809104026020016040519081016040528092919081815260200182805461020b90610869565b80156102585780601f1061022d57610100808354040283529160200191610258565b820191906000526020600020905b81548152906001019060200180831161023b57829003601f168201915b5050505050905090565b600061026f33848461044a565b50600192915050565b60065461010090046001600160a01b03166000908152602081905260408120546005546102a591906108ba565b905090565b60006102b784848461056e565b6001600160a01b0384166000908152600160209081526040808320338452909152902054828110156103415760405162461bcd60e51b815260206004820152602860248201527f45524332303a207472616e7366657220616d6f756e74206578636565647320616044820152676c6c6f77616e636560c01b60648201526084015b60405180910390fd5b61034e853385840361044a565b506001949350505050565b3360008181526001602090815260408083206001600160a01b0387168452909152812054909161026f9185906103909086906108d1565b61044a565b6060600480546101df90610869565b3360009081526001602090815260408083206001600160a01b0386168452909152812054828110156104265760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610338565b610433338585840361044a565b5060019392505050565b600061026f33848461056e565b6001600160a01b0383166104ac5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610338565b6001600160a01b03821661050d5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610338565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b0383166105d25760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610338565b6001600160a01b0382166106345760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610338565b6001600160a01b038316600090815260208190526040902054818110156106ac5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610338565b6001600160a01b038085166000908152602081905260408082208585039055918516815290812080548492906106e39084906108d1565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161072f91815260200190565b60405180910390a350505050565b600060208083528351808285015260005b8181101561076a5785810183015185820160400152820161074e565b8181111561077c576000604083870101525b50601f01601f1916929092016040019392505050565b80356001600160a01b03811681146107a957600080fd5b919050565b600080604083850312156107c157600080fd5b6107ca83610792565b946020939093013593505050565b6000806000606084860312156107ed57600080fd5b6107f684610792565b925061080460208501610792565b9150604084013590509250925092565b60006020828403121561082657600080fd5b61082f82610792565b9392505050565b6000806040838503121561084957600080fd5b61085283610792565b915061086060208401610792565b90509250929050565b600181811c9082168061087d57607f821691505b6020821081141561089e57634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052601160045260246000fd5b6000828210156108cc576108cc6108a4565b500390565b600082198211156108e4576108e46108a4565b50019056fea264697066735822122030a282fb7e0b734096beb9323062edce33d11c6ccd7166512f1150282b9d8c8a64736f6c634300080a0033a2646970667358221220a343e67087c843940f5d01cf08cc6bb77beecfc24ee508b7d14cc759a0d3b10564736f6c634300080a0033

Verified Source Code Full Match

Compiler: v0.8.10+commit.fc410830 EVM: london Optimization: Yes (200 runs)
Gravity.sol 663 lines
//SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./CosmosToken.sol";

error InvalidSignature();
error InvalidValsetNonce(uint256 newNonce, uint256 currentNonce);
error InvalidBatchNonce(uint256 newNonce, uint256 currentNonce);
error InvalidLogicCallNonce(uint256 newNonce, uint256 currentNonce);
error InvalidLogicCallTransfers();
error InvalidLogicCallFees();
error InvalidSendToCosmos();
error IncorrectCheckpoint();
error MalformedNewValidatorSet();
error MalformedCurrentValidatorSet();
error MalformedBatch();
error InsufficientPower(uint256 cumulativePower, uint256 powerThreshold);
error BatchTimedOut();
error LogicCallTimedOut();

// This is being used purely to avoid stack too deep errors
struct LogicCallArgs {
	// Transfers out to the logic contract
	uint256[] transferAmounts;
	address[] transferTokenContracts;
	// The fees (transferred to msg.sender)
	uint256[] feeAmounts;
	address[] feeTokenContracts;
	// The arbitrary logic call
	address logicContractAddress;
	bytes payload;
	// Invalidation metadata
	uint256 timeOut;
	bytes32 invalidationId;
	uint256 invalidationNonce;
}

// This is used purely to avoid stack too deep errors
// represents everything about a given validator set
struct ValsetArgs {
	// the validators in this set, represented by an Ethereum address
	address[] validators;
	// the powers of the given validators in the same order as above
	uint256[] powers;
	// the nonce of this validator set
	uint256 valsetNonce;
	// the reward amount denominated in the below reward token, can be
	// set to zero
	uint256 rewardAmount;
	// the reward token, should be set to the zero address if not being used
	address rewardToken;
}

// This represents a validator signature
struct Signature {
	uint8 v;
	bytes32 r;
	bytes32 s;
}

contract Gravity is ReentrancyGuard {
	using SafeERC20 for IERC20;

	// The number of 'votes' required to execute a valset
	// update or batch execution, set to 2/3 of 2^32
	uint256 constant constant_powerThreshold = 2863311530;

	// These are updated often
	bytes32 public state_lastValsetCheckpoint;
	mapping(address => uint256) public state_lastBatchNonces;
	mapping(bytes32 => uint256) public state_invalidationMapping;
	uint256 public state_lastValsetNonce = 0;
	// event nonce zero is reserved by the Cosmos module as a special
	// value indicating that no events have yet been submitted
	uint256 public state_lastEventNonce = 1;

	// This is set once at initialization
	bytes32 public immutable state_gravityId;

	// TransactionBatchExecutedEvent and SendToCosmosEvent both include the field _eventNonce.
	// This is incremented every time one of these events is emitted. It is checked by the
	// Cosmos module to ensure that all events are received in order, and that none are lost.
	//
	// ValsetUpdatedEvent does not include the field _eventNonce because it is never submitted to the Cosmos
	// module. It is purely for the use of relayers to allow them to successfully submit batches.
	event TransactionBatchExecutedEvent(
		uint256 indexed _batchNonce,
		address indexed _token,
		uint256 _eventNonce
	);
	event SendToCosmosEvent(
		address indexed _tokenContract,
		address indexed _sender,
		string _destination,
		uint256 _amount,
		uint256 _eventNonce
	);
	event ERC20DeployedEvent(
		// FYI: Can't index on a string without doing a bunch of weird stuff
		string _cosmosDenom,
		address indexed _tokenContract,
		string _name,
		string _symbol,
		uint8 _decimals,
		uint256 _eventNonce
	);
	event ValsetUpdatedEvent(
		uint256 indexed _newValsetNonce,
		uint256 _eventNonce,
		uint256 _rewardAmount,
		address _rewardToken,
		address[] _validators,
		uint256[] _powers
	);
	event LogicCallEvent(
		bytes32 _invalidationId,
		uint256 _invalidationNonce,
		bytes _returnData,
		uint256 _eventNonce
	);

	// TEST FIXTURES
	// These are here to make it easier to measure gas usage. They should be removed before production
	function testMakeCheckpoint(ValsetArgs calldata _valsetArgs, bytes32 _gravityId) external pure {
		makeCheckpoint(_valsetArgs, _gravityId);
	}

	function testCheckValidatorSignatures(
		ValsetArgs calldata _currentValset,
		Signature[] calldata _sigs,
		bytes32 _theHash,
		uint256 _powerThreshold
	) external pure {
		checkValidatorSignatures(_currentValset, _sigs, _theHash, _powerThreshold);
	}

	// END TEST FIXTURES

	function lastBatchNonce(address _erc20Address) external view returns (uint256) {
		return state_lastBatchNonces[_erc20Address];
	}

	function lastLogicCallNonce(bytes32 _invalidation_id) external view returns (uint256) {
		return state_invalidationMapping[_invalidation_id];
	}

	// Utility function to verify geth style signatures
	function verifySig(
		address _signer,
		bytes32 _theHash,
		Signature calldata _sig
	) private pure returns (bool) {
		bytes32 messageDigest = keccak256(
			abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash)
		);
		return _signer == ECDSA.recover(messageDigest, _sig.v, _sig.r, _sig.s);
	}

	// Utility function to determine that a validator set and signatures are well formed
	function validateValset(ValsetArgs calldata _valset, Signature[] calldata _sigs) private pure {
		// Check that current validators, powers, and signatures (v,r,s) set is well-formed
		if (
			_valset.validators.length != _valset.powers.length ||
			_valset.validators.length != _sigs.length
		) {
			revert MalformedCurrentValidatorSet();
		}
	}

	// Make a new checkpoint from the supplied validator set
	// A checkpoint is a hash of all relevant information about the valset. This is stored by the contract,
	// instead of storing the information directly. This saves on storage and gas.
	// The format of the checkpoint is:
	// h(gravityId, "checkpoint", valsetNonce, validators[], powers[])
	// Where h is the keccak256 hash function.
	// The validator powers must be decreasing or equal. This is important for checking the signatures on the
	// next valset, since it allows the caller to stop verifying signatures once a quorum of signatures have been verified.
	function makeCheckpoint(ValsetArgs memory _valsetArgs, bytes32 _gravityId)
		private
		pure
		returns (bytes32)
	{
		// bytes32 encoding of the string "checkpoint"
		bytes32 methodName = 0x636865636b706f696e7400000000000000000000000000000000000000000000;

		bytes32 checkpoint = keccak256(
			abi.encode(
				_gravityId,
				methodName,
				_valsetArgs.valsetNonce,
				_valsetArgs.validators,
				_valsetArgs.powers,
				_valsetArgs.rewardAmount,
				_valsetArgs.rewardToken
			)
		);

		return checkpoint;
	}

	function checkValidatorSignatures(
		// The current validator set and their powers
		ValsetArgs calldata _currentValset,
		// The current validator's signatures
		Signature[] calldata _sigs,
		// This is what we are checking they have signed
		bytes32 _theHash,
		uint256 _powerThreshold
	) private pure {
		uint256 cumulativePower = 0;

		for (uint256 i = 0; i < _currentValset.validators.length; i++) {
			// If v is set to 0, this signifies that it was not possible to get a signature from this validator and we skip evaluation
			// (In a valid signature, it is either 27 or 28)
			if (_sigs[i].v != 0) {
				// Check that the current validator has signed off on the hash
				if (!verifySig(_currentValset.validators[i], _theHash, _sigs[i])) {
					revert InvalidSignature();
				}

				// Sum up cumulative power
				cumulativePower = cumulativePower + _currentValset.powers[i];

				// Break early to avoid wasting gas
				if (cumulativePower > _powerThreshold) {
					break;
				}
			}
		}

		// Check that there was enough power
		if (cumulativePower <= _powerThreshold) {
			revert InsufficientPower(cumulativePower, _powerThreshold);
		}
		// Success
	}

	// This updates the valset by checking that the validators in the current valset have signed off on the
	// new valset. The signatures supplied are the signatures of the current valset over the checkpoint hash
	// generated from the new valset.
	// Anyone can call this function, but they must supply valid signatures of constant_powerThreshold of the current valset over
	// the new valset.
	function updateValset(
		// The new version of the validator set
		ValsetArgs calldata _newValset,
		// The current validators that approve the change
		ValsetArgs calldata _currentValset,
		// These are arrays of the parts of the current validator's signatures
		Signature[] calldata _sigs
	) external {
		// CHECKS

		// Check that the valset nonce is greater than the old one
		if (_newValset.valsetNonce <= _currentValset.valsetNonce) {
			revert InvalidValsetNonce({
				newNonce: _newValset.valsetNonce,
				currentNonce: _currentValset.valsetNonce
			});
		}

		// Check that the valset nonce is less than a million nonces forward from the old one
		// this makes it difficult for an attacker to lock out the contract by getting a single
		// bad validator set through with uint256 max nonce
		if (_newValset.valsetNonce > _currentValset.valsetNonce + 1000000) {
			revert InvalidValsetNonce({
				newNonce: _newValset.valsetNonce,
				currentNonce: _currentValset.valsetNonce
			});
		}

		// Check that new validators and powers set is well-formed
		if (
			_newValset.validators.length != _newValset.powers.length ||
			_newValset.validators.length == 0
		) {
			revert MalformedNewValidatorSet();
		}

		// Check that current validators, powers, and signatures (v,r,s) set is well-formed
		validateValset(_currentValset, _sigs);

		// Check cumulative power to ensure the contract has sufficient power to actually
		// pass a vote
		uint256 cumulativePower = 0;
		for (uint256 i = 0; i < _newValset.powers.length; i++) {
			cumulativePower = cumulativePower + _newValset.powers[i];
			if (cumulativePower > constant_powerThreshold) {
				break;
			}
		}
		if (cumulativePower <= constant_powerThreshold) {
			revert InsufficientPower({
				cumulativePower: cumulativePower,
				powerThreshold: constant_powerThreshold
			});
		}

		// Check that the supplied current validator set matches the saved checkpoint
		if (makeCheckpoint(_currentValset, state_gravityId) != state_lastValsetCheckpoint) {
			revert IncorrectCheckpoint();
		}

		// Check that enough current validators have signed off on the new validator set
		bytes32 newCheckpoint = makeCheckpoint(_newValset, state_gravityId);

		checkValidatorSignatures(_currentValset, _sigs, newCheckpoint, constant_powerThreshold);

		// ACTIONS

		// Stored to be used next time to validate that the valset
		// supplied by the caller is correct.
		state_lastValsetCheckpoint = newCheckpoint;

		// Store new nonce
		state_lastValsetNonce = _newValset.valsetNonce;

		// Send submission reward to msg.sender if reward token is a valid value
		if (_newValset.rewardToken != address(0) && _newValset.rewardAmount != 0) {
			IERC20(_newValset.rewardToken).safeTransfer(msg.sender, _newValset.rewardAmount);
		}

		// LOGS

		state_lastEventNonce = state_lastEventNonce + 1;
		emit ValsetUpdatedEvent(
			_newValset.valsetNonce,
			state_lastEventNonce,
			_newValset.rewardAmount,
			_newValset.rewardToken,
			_newValset.validators,
			_newValset.powers
		);
	}

	// submitBatch processes a batch of Cosmos -> Ethereum transactions by sending the tokens in the transactions
	// to the destination addresses. It is approved by the current Cosmos validator set.
	// Anyone can call this function, but they must supply valid signatures of constant_powerThreshold of the current valset over
	// the batch.
	function submitBatch(
		// The validators that approve the batch
		ValsetArgs calldata _currentValset,
		// These are arrays of the parts of the validators signatures
		Signature[] calldata _sigs,
		// The batch of transactions
		uint256[] calldata _amounts,
		address[] calldata _destinations,
		uint256[] calldata _fees,
		uint256 _batchNonce,
		address _tokenContract,
		// a block height beyond which this batch is not valid
		// used to provide a fee-free timeout
		uint256 _batchTimeout
	) external nonReentrant {
		// CHECKS scoped to reduce stack depth
		{
			// Check that the batch nonce is higher than the last nonce for this token
			if (_batchNonce <= state_lastBatchNonces[_tokenContract]) {
				revert InvalidBatchNonce({
					newNonce: _batchNonce,
					currentNonce: state_lastBatchNonces[_tokenContract]
				});
			}

			// Check that the batch nonce is less than one million nonces forward from the old one
			// this makes it difficult for an attacker to lock out the contract by getting a single
			// bad batch through with uint256 max nonce
			if (_batchNonce > state_lastBatchNonces[_tokenContract] + 1000000) {
				revert InvalidBatchNonce({
					newNonce: _batchNonce,
					currentNonce: state_lastBatchNonces[_tokenContract]
				});
			}

			// Check that the block height is less than the timeout height
			if (block.number >= _batchTimeout) {
				revert BatchTimedOut();
			}

			// Check that current validators, powers, and signatures (v,r,s) set is well-formed
			validateValset(_currentValset, _sigs);

			// Check that the supplied current validator set matches the saved checkpoint
			if (makeCheckpoint(_currentValset, state_gravityId) != state_lastValsetCheckpoint) {
				revert IncorrectCheckpoint();
			}

			// Check that the transaction batch is well-formed
			if (_amounts.length != _destinations.length || _amounts.length != _fees.length) {
				revert MalformedBatch();
			}

			// Check that enough current validators have signed off on the transaction batch and valset
			checkValidatorSignatures(
				_currentValset,
				_sigs,
				// Get hash of the transaction batch and checkpoint
				keccak256(
					abi.encode(
						state_gravityId,
						// bytes32 encoding of "transactionBatch"
						0x7472616e73616374696f6e426174636800000000000000000000000000000000,
						_amounts,
						_destinations,
						_fees,
						_batchNonce,
						_tokenContract,
						_batchTimeout
					)
				),
				constant_powerThreshold
			);

			// ACTIONS

			// Store batch nonce
			state_lastBatchNonces[_tokenContract] = _batchNonce;

			{
				// Send transaction amounts to destinations
				uint256 totalFee;
				for (uint256 i = 0; i < _amounts.length; i++) {
					IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]);
					totalFee = totalFee + _fees[i];
				}

				// Send transaction fees to msg.sender
				IERC20(_tokenContract).safeTransfer(msg.sender, totalFee);
			}
		}

		// LOGS scoped to reduce stack depth
		{
			state_lastEventNonce = state_lastEventNonce + 1;
			emit TransactionBatchExecutedEvent(_batchNonce, _tokenContract, state_lastEventNonce);
		}
	}

	// This makes calls to contracts that execute arbitrary logic
	// First, it gives the logic contract some tokens
	// Then, it gives msg.senders tokens for fees
	// Then, it calls an arbitrary function on the logic contract
	// invalidationId and invalidationNonce are used for replay prevention.
	// They can be used to implement a per-token nonce by setting the token
	// address as the invalidationId and incrementing the nonce each call.
	// They can be used for nonce-free replay prevention by using a different invalidationId
	// for each call.
	function submitLogicCall(
		// The validators that approve the call
		ValsetArgs calldata _currentValset,
		// These are arrays of the parts of the validators signatures
		Signature[] calldata _sigs,
		LogicCallArgs memory _args
	) external nonReentrant {
		// CHECKS scoped to reduce stack depth
		{
			// Check that the call has not timed out
			if (block.number >= _args.timeOut) {
				revert LogicCallTimedOut();
			}

			// Check that the invalidation nonce is higher than the last nonce for this invalidation Id
			if (state_invalidationMapping[_args.invalidationId] >= _args.invalidationNonce) {
				revert InvalidLogicCallNonce({
					newNonce: _args.invalidationNonce,
					currentNonce: state_invalidationMapping[_args.invalidationId]
				});
			}

			// note the lack of nonce skipping check, it's not needed here since an attacker
			// will never be able to fill the invalidationId space, therefore a nonce lockout
			// is simply not possible

			// Check that current validators, powers, and signatures (v,r,s) set is well-formed
			validateValset(_currentValset, _sigs);

			// Check that the supplied current validator set matches the saved checkpoint
			if (makeCheckpoint(_currentValset, state_gravityId) != state_lastValsetCheckpoint) {
				revert IncorrectCheckpoint();
			}

			if (_args.transferAmounts.length != _args.transferTokenContracts.length) {
				revert InvalidLogicCallTransfers();
			}

			if (_args.feeAmounts.length != _args.feeTokenContracts.length) {
				revert InvalidLogicCallFees();
			}
		}
		{
			bytes32 argsHash = keccak256(
				abi.encode(
					state_gravityId,
					// bytes32 encoding of "logicCall"
					0x6c6f67696343616c6c0000000000000000000000000000000000000000000000,
					_args.transferAmounts,
					_args.transferTokenContracts,
					_args.feeAmounts,
					_args.feeTokenContracts,
					_args.logicContractAddress,
					_args.payload,
					_args.timeOut,
					_args.invalidationId,
					_args.invalidationNonce
				)
			);

			// Check that enough current validators have signed off on the transaction batch and valset
			checkValidatorSignatures(
				_currentValset,
				_sigs,
				// Get hash of the transaction batch and checkpoint
				argsHash,
				constant_powerThreshold
			);
		}

		// ACTIONS

		// Update invaldiation nonce
		state_invalidationMapping[_args.invalidationId] = _args.invalidationNonce;

		// Send tokens to the logic contract
		for (uint256 i = 0; i < _args.transferAmounts.length; i++) {
			IERC20(_args.transferTokenContracts[i]).safeTransfer(
				_args.logicContractAddress,
				_args.transferAmounts[i]
			);
		}

		// Make call to logic contract
		bytes memory returnData = Address.functionCall(_args.logicContractAddress, _args.payload);

		// Send fees to msg.sender
		for (uint256 i = 0; i < _args.feeAmounts.length; i++) {
			IERC20(_args.feeTokenContracts[i]).safeTransfer(msg.sender, _args.feeAmounts[i]);
		}

		// LOGS scoped to reduce stack depth
		{
			state_lastEventNonce = state_lastEventNonce + 1;
			emit LogicCallEvent(
				_args.invalidationId,
				_args.invalidationNonce,
				returnData,
				state_lastEventNonce
			);
		}
	}

	function sendToCosmos(
		address _tokenContract,
		string calldata _destination,
		uint256 _amount
	) external nonReentrant {
		// we snapshot our current balance of this token
		uint256 ourStartingBalance = IERC20(_tokenContract).balanceOf(address(this));

		// attempt to transfer the user specified amount
		IERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);

		// check what this particular ERC20 implementation actually gave us, since it doesn't
		// have to be at all related to the _amount
		uint256 ourEndingBalance = IERC20(_tokenContract).balanceOf(address(this));

		// a very strange ERC20 may trigger this condition, if we didn't have this we would
		// underflow, so it's mostly just an error message printer
		if (ourEndingBalance <= ourStartingBalance) {
			revert InvalidSendToCosmos();
		}

		state_lastEventNonce = state_lastEventNonce + 1;

		// emit to Cosmos the actual amount our balance has changed, rather than the user
		// provided amount. This protects against a small set of wonky ERC20 behavior, like
		// burning on send but not tokens that for example change every users balance every day.
		emit SendToCosmosEvent(
			_tokenContract,
			msg.sender,
			_destination,
			ourEndingBalance - ourStartingBalance,
			state_lastEventNonce
		);
	}

	function deployERC20(
		string calldata _cosmosDenom,
		string calldata _name,
		string calldata _symbol,
		uint8 _decimals
	) external {
		// Deploy an ERC20 with entire supply granted to Gravity.sol
		CosmosERC20 erc20 = new CosmosERC20(address(this), _name, _symbol, _decimals);

		// Fire an event to let the Cosmos module know
		state_lastEventNonce = state_lastEventNonce + 1;
		emit ERC20DeployedEvent(
			_cosmosDenom,
			address(erc20),
			_name,
			_symbol,
			_decimals,
			state_lastEventNonce
		);
	}

	constructor(
		// A unique identifier for this gravity instance to use in signatures
		bytes32 _gravityId,
		// The validator set, not in valset args format since many of it's
		// arguments would never be used in this case
		address[] memory _validators,
		uint256[] memory _powers
	) {
		// CHECKS

		// Check that validators, powers, and signatures (v,r,s) set is well-formed
		if (_validators.length != _powers.length || _validators.length == 0) {
			revert MalformedCurrentValidatorSet();
		}

		// Check cumulative power to ensure the contract has sufficient power to actually
		// pass a vote
		uint256 cumulativePower = 0;
		for (uint256 i = 0; i < _powers.length; i++) {
			cumulativePower = cumulativePower + _powers[i];
			if (cumulativePower > constant_powerThreshold) {
				break;
			}
		}
		if (cumulativePower <= constant_powerThreshold) {
			revert InsufficientPower({
				cumulativePower: cumulativePower,
				powerThreshold: constant_powerThreshold
			});
		}

		ValsetArgs memory _valset;
		_valset = ValsetArgs(_validators, _powers, 0, 0, address(0));

		bytes32 newCheckpoint = makeCheckpoint(_valset, _gravityId);

		// ACTIONS

		state_gravityId = _gravityId;
		state_lastValsetCheckpoint = newCheckpoint;

		// LOGS

		emit ValsetUpdatedEvent(
			state_lastValsetNonce,
			state_lastEventNonce,
			0,
			address(0),
			_validators,
			_powers
		);
	}
}
CosmosToken.sol 35 lines
//SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract CosmosERC20 is ERC20 {
	uint256 MAX_UINT = 2**256 - 1;
	uint8 private cosmosDecimals;
	address private gravityAddress;

	// This override ensures we return the proper number of decimals
	// for the cosmos token
	function decimals() public view virtual override returns (uint8) {
		return cosmosDecimals;
	}

	// This is not an accurate total supply. Instead this is the total supply
	// of the given cosmos asset on Ethereum at this moment in time. Keeping
	// a totally accurate supply would require constant updates from the Cosmos
	// side, while in theory this could be piggy-backed on some existing bridge
	// operation it's a lot of complextiy to add so we chose to forgoe it.
	function totalSupply() public view virtual override returns (uint256) {
		return MAX_UINT - balanceOf(gravityAddress);
	}

	constructor(
		address _gravityAddress,
		string memory _name,
		string memory _symbol,
		uint8 _decimals
	) ERC20(_name, _symbol) {
		cosmosDecimals = _decimals;
		gravityAddress = _gravityAddress;
		_mint(_gravityAddress, MAX_UINT);
	}
}
Address.sol 216 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
Context.sol 23 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
ERC20.sol 355 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}
IERC20.sol 81 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}
ReentrancyGuard.sol 62 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}
ECDSA.sol 219 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s;
        uint8 v;
        assembly {
            s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
            v := add(shr(255, vs), 27)
        }
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}
SafeERC20.sol 98 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
IERC20Metadata.sol 27 lines
// SPDX-License-Identifier: MIT

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);
}

Read Contract

lastBatchNonce 0x011b2174 → uint256
lastLogicCallNonce 0xc9d194d5 → uint256
state_gravityId 0xbdda81d4 → bytes32
state_invalidationMapping 0x7dfb6f86 → uint256
state_lastBatchNonces 0xdf97174b → uint256
state_lastEventNonce 0x73b20547 → uint256
state_lastValsetCheckpoint 0xf2b53307 → bytes32
state_lastValsetNonce 0xb56561fe → uint256
testCheckValidatorSignatures 0x9ec8fe03
testMakeCheckpoint 0x232dd31c

Write Contract 5 functions

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

deployERC20 0xf7955637
string _cosmosDenom
string _name
string _symbol
uint8 _decimals
sendToCosmos 0x0f212357
address _tokenContract
string _destination
uint256 _amount
submitBatch 0x18c1fc38
tuple _currentValset
tuple[] _sigs
uint256[] _amounts
address[] _destinations
uint256[] _fees
uint256 _batchNonce
address _tokenContract
uint256 _batchTimeout
submitLogicCall 0xd9e69b8d
tuple _currentValset
tuple[] _sigs
tuple _args
updateValset 0x8353ff45
tuple _newValset
tuple _currentValset
tuple[] _sigs

Recent Transactions

No transactions found for this address