ETH Price: $2,444.77 (+0.27%)
Gas: 5.75 Gwei

Transaction Decoder

Block:
22812467 at Jun-29-2025 08:28:11 PM +UTC
Transaction Fee:
0.000090456033400935 ETH $0.22
Gas Used:
251,205 Gas / 0.360088507 Gwei

Emitted Events:

328 EntryPoint.BeforeExecution( )
329 CErc20.Approval( owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, spender=0x11111112...aDB56F3ae, amount=0 )
330 DSToken.Approval( src=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, guy=0x9fdc1510...89602E0fd, wad=0 )
331 ChiToken.Approval( owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, spender=0x6637f8FF...767BF957E, value=0 )
332 VIPSwap.Approval( _owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, _spender=0x7a250d56...659F2488D, _value=0 )
333 Dai.Approval( src=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, guy=0x1E0447b1...659614e4e, wad=0 )
334 ChiToken.Approval( owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, spender=0xE4C91949...641c6eD2E, value=0 )
335 FiatTokenProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x000000000000000000000000d175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, 0x00000000000000000000000039aa39c021dfbae8fac545936693ac917d5e7563, 0000000000000000000000000000000000000000000000000000000000000000 )
336 UniswapV2Pair.Approval( owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, spender=0x7a250d56...659F2488D, value=0 )
337 UniswapV2Pair.Approval( owner=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, spender=0x0eEf70ab...9767fd940, value=0 )
338 AdminUpgradeabilityProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x000000000000000000000000d175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, 0x0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d, 0000000000000000000000000000000000000000000000000000000000000000 )
339 EntryPoint.UserOperationEvent( userOpHash=13BA026F075DE70ACB1F871CAF698C4A9440D0FB712CA23EBCECDDF460A0C804, sender=0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a, paymaster=AmbirePaymaster, nonce=0, success=True, actualGasCost=113883157695134, actualGasUsed=328742 )

Account State Difference:

  Address   Before After State Difference Code
0x00000000...b0eF1fA1c
0x00000000...6f37da032
(Entry Point 0.7.0)
110.875870300848791964 Eth110.87575641769109683 Eth0.000113883157695134
0x39AA39c0...17d5E7563
0x3b0407c6...B2F24257e
0x4337006f...17E65dF9B
(Pimlico: ERC-4337 Bundler 6)
0.352974152758382375 Eth
Nonce: 2271
0.352997579882676574 Eth
Nonce: 2272
0.000023427124294199
(Titan Builder)
13.527187448441116242 Eth13.527204070030369392 Eth0.00001662158925315
0x6B175474...495271d0F
0x89d24A6b...a23260359
0xA0b86991...E3606eB48
0xc5be99A0...72498F40c
0xd175C3f9...821FBcD4A From: 0 To: 22892026802761554885710270109960457884771093328183258989
0xD46bA6D9...d5039A161

Execution Trace

EntryPoint.handleOps( ops=, beneficiary=0x4337006f33e2940FcbEbD899bF2396117E65dF9B )
  • 0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a.19822f7c( )
    • Null: 0x000...001.c7f74f9f( )
    • AmbirePaymaster.validatePaymasterUserOp( userOp=[{name:sender, type:address, order:1, indexed:false, value:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A, valueString:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A}, {name:nonce, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:initCode, type:bytes, order:3, indexed:false, value:0x, valueString:0x}, {name:callData, type:bytes, order:4, indexed:false, value:0xABC5345E0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000B000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004E000000000000000000000000000000000000000000000000000000000000005C000000000000000000000000000000000000000000000000000000000000006A00000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000000000000000000086000000000000000000000000000000000000000000000000000000000000009400000000000000000000000000000000000000000000000000000000000000A2000000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000111111125434B319222CDBF8C261674ADB56F3AE00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000089D24A6B4CCB1B6FAA2625FE562BDD9A23260359000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000009FDC15106DA755F9FFD5B0BA9854CFB89602E0FD0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000006637F8FF227E85DD9F772D6CE489F17767BF957E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003B0407C648DD2F3EAA23FC69F952D98B2F24257E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0F000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000001E0447B19BB6ECFDAE1E4AE1694B0C3659614E4E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000E4C9194962532FEB467DCE8B3D42419641C6ED2E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B300000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000000EEF70AB0638A763ACB5178DD3C62E49767FD940000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D46BA6D942050D489DBD938A2C909A5D5039A161000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000942F9CE5D9A33A82F88D233AEB3292E6802303480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000003C3FC00000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000000000000000000000000000000000000000000767617354616E6B0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045553444300000000000000000000000000000000000000000000000000000000, valueString:0xABC5345E0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000B000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004E000000000000000000000000000000000000000000000000000000000000005C000000000000000000000000000000000000000000000000000000000000006A00000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000000000000000000086000000000000000000000000000000000000000000000000000000000000009400000000000000000000000000000000000000000000000000000000000000A2000000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000111111125434B319222CDBF8C261674ADB56F3AE00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000089D24A6B4CCB1B6FAA2625FE562BDD9A23260359000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000009FDC15106DA755F9FFD5B0BA9854CFB89602E0FD0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000006637F8FF227E85DD9F772D6CE489F17767BF957E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003B0407C648DD2F3EAA23FC69F952D98B2F24257E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0F000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000001E0447B19BB6ECFDAE1E4AE1694B0C3659614E4E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000E4C9194962532FEB467DCE8B3D42419641C6ED2E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B300000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000000EEF70AB0638A763ACB5178DD3C62E49767FD940000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D46BA6D942050D489DBD938A2C909A5D5039A161000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000942F9CE5D9A33A82F88D233AEB3292E6802303480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000003C3FC00000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000000000000000000000000000000000000000000767617354616E6B0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045553444300000000000000000000000000000000000000000000000000000000}, {name:accountGasLimits, type:bytes32, order:5, indexed:false, value:0000000000000000000000000001573D00000000000000000000000000025135, valueString:0000000000000000000000000001573D00000000000000000000000000025135}, {name:preVerificationGas, type:uint256, order:6, indexed:false, value:110453, valueString:110453}, {name:gasFees, type:bytes32, order:7, indexed:false, value:000000000000000000000000032116200000000000000000000000001567FCC5, valueString:000000000000000000000000032116200000000000000000000000001567FCC5}, {name:paymasterAndData, type:bytes, order:8, indexed:false, value:0xA8B267C68715FA1DCA055993149F30217B572CF00000000000000000000000000000912D00000000000000000000000000000001000000000000000000000000000000000000000000000000000000006861A2E9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000042B060692763F25DED5CFBECECD63FC8FC3B48A45B0D38CB4854C6F55C4C34CF9D16534A44E5865E9A11CD836C7C419B632D5B7FF9FFB8DF1652BCD9EE7CA121EA1B00000000000000000000000000000000000000000000000000000000000000, valueString:0xA8B267C68715FA1DCA055993149F30217B572CF00000000000000000000000000000912D00000000000000000000000000000001000000000000000000000000000000000000000000000000000000006861A2E9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000042B060692763F25DED5CFBECECD63FC8FC3B48A45B0D38CB4854C6F55C4C34CF9D16534A44E5865E9A11CD836C7C419B632D5B7FF9FFB8DF1652BCD9EE7CA121EA1B00000000000000000000000000000000000000000000000000000000000000}, {name:signature, type:bytes, order:9, indexed:false, value:0x9E78D1C93E2A9D449CDF745305B8006DB05991C0D6C4A9530FDE2D3E197252A2658BD70D9A5DE47AED5B027DE45E10AF568905090B77171C11C5D4EAE00F27E31C00, valueString:0x9E78D1C93E2A9D449CDF745305B8006DB05991C0D6C4A9530FDE2D3E197252A2658BD70D9A5DE47AED5B027DE45E10AF568905090B77171C11C5D4EAE00F27E31C00}], 13BA026F075DE70ACB1F871CAF698C4A9440D0FB712CA23EBCECDDF460A0C804, 139111145933097 ) => ( context=0x, validationData=2559424286143123396818290616706161663550605255908456923136 )
      • Null: 0x000...001.f93fc100( )
      • EntryPoint.innerHandleOp( callData=0xABC5345E0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000B000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000004E000000000000000000000000000000000000000000000000000000000000005C000000000000000000000000000000000000000000000000000000000000006A00000000000000000000000000000000000000000000000000000000000000780000000000000000000000000000000000000000000000000000000000000086000000000000000000000000000000000000000000000000000000000000009400000000000000000000000000000000000000000000000000000000000000A2000000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000111111125434B319222CDBF8C261674ADB56F3AE00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000089D24A6B4CCB1B6FAA2625FE562BDD9A23260359000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000009FDC15106DA755F9FFD5B0BA9854CFB89602E0FD0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000006637F8FF227E85DD9F772D6CE489F17767BF957E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003B0407C648DD2F3EAA23FC69F952D98B2F24257E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006B175474E89094C44DA98B954EEDEAC495271D0F000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000001E0447B19BB6ECFDAE1E4AE1694B0C3659614E4E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004946C0E9F43F4DEE607B0EF1FA1C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B3000000000000000000000000E4C9194962532FEB467DCE8B3D42419641C6ED2E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B300000000000000000000000039AA39C021DFBAE8FAC545936693AC917D5E7563000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C5BE99A02C6857F9EAC67BBCE58DF5572498F40C000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000000EEF70AB0638A763ACB5178DD3C62E49767FD940000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D46BA6D942050D489DBD938A2C909A5D5039A161000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000044095EA7B30000000000000000000000007A250D5630B4CF539739DF2C5DACB4C659F2488D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000942F9CE5D9A33A82F88D233AEB3292E6802303480000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000003C3FC00000000000000000000000000000000000000000000000000000000000000A0000000000000000000000000000000000000000000000000000000000000000767617354616E6B0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045553444300000000000000000000000000000000000000000000000000000000, opInfo=[{name:mUserOp, type:tuple, order:1, indexed:false, value:[{name:sender, type:address, order:1, indexed:false, value:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A, valueString:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A}, {name:nonce, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:verificationGasLimit, type:uint256, order:3, indexed:false, value:87869, valueString:87869}, {name:callGasLimit, type:uint256, order:4, indexed:false, value:151861, valueString:151861}, {name:paymasterVerificationGasLimit, type:uint256, order:5, indexed:false, value:37165, valueString:37165}, {name:paymasterPostOpGasLimit, type:uint256, order:6, indexed:false, value:1, valueString:1}, {name:preVerificationGas, type:uint256, order:7, indexed:false, value:110453, valueString:110453}, {name:paymaster, type:address, order:8, indexed:false, value:0xA8B267C68715FA1Dca055993149f30217B572Cf0, valueString:0xA8B267C68715FA1Dca055993149f30217B572Cf0}, {name:maxFeePerGas, type:uint256, order:9, indexed:false, value:359136453, valueString:359136453}, {name:maxPriorityFeePerGas, type:uint256, order:10, indexed:false, value:52500000, valueString:52500000}], valueString:[{name:sender, type:address, order:1, indexed:false, value:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A, valueString:0xd175C3f9a1FFD34B2872FB8d5b4779a821FBcD4A}, {name:nonce, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:verificationGasLimit, type:uint256, order:3, indexed:false, value:87869, valueString:87869}, {name:callGasLimit, type:uint256, order:4, indexed:false, value:151861, valueString:151861}, {name:paymasterVerificationGasLimit, type:uint256, order:5, indexed:false, value:37165, valueString:37165}, {name:paymasterPostOpGasLimit, type:uint256, order:6, indexed:false, value:1, valueString:1}, {name:preVerificationGas, type:uint256, order:7, indexed:false, value:110453, valueString:110453}, {name:paymaster, type:address, order:8, indexed:false, value:0xA8B267C68715FA1Dca055993149f30217B572Cf0, valueString:0xA8B267C68715FA1Dca055993149f30217B572Cf0}, {name:maxFeePerGas, type:uint256, order:9, indexed:false, value:359136453, valueString:359136453}, {name:maxPriorityFeePerGas, type:uint256, order:10, indexed:false, value:52500000, valueString:52500000}]}, {name:userOpHash, type:bytes32, order:2, indexed:false, value:13BA026F075DE70ACB1F871CAF698C4A9440D0FB712CA23EBCECDDF460A0C804, valueString:13BA026F075DE70ACB1F871CAF698C4A9440D0FB712CA23EBCECDDF460A0C804}, {name:prefund, type:uint256, order:3, indexed:false, value:139111145933097, valueString:139111145933097}, {name:contextOffset, type:uint256, order:4, indexed:false, value:1216, valueString:1216}, {name:preOpGas, type:uint256, order:5, indexed:false, value:198129, valueString:198129}], context=0x ) => ( actualGasCost=113883157695134 )
        • 0xd175c3f9a1ffd34b2872fb8d5b4779a821fbcd4a.abc5345e( )
          • CErc20.approve( spender=0x111111125434b319222CdBf8C261674aDB56F3ae, amount=0 ) => ( True )
          • DSToken.approve( guy=0x9fdc15106da755f9FfD5b0BA9854Cfb89602E0fd, wad=0 ) => ( True )
          • ChiToken.approve( spender=0x6637f8FF227E85Dd9F772d6Ce489F17767BF957E, amount=0 ) => ( True )
          • VIPSwap.approve( _spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, _value=0 ) => ( True )
          • Dai.approve( usr=0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e, wad=0 ) => ( True )
          • ChiToken.approve( spender=0xE4C9194962532fEB467DCe8b3d42419641c6eD2E, amount=0 ) => ( True )
          • FiatTokenProxy.095ea7b3( )
            • FiatTokenV2_2.approve( spender=0x39AA39c021dfbaE8faC545936693aC917d5E7563, value=0 ) => ( True )
            • UniswapV2Pair.approve( spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, value=0 ) => ( True )
            • UniswapV2Pair.approve( spender=0x0eEf70ab0638A763acb5178Dd3C62E49767fd940, value=0 ) => ( True )
            • AdminUpgradeabilityProxy.095ea7b3( )
              • UFragments.approve( spender=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, value=0 ) => ( True )
              • Ambire Wallet: Deployer.00000000( )
              • ETH 0.000113883157695134 Pimlico: ERC-4337 Bundler 6.CALL( )
                File 1 of 12: EntryPoint
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
                pragma solidity ^0.8.20;
                import {IERC165} from "./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);
                 * }
                 * ```
                 */
                abstract contract ERC165 is IERC165 {
                    /**
                     * @dev See {IERC165-supportsInterface}.
                     */
                    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
                        return interfaceId == type(IERC165).interfaceId;
                    }
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
                pragma solidity ^0.8.20;
                /**
                 * @dev Interface of the ERC165 standard, as defined in the
                 * https://eips.ethereum.org/EIPS/eip-165[EIP].
                 *
                 * Implementers can declare support of contract interfaces, which can then be
                 * queried by others ({ERC165Checker}).
                 *
                 * For an implementation, see {ERC165}.
                 */
                interface IERC165 {
                    /**
                     * @dev Returns true if this contract implements the interface defined by
                     * `interfaceId`. See the corresponding
                     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                     * to learn more about how these ids are created.
                     *
                     * This function call must use less than 30 000 gas.
                     */
                    function supportsInterface(bytes4 interfaceId) external view returns (bool);
                }
                // SPDX-License-Identifier: MIT
                // OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
                pragma solidity ^0.8.20;
                /**
                 * @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;
                    /**
                     * @dev Unauthorized reentrant call.
                     */
                    error ReentrancyGuardReentrantCall();
                    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
                        if (_status == ENTERED) {
                            revert ReentrancyGuardReentrantCall();
                        }
                        // 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;
                    }
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.23;
                /* solhint-disable avoid-low-level-calls */
                /* solhint-disable no-inline-assembly */
                import "../interfaces/IAccount.sol";
                import "../interfaces/IAccountExecute.sol";
                import "../interfaces/IPaymaster.sol";
                import "../interfaces/IEntryPoint.sol";
                import "../utils/Exec.sol";
                import "./StakeManager.sol";
                import "./SenderCreator.sol";
                import "./Helpers.sol";
                import "./NonceManager.sol";
                import "./UserOperationLib.sol";
                import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
                import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                /*
                 * Account-Abstraction (EIP-4337) singleton EntryPoint implementation.
                 * Only one instance required on each chain.
                 */
                /// @custom:security-contact https://bounty.ethereum.org
                contract EntryPoint is IEntryPoint, StakeManager, NonceManager, ReentrancyGuard, ERC165 {
                    using UserOperationLib for PackedUserOperation;
                    SenderCreator private immutable _senderCreator = new SenderCreator();
                    function senderCreator() internal view virtual returns (SenderCreator) {
                        return _senderCreator;
                    }
                    //compensate for innerHandleOps' emit message and deposit refund.
                    // allow some slack for future gas price changes.
                    uint256 private constant INNER_GAS_OVERHEAD = 10000;
                    // Marker for inner call revert on out of gas
                    bytes32 private constant INNER_OUT_OF_GAS = hex"deaddead";
                    bytes32 private constant INNER_REVERT_LOW_PREFUND = hex"deadaa51";
                    uint256 private constant REVERT_REASON_MAX_LEN = 2048;
                    uint256 private constant PENALTY_PERCENT = 10;
                    /// @inheritdoc IERC165
                    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                        // note: solidity "type(IEntryPoint).interfaceId" is without inherited methods but we want to check everything
                        return interfaceId == (type(IEntryPoint).interfaceId ^ type(IStakeManager).interfaceId ^ type(INonceManager).interfaceId) ||
                            interfaceId == type(IEntryPoint).interfaceId ||
                            interfaceId == type(IStakeManager).interfaceId ||
                            interfaceId == type(INonceManager).interfaceId ||
                            super.supportsInterface(interfaceId);
                    }
                    /**
                     * Compensate the caller's beneficiary address with the collected fees of all UserOperations.
                     * @param beneficiary - The address to receive the fees.
                     * @param amount      - Amount to transfer.
                     */
                    function _compensate(address payable beneficiary, uint256 amount) internal {
                        require(beneficiary != address(0), "AA90 invalid beneficiary");
                        (bool success, ) = beneficiary.call{value: amount}("");
                        require(success, "AA91 failed send to beneficiary");
                    }
                    /**
                     * Execute a user operation.
                     * @param opIndex    - Index into the opInfo array.
                     * @param userOp     - The userOp to execute.
                     * @param opInfo     - The opInfo filled by validatePrepayment for this userOp.
                     * @return collected - The total amount this userOp paid.
                     */
                    function _executeUserOp(
                        uint256 opIndex,
                        PackedUserOperation calldata userOp,
                        UserOpInfo memory opInfo
                    )
                    internal
                    returns
                    (uint256 collected) {
                        uint256 preGas = gasleft();
                        bytes memory context = getMemoryBytesFromOffset(opInfo.contextOffset);
                        bool success;
                        {
                            uint256 saveFreePtr;
                            assembly ("memory-safe") {
                                saveFreePtr := mload(0x40)
                            }
                            bytes calldata callData = userOp.callData;
                            bytes memory innerCall;
                            bytes4 methodSig;
                            assembly {
                                let len := callData.length
                                if gt(len, 3) {
                                    methodSig := calldataload(callData.offset)
                                }
                            }
                            if (methodSig == IAccountExecute.executeUserOp.selector) {
                                bytes memory executeUserOp = abi.encodeCall(IAccountExecute.executeUserOp, (userOp, opInfo.userOpHash));
                                innerCall = abi.encodeCall(this.innerHandleOp, (executeUserOp, opInfo, context));
                            } else
                            {
                                innerCall = abi.encodeCall(this.innerHandleOp, (callData, opInfo, context));
                            }
                            assembly ("memory-safe") {
                                success := call(gas(), address(), 0, add(innerCall, 0x20), mload(innerCall), 0, 32)
                                collected := mload(0)
                                mstore(0x40, saveFreePtr)
                            }
                        }
                        if (!success) {
                            bytes32 innerRevertCode;
                            assembly ("memory-safe") {
                                let len := returndatasize()
                                if eq(32,len) {
                                    returndatacopy(0, 0, 32)
                                    innerRevertCode := mload(0)
                                }
                            }
                            if (innerRevertCode == INNER_OUT_OF_GAS) {
                                // handleOps was called with gas limit too low. abort entire bundle.
                                //can only be caused by bundler (leaving not enough gas for inner call)
                                revert FailedOp(opIndex, "AA95 out of gas");
                            } else if (innerRevertCode == INNER_REVERT_LOW_PREFUND) {
                                // innerCall reverted on prefund too low. treat entire prefund as "gas cost"
                                uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;
                                uint256 actualGasCost = opInfo.prefund;
                                emitPrefundTooLow(opInfo);
                                emitUserOperationEvent(opInfo, false, actualGasCost, actualGas);
                                collected = actualGasCost;
                            } else {
                                emit PostOpRevertReason(
                                    opInfo.userOpHash,
                                    opInfo.mUserOp.sender,
                                    opInfo.mUserOp.nonce,
                                    Exec.getReturnData(REVERT_REASON_MAX_LEN)
                                );
                                uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;
                                collected = _postExecution(
                                    IPaymaster.PostOpMode.postOpReverted,
                                    opInfo,
                                    context,
                                    actualGas
                                );
                            }
                        }
                    }
                    function emitUserOperationEvent(UserOpInfo memory opInfo, bool success, uint256 actualGasCost, uint256 actualGas) internal virtual {
                        emit UserOperationEvent(
                            opInfo.userOpHash,
                            opInfo.mUserOp.sender,
                            opInfo.mUserOp.paymaster,
                            opInfo.mUserOp.nonce,
                            success,
                            actualGasCost,
                            actualGas
                        );
                    }
                    function emitPrefundTooLow(UserOpInfo memory opInfo) internal virtual {
                        emit UserOperationPrefundTooLow(
                            opInfo.userOpHash,
                            opInfo.mUserOp.sender,
                            opInfo.mUserOp.nonce
                        );
                    }
                    /// @inheritdoc IEntryPoint
                    function handleOps(
                        PackedUserOperation[] calldata ops,
                        address payable beneficiary
                    ) public nonReentrant {
                        uint256 opslen = ops.length;
                        UserOpInfo[] memory opInfos = new UserOpInfo[](opslen);
                        unchecked {
                            for (uint256 i = 0; i < opslen; i++) {
                                UserOpInfo memory opInfo = opInfos[i];
                                (
                                    uint256 validationData,
                                    uint256 pmValidationData
                                ) = _validatePrepayment(i, ops[i], opInfo);
                                _validateAccountAndPaymasterValidationData(
                                    i,
                                    validationData,
                                    pmValidationData,
                                    address(0)
                                );
                            }
                            uint256 collected = 0;
                            emit BeforeExecution();
                            for (uint256 i = 0; i < opslen; i++) {
                                collected += _executeUserOp(i, ops[i], opInfos[i]);
                            }
                            _compensate(beneficiary, collected);
                        }
                    }
                    /// @inheritdoc IEntryPoint
                    function handleAggregatedOps(
                        UserOpsPerAggregator[] calldata opsPerAggregator,
                        address payable beneficiary
                    ) public nonReentrant {
                        uint256 opasLen = opsPerAggregator.length;
                        uint256 totalOps = 0;
                        for (uint256 i = 0; i < opasLen; i++) {
                            UserOpsPerAggregator calldata opa = opsPerAggregator[i];
                            PackedUserOperation[] calldata ops = opa.userOps;
                            IAggregator aggregator = opa.aggregator;
                            //address(1) is special marker of "signature error"
                            require(
                                address(aggregator) != address(1),
                                "AA96 invalid aggregator"
                            );
                            if (address(aggregator) != address(0)) {
                                // solhint-disable-next-line no-empty-blocks
                                try aggregator.validateSignatures(ops, opa.signature) {} catch {
                                    revert SignatureValidationFailed(address(aggregator));
                                }
                            }
                            totalOps += ops.length;
                        }
                        UserOpInfo[] memory opInfos = new UserOpInfo[](totalOps);
                        uint256 opIndex = 0;
                        for (uint256 a = 0; a < opasLen; a++) {
                            UserOpsPerAggregator calldata opa = opsPerAggregator[a];
                            PackedUserOperation[] calldata ops = opa.userOps;
                            IAggregator aggregator = opa.aggregator;
                            uint256 opslen = ops.length;
                            for (uint256 i = 0; i < opslen; i++) {
                                UserOpInfo memory opInfo = opInfos[opIndex];
                                (
                                    uint256 validationData,
                                    uint256 paymasterValidationData
                                ) = _validatePrepayment(opIndex, ops[i], opInfo);
                                _validateAccountAndPaymasterValidationData(
                                    i,
                                    validationData,
                                    paymasterValidationData,
                                    address(aggregator)
                                );
                                opIndex++;
                            }
                        }
                        emit BeforeExecution();
                        uint256 collected = 0;
                        opIndex = 0;
                        for (uint256 a = 0; a < opasLen; a++) {
                            UserOpsPerAggregator calldata opa = opsPerAggregator[a];
                            emit SignatureAggregatorChanged(address(opa.aggregator));
                            PackedUserOperation[] calldata ops = opa.userOps;
                            uint256 opslen = ops.length;
                            for (uint256 i = 0; i < opslen; i++) {
                                collected += _executeUserOp(opIndex, ops[i], opInfos[opIndex]);
                                opIndex++;
                            }
                        }
                        emit SignatureAggregatorChanged(address(0));
                        _compensate(beneficiary, collected);
                    }
                    /**
                     * A memory copy of UserOp static fields only.
                     * Excluding: callData, initCode and signature. Replacing paymasterAndData with paymaster.
                     */
                    struct MemoryUserOp {
                        address sender;
                        uint256 nonce;
                        uint256 verificationGasLimit;
                        uint256 callGasLimit;
                        uint256 paymasterVerificationGasLimit;
                        uint256 paymasterPostOpGasLimit;
                        uint256 preVerificationGas;
                        address paymaster;
                        uint256 maxFeePerGas;
                        uint256 maxPriorityFeePerGas;
                    }
                    struct UserOpInfo {
                        MemoryUserOp mUserOp;
                        bytes32 userOpHash;
                        uint256 prefund;
                        uint256 contextOffset;
                        uint256 preOpGas;
                    }
                    /**
                     * Inner function to handle a UserOperation.
                     * Must be declared "external" to open a call context, but it can only be called by handleOps.
                     * @param callData - The callData to execute.
                     * @param opInfo   - The UserOpInfo struct.
                     * @param context  - The context bytes.
                     * @return actualGasCost - the actual cost in eth this UserOperation paid for gas
                     */
                    function innerHandleOp(
                        bytes memory callData,
                        UserOpInfo memory opInfo,
                        bytes calldata context
                    ) external returns (uint256 actualGasCost) {
                        uint256 preGas = gasleft();
                        require(msg.sender == address(this), "AA92 internal call only");
                        MemoryUserOp memory mUserOp = opInfo.mUserOp;
                        uint256 callGasLimit = mUserOp.callGasLimit;
                        unchecked {
                            // handleOps was called with gas limit too low. abort entire bundle.
                            if (
                                gasleft() * 63 / 64 <
                                callGasLimit +
                                mUserOp.paymasterPostOpGasLimit +
                                INNER_GAS_OVERHEAD
                            ) {
                                assembly ("memory-safe") {
                                    mstore(0, INNER_OUT_OF_GAS)
                                    revert(0, 32)
                                }
                            }
                        }
                        IPaymaster.PostOpMode mode = IPaymaster.PostOpMode.opSucceeded;
                        if (callData.length > 0) {
                            bool success = Exec.call(mUserOp.sender, 0, callData, callGasLimit);
                            if (!success) {
                                bytes memory result = Exec.getReturnData(REVERT_REASON_MAX_LEN);
                                if (result.length > 0) {
                                    emit UserOperationRevertReason(
                                        opInfo.userOpHash,
                                        mUserOp.sender,
                                        mUserOp.nonce,
                                        result
                                    );
                                }
                                mode = IPaymaster.PostOpMode.opReverted;
                            }
                        }
                        unchecked {
                            uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;
                            return _postExecution(mode, opInfo, context, actualGas);
                        }
                    }
                    /// @inheritdoc IEntryPoint
                    function getUserOpHash(
                        PackedUserOperation calldata userOp
                    ) public view returns (bytes32) {
                        return
                            keccak256(abi.encode(userOp.hash(), address(this), block.chainid));
                    }
                    /**
                     * Copy general fields from userOp into the memory opInfo structure.
                     * @param userOp  - The user operation.
                     * @param mUserOp - The memory user operation.
                     */
                    function _copyUserOpToMemory(
                        PackedUserOperation calldata userOp,
                        MemoryUserOp memory mUserOp
                    ) internal pure {
                        mUserOp.sender = userOp.sender;
                        mUserOp.nonce = userOp.nonce;
                        (mUserOp.verificationGasLimit, mUserOp.callGasLimit) = UserOperationLib.unpackUints(userOp.accountGasLimits);
                        mUserOp.preVerificationGas = userOp.preVerificationGas;
                        (mUserOp.maxPriorityFeePerGas, mUserOp.maxFeePerGas) = UserOperationLib.unpackUints(userOp.gasFees);
                        bytes calldata paymasterAndData = userOp.paymasterAndData;
                        if (paymasterAndData.length > 0) {
                            require(
                                paymasterAndData.length >= UserOperationLib.PAYMASTER_DATA_OFFSET,
                                "AA93 invalid paymasterAndData"
                            );
                            (mUserOp.paymaster, mUserOp.paymasterVerificationGasLimit, mUserOp.paymasterPostOpGasLimit) = UserOperationLib.unpackPaymasterStaticFields(paymasterAndData);
                        } else {
                            mUserOp.paymaster = address(0);
                            mUserOp.paymasterVerificationGasLimit = 0;
                            mUserOp.paymasterPostOpGasLimit = 0;
                        }
                    }
                    /**
                     * Get the required prefunded gas fee amount for an operation.
                     * @param mUserOp - The user operation in memory.
                     */
                    function _getRequiredPrefund(
                        MemoryUserOp memory mUserOp
                    ) internal pure returns (uint256 requiredPrefund) {
                        unchecked {
                            uint256 requiredGas = mUserOp.verificationGasLimit +
                                mUserOp.callGasLimit +
                                mUserOp.paymasterVerificationGasLimit +
                                mUserOp.paymasterPostOpGasLimit +
                                mUserOp.preVerificationGas;
                            requiredPrefund = requiredGas * mUserOp.maxFeePerGas;
                        }
                    }
                    /**
                     * Create sender smart contract account if init code is provided.
                     * @param opIndex  - The operation index.
                     * @param opInfo   - The operation info.
                     * @param initCode - The init code for the smart contract account.
                     */
                    function _createSenderIfNeeded(
                        uint256 opIndex,
                        UserOpInfo memory opInfo,
                        bytes calldata initCode
                    ) internal {
                        if (initCode.length != 0) {
                            address sender = opInfo.mUserOp.sender;
                            if (sender.code.length != 0)
                                revert FailedOp(opIndex, "AA10 sender already constructed");
                            address sender1 = senderCreator().createSender{
                                gas: opInfo.mUserOp.verificationGasLimit
                            }(initCode);
                            if (sender1 == address(0))
                                revert FailedOp(opIndex, "AA13 initCode failed or OOG");
                            if (sender1 != sender)
                                revert FailedOp(opIndex, "AA14 initCode must return sender");
                            if (sender1.code.length == 0)
                                revert FailedOp(opIndex, "AA15 initCode must create sender");
                            address factory = address(bytes20(initCode[0:20]));
                            emit AccountDeployed(
                                opInfo.userOpHash,
                                sender,
                                factory,
                                opInfo.mUserOp.paymaster
                            );
                        }
                    }
                    /// @inheritdoc IEntryPoint
                    function getSenderAddress(bytes calldata initCode) public {
                        address sender = senderCreator().createSender(initCode);
                        revert SenderAddressResult(sender);
                    }
                    /**
                     * Call account.validateUserOp.
                     * Revert (with FailedOp) in case validateUserOp reverts, or account didn't send required prefund.
                     * Decrement account's deposit if needed.
                     * @param opIndex         - The operation index.
                     * @param op              - The user operation.
                     * @param opInfo          - The operation info.
                     * @param requiredPrefund - The required prefund amount.
                     */
                    function _validateAccountPrepayment(
                        uint256 opIndex,
                        PackedUserOperation calldata op,
                        UserOpInfo memory opInfo,
                        uint256 requiredPrefund,
                        uint256 verificationGasLimit
                    )
                        internal
                        returns (
                            uint256 validationData
                        )
                    {
                        unchecked {
                            MemoryUserOp memory mUserOp = opInfo.mUserOp;
                            address sender = mUserOp.sender;
                            _createSenderIfNeeded(opIndex, opInfo, op.initCode);
                            address paymaster = mUserOp.paymaster;
                            uint256 missingAccountFunds = 0;
                            if (paymaster == address(0)) {
                                uint256 bal = balanceOf(sender);
                                missingAccountFunds = bal > requiredPrefund
                                    ? 0
                                    : requiredPrefund - bal;
                            }
                            try
                                IAccount(sender).validateUserOp{
                                    gas: verificationGasLimit
                                }(op, opInfo.userOpHash, missingAccountFunds)
                            returns (uint256 _validationData) {
                                validationData = _validationData;
                            } catch {
                                revert FailedOpWithRevert(opIndex, "AA23 reverted", Exec.getReturnData(REVERT_REASON_MAX_LEN));
                            }
                            if (paymaster == address(0)) {
                                DepositInfo storage senderInfo = deposits[sender];
                                uint256 deposit = senderInfo.deposit;
                                if (requiredPrefund > deposit) {
                                    revert FailedOp(opIndex, "AA21 didn't pay prefund");
                                }
                                senderInfo.deposit = deposit - requiredPrefund;
                            }
                        }
                    }
                    /**
                     * In case the request has a paymaster:
                     *  - Validate paymaster has enough deposit.
                     *  - Call paymaster.validatePaymasterUserOp.
                     *  - Revert with proper FailedOp in case paymaster reverts.
                     *  - Decrement paymaster's deposit.
                     * @param opIndex                            - The operation index.
                     * @param op                                 - The user operation.
                     * @param opInfo                             - The operation info.
                     * @param requiredPreFund                    - The required prefund amount.
                     */
                    function _validatePaymasterPrepayment(
                        uint256 opIndex,
                        PackedUserOperation calldata op,
                        UserOpInfo memory opInfo,
                        uint256 requiredPreFund
                    ) internal returns (bytes memory context, uint256 validationData) {
                        unchecked {
                            uint256 preGas = gasleft();
                            MemoryUserOp memory mUserOp = opInfo.mUserOp;
                            address paymaster = mUserOp.paymaster;
                            DepositInfo storage paymasterInfo = deposits[paymaster];
                            uint256 deposit = paymasterInfo.deposit;
                            if (deposit < requiredPreFund) {
                                revert FailedOp(opIndex, "AA31 paymaster deposit too low");
                            }
                            paymasterInfo.deposit = deposit - requiredPreFund;
                            uint256 pmVerificationGasLimit = mUserOp.paymasterVerificationGasLimit;
                            try
                                IPaymaster(paymaster).validatePaymasterUserOp{gas: pmVerificationGasLimit}(
                                    op,
                                    opInfo.userOpHash,
                                    requiredPreFund
                                )
                            returns (bytes memory _context, uint256 _validationData) {
                                context = _context;
                                validationData = _validationData;
                            } catch {
                                revert FailedOpWithRevert(opIndex, "AA33 reverted", Exec.getReturnData(REVERT_REASON_MAX_LEN));
                            }
                            if (preGas - gasleft() > pmVerificationGasLimit) {
                                revert FailedOp(opIndex, "AA36 over paymasterVerificationGasLimit");
                            }
                        }
                    }
                    /**
                     * Revert if either account validationData or paymaster validationData is expired.
                     * @param opIndex                 - The operation index.
                     * @param validationData          - The account validationData.
                     * @param paymasterValidationData - The paymaster validationData.
                     * @param expectedAggregator      - The expected aggregator.
                     */
                    function _validateAccountAndPaymasterValidationData(
                        uint256 opIndex,
                        uint256 validationData,
                        uint256 paymasterValidationData,
                        address expectedAggregator
                    ) internal view {
                        (address aggregator, bool outOfTimeRange) = _getValidationData(
                            validationData
                        );
                        if (expectedAggregator != aggregator) {
                            revert FailedOp(opIndex, "AA24 signature error");
                        }
                        if (outOfTimeRange) {
                            revert FailedOp(opIndex, "AA22 expired or not due");
                        }
                        // pmAggregator is not a real signature aggregator: we don't have logic to handle it as address.
                        // Non-zero address means that the paymaster fails due to some signature check (which is ok only during estimation).
                        address pmAggregator;
                        (pmAggregator, outOfTimeRange) = _getValidationData(
                            paymasterValidationData
                        );
                        if (pmAggregator != address(0)) {
                            revert FailedOp(opIndex, "AA34 signature error");
                        }
                        if (outOfTimeRange) {
                            revert FailedOp(opIndex, "AA32 paymaster expired or not due");
                        }
                    }
                    /**
                     * Parse validationData into its components.
                     * @param validationData - The packed validation data (sigFailed, validAfter, validUntil).
                     * @return aggregator the aggregator of the validationData
                     * @return outOfTimeRange true if current time is outside the time range of this validationData.
                     */
                    function _getValidationData(
                        uint256 validationData
                    ) internal view returns (address aggregator, bool outOfTimeRange) {
                        if (validationData == 0) {
                            return (address(0), false);
                        }
                        ValidationData memory data = _parseValidationData(validationData);
                        // solhint-disable-next-line not-rely-on-time
                        outOfTimeRange = block.timestamp > data.validUntil || block.timestamp < data.validAfter;
                        aggregator = data.aggregator;
                    }
                    /**
                     * Validate account and paymaster (if defined) and
                     * also make sure total validation doesn't exceed verificationGasLimit.
                     * This method is called off-chain (simulateValidation()) and on-chain (from handleOps)
                     * @param opIndex - The index of this userOp into the "opInfos" array.
                     * @param userOp  - The userOp to validate.
                     */
                    function _validatePrepayment(
                        uint256 opIndex,
                        PackedUserOperation calldata userOp,
                        UserOpInfo memory outOpInfo
                    )
                        internal
                        returns (uint256 validationData, uint256 paymasterValidationData)
                    {
                        uint256 preGas = gasleft();
                        MemoryUserOp memory mUserOp = outOpInfo.mUserOp;
                        _copyUserOpToMemory(userOp, mUserOp);
                        outOpInfo.userOpHash = getUserOpHash(userOp);
                        // Validate all numeric values in userOp are well below 128 bit, so they can safely be added
                        // and multiplied without causing overflow.
                        uint256 verificationGasLimit = mUserOp.verificationGasLimit;
                        uint256 maxGasValues = mUserOp.preVerificationGas |
                            verificationGasLimit |
                            mUserOp.callGasLimit |
                            mUserOp.paymasterVerificationGasLimit |
                            mUserOp.paymasterPostOpGasLimit |
                            mUserOp.maxFeePerGas |
                            mUserOp.maxPriorityFeePerGas;
                        require(maxGasValues <= type(uint120).max, "AA94 gas values overflow");
                        uint256 requiredPreFund = _getRequiredPrefund(mUserOp);
                        validationData = _validateAccountPrepayment(
                            opIndex,
                            userOp,
                            outOpInfo,
                            requiredPreFund,
                            verificationGasLimit
                        );
                        if (!_validateAndUpdateNonce(mUserOp.sender, mUserOp.nonce)) {
                            revert FailedOp(opIndex, "AA25 invalid account nonce");
                        }
                        unchecked {
                            if (preGas - gasleft() > verificationGasLimit) {
                                revert FailedOp(opIndex, "AA26 over verificationGasLimit");
                            }
                        }
                        bytes memory context;
                        if (mUserOp.paymaster != address(0)) {
                            (context, paymasterValidationData) = _validatePaymasterPrepayment(
                                opIndex,
                                userOp,
                                outOpInfo,
                                requiredPreFund
                            );
                        }
                        unchecked {
                            outOpInfo.prefund = requiredPreFund;
                            outOpInfo.contextOffset = getOffsetOfMemoryBytes(context);
                            outOpInfo.preOpGas = preGas - gasleft() + userOp.preVerificationGas;
                        }
                    }
                    /**
                     * Process post-operation, called just after the callData is executed.
                     * If a paymaster is defined and its validation returned a non-empty context, its postOp is called.
                     * The excess amount is refunded to the account (or paymaster - if it was used in the request).
                     * @param mode      - Whether is called from innerHandleOp, or outside (postOpReverted).
                     * @param opInfo    - UserOp fields and info collected during validation.
                     * @param context   - The context returned in validatePaymasterUserOp.
                     * @param actualGas - The gas used so far by this user operation.
                     */
                    function _postExecution(
                        IPaymaster.PostOpMode mode,
                        UserOpInfo memory opInfo,
                        bytes memory context,
                        uint256 actualGas
                    ) private returns (uint256 actualGasCost) {
                        uint256 preGas = gasleft();
                        unchecked {
                            address refundAddress;
                            MemoryUserOp memory mUserOp = opInfo.mUserOp;
                            uint256 gasPrice = getUserOpGasPrice(mUserOp);
                            address paymaster = mUserOp.paymaster;
                            if (paymaster == address(0)) {
                                refundAddress = mUserOp.sender;
                            } else {
                                refundAddress = paymaster;
                                if (context.length > 0) {
                                    actualGasCost = actualGas * gasPrice;
                                    if (mode != IPaymaster.PostOpMode.postOpReverted) {
                                        try IPaymaster(paymaster).postOp{
                                            gas: mUserOp.paymasterPostOpGasLimit
                                        }(mode, context, actualGasCost, gasPrice)
                                        // solhint-disable-next-line no-empty-blocks
                                        {} catch {
                                            bytes memory reason = Exec.getReturnData(REVERT_REASON_MAX_LEN);
                                            revert PostOpReverted(reason);
                                        }
                                    }
                                }
                            }
                            actualGas += preGas - gasleft();
                            // Calculating a penalty for unused execution gas
                            {
                                uint256 executionGasLimit = mUserOp.callGasLimit + mUserOp.paymasterPostOpGasLimit;
                                uint256 executionGasUsed = actualGas - opInfo.preOpGas;
                                // this check is required for the gas used within EntryPoint and not covered by explicit gas limits
                                if (executionGasLimit > executionGasUsed) {
                                    uint256 unusedGas = executionGasLimit - executionGasUsed;
                                    uint256 unusedGasPenalty = (unusedGas * PENALTY_PERCENT) / 100;
                                    actualGas += unusedGasPenalty;
                                }
                            }
                            actualGasCost = actualGas * gasPrice;
                            uint256 prefund = opInfo.prefund;
                            if (prefund < actualGasCost) {
                                if (mode == IPaymaster.PostOpMode.postOpReverted) {
                                    actualGasCost = prefund;
                                    emitPrefundTooLow(opInfo);
                                    emitUserOperationEvent(opInfo, false, actualGasCost, actualGas);
                                } else {
                                    assembly ("memory-safe") {
                                        mstore(0, INNER_REVERT_LOW_PREFUND)
                                        revert(0, 32)
                                    }
                                }
                            } else {
                                uint256 refund = prefund - actualGasCost;
                                _incrementDeposit(refundAddress, refund);
                                bool success = mode == IPaymaster.PostOpMode.opSucceeded;
                                emitUserOperationEvent(opInfo, success, actualGasCost, actualGas);
                            }
                        } // unchecked
                    }
                    /**
                     * The gas price this UserOp agrees to pay.
                     * Relayer/block builder might submit the TX with higher priorityFee, but the user should not.
                     * @param mUserOp - The userOp to get the gas price from.
                     */
                    function getUserOpGasPrice(
                        MemoryUserOp memory mUserOp
                    ) internal view returns (uint256) {
                        unchecked {
                            uint256 maxFeePerGas = mUserOp.maxFeePerGas;
                            uint256 maxPriorityFeePerGas = mUserOp.maxPriorityFeePerGas;
                            if (maxFeePerGas == maxPriorityFeePerGas) {
                                //legacy mode (for networks that don't support basefee opcode)
                                return maxFeePerGas;
                            }
                            return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);
                        }
                    }
                    /**
                     * The offset of the given bytes in memory.
                     * @param data - The bytes to get the offset of.
                     */
                    function getOffsetOfMemoryBytes(
                        bytes memory data
                    ) internal pure returns (uint256 offset) {
                        assembly {
                            offset := data
                        }
                    }
                    /**
                     * The bytes in memory at the given offset.
                     * @param offset - The offset to get the bytes from.
                     */
                    function getMemoryBytesFromOffset(
                        uint256 offset
                    ) internal pure returns (bytes memory data) {
                        assembly ("memory-safe") {
                            data := offset
                        }
                    }
                    /// @inheritdoc IEntryPoint
                    function delegateAndRevert(address target, bytes calldata data) external {
                        (bool success, bytes memory ret) = target.delegatecall(data);
                        revert DelegateAndRevert(success, ret);
                    }
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.23;
                /* solhint-disable no-inline-assembly */
                 /*
                  * For simulation purposes, validateUserOp (and validatePaymasterUserOp)
                  * must return this value in case of signature failure, instead of revert.
                  */
                uint256 constant SIG_VALIDATION_FAILED = 1;
                /*
                 * For simulation purposes, validateUserOp (and validatePaymasterUserOp)
                 * return this value on success.
                 */
                uint256 constant SIG_VALIDATION_SUCCESS = 0;
                /**
                 * Returned data from validateUserOp.
                 * validateUserOp returns a uint256, which is created by `_packedValidationData` and
                 * parsed by `_parseValidationData`.
                 * @param aggregator  - address(0) - The account validated the signature by itself.
                 *                      address(1) - The account failed to validate the signature.
                 *                      otherwise - This is an address of a signature aggregator that must
                 *                                  be used to validate the signature.
                 * @param validAfter  - This UserOp is valid only after this timestamp.
                 * @param validaUntil - This UserOp is valid only up to this timestamp.
                 */
                struct ValidationData {
                    address aggregator;
                    uint48 validAfter;
                    uint48 validUntil;
                }
                /**
                 * Extract sigFailed, validAfter, validUntil.
                 * Also convert zero validUntil to type(uint48).max.
                 * @param validationData - The packed validation data.
                 */
                function _parseValidationData(
                    uint256 validationData
                ) pure returns (ValidationData memory data) {
                    address aggregator = address(uint160(validationData));
                    uint48 validUntil = uint48(validationData >> 160);
                    if (validUntil == 0) {
                        validUntil = type(uint48).max;
                    }
                    uint48 validAfter = uint48(validationData >> (48 + 160));
                    return ValidationData(aggregator, validAfter, validUntil);
                }
                /**
                 * Helper to pack the return value for validateUserOp.
                 * @param data - The ValidationData to pack.
                 */
                function _packValidationData(
                    ValidationData memory data
                ) pure returns (uint256) {
                    return
                        uint160(data.aggregator) |
                        (uint256(data.validUntil) << 160) |
                        (uint256(data.validAfter) << (160 + 48));
                }
                /**
                 * Helper to pack the return value for validateUserOp, when not using an aggregator.
                 * @param sigFailed  - True for signature failure, false for success.
                 * @param validUntil - Last timestamp this UserOperation is valid (or zero for infinite).
                 * @param validAfter - First timestamp this UserOperation is valid.
                 */
                function _packValidationData(
                    bool sigFailed,
                    uint48 validUntil,
                    uint48 validAfter
                ) pure returns (uint256) {
                    return
                        (sigFailed ? 1 : 0) |
                        (uint256(validUntil) << 160) |
                        (uint256(validAfter) << (160 + 48));
                }
                /**
                 * keccak function over calldata.
                 * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.
                 */
                    function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {
                        assembly ("memory-safe") {
                            let mem := mload(0x40)
                            let len := data.length
                            calldatacopy(mem, data.offset, len)
                            ret := keccak256(mem, len)
                        }
                    }
                /**
                 * The minimum of two numbers.
                 * @param a - First number.
                 * @param b - Second number.
                 */
                    function min(uint256 a, uint256 b) pure returns (uint256) {
                        return a < b ? a : b;
                    }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.23;
                import "../interfaces/INonceManager.sol";
                /**
                 * nonce management functionality
                 */
                abstract contract NonceManager is INonceManager {
                    /**
                     * The next valid sequence number for a given nonce key.
                     */
                    mapping(address => mapping(uint192 => uint256)) public nonceSequenceNumber;
                    /// @inheritdoc INonceManager
                    function getNonce(address sender, uint192 key)
                    public view override returns (uint256 nonce) {
                        return nonceSequenceNumber[sender][key] | (uint256(key) << 64);
                    }
                    // allow an account to manually increment its own nonce.
                    // (mainly so that during construction nonce can be made non-zero,
                    // to "absorb" the gas cost of first nonce increment to 1st transaction (construction),
                    // not to 2nd transaction)
                    function incrementNonce(uint192 key) public override {
                        nonceSequenceNumber[msg.sender][key]++;
                    }
                    /**
                     * validate nonce uniqueness for this account.
                     * called just after validateUserOp()
                     * @return true if the nonce was incremented successfully.
                     *         false if the current nonce doesn't match the given one.
                     */
                    function _validateAndUpdateNonce(address sender, uint256 nonce) internal returns (bool) {
                        uint192 key = uint192(nonce >> 64);
                        uint64 seq = uint64(nonce);
                        return nonceSequenceNumber[sender][key]++ == seq;
                    }
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.23;
                /**
                 * Helper contract for EntryPoint, to call userOp.initCode from a "neutral" address,
                 * which is explicitly not the entryPoint itself.
                 */
                contract SenderCreator {
                    /**
                     * Call the "initCode" factory to create and return the sender account address.
                     * @param initCode - The initCode value from a UserOp. contains 20 bytes of factory address,
                     *                   followed by calldata.
                     * @return sender  - The returned address of the created account, or zero address on failure.
                     */
                    function createSender(
                        bytes calldata initCode
                    ) external returns (address sender) {
                        address factory = address(bytes20(initCode[0:20]));
                        bytes memory initCallData = initCode[20:];
                        bool success;
                        /* solhint-disable no-inline-assembly */
                        assembly ("memory-safe") {
                            success := call(
                                gas(),
                                factory,
                                0,
                                add(initCallData, 0x20),
                                mload(initCallData),
                                0,
                                32
                            )
                            sender := mload(0)
                        }
                        if (!success) {
                            sender = address(0);
                        }
                    }
                }
                // SPDX-License-Identifier: GPL-3.0-only
                pragma solidity ^0.8.23;
                import "../interfaces/IStakeManager.sol";
                /* solhint-disable avoid-low-level-calls */
                /* solhint-disable not-rely-on-time */
                /**
                 * Manage deposits and stakes.
                 * Deposit is just a balance used to pay for UserOperations (either by a paymaster or an account).
                 * Stake is value locked for at least "unstakeDelay" by a paymaster.
                 */
                abstract contract StakeManager is IStakeManager {
                    /// maps paymaster to their deposits and stakes
                    mapping(address => DepositInfo) public deposits;
                    /// @inheritdoc IStakeManager
                    function getDepositInfo(
                        address account
                    ) public view returns (DepositInfo memory info) {
                        return deposits[account];
                    }
                    /**
                     * Internal method to return just the stake info.
                     * @param addr - The account to query.
                     */
                    function _getStakeInfo(
                        address addr
                    ) internal view returns (StakeInfo memory info) {
                        DepositInfo storage depositInfo = deposits[addr];
                        info.stake = depositInfo.stake;
                        info.unstakeDelaySec = depositInfo.unstakeDelaySec;
                    }
                    /// @inheritdoc IStakeManager
                    function balanceOf(address account) public view returns (uint256) {
                        return deposits[account].deposit;
                    }
                    receive() external payable {
                        depositTo(msg.sender);
                    }
                    /**
                     * Increments an account's deposit.
                     * @param account - The account to increment.
                     * @param amount  - The amount to increment by.
                     * @return the updated deposit of this account
                     */
                    function _incrementDeposit(address account, uint256 amount) internal returns (uint256) {
                        DepositInfo storage info = deposits[account];
                        uint256 newAmount = info.deposit + amount;
                        info.deposit = newAmount;
                        return newAmount;
                    }
                    /**
                     * Add to the deposit of the given account.
                     * @param account - The account to add to.
                     */
                    function depositTo(address account) public virtual payable {
                        uint256 newDeposit = _incrementDeposit(account, msg.value);
                        emit Deposited(account, newDeposit);
                    }
                    /**
                     * Add to the account's stake - amount and delay
                     * any pending unstake is first cancelled.
                     * @param unstakeDelaySec The new lock duration before the deposit can be withdrawn.
                     */
                    function addStake(uint32 unstakeDelaySec) public payable {
                        DepositInfo storage info = deposits[msg.sender];
                        require(unstakeDelaySec > 0, "must specify unstake delay");
                        require(
                            unstakeDelaySec >= info.unstakeDelaySec,
                            "cannot decrease unstake time"
                        );
                        uint256 stake = info.stake + msg.value;
                        require(stake > 0, "no stake specified");
                        require(stake <= type(uint112).max, "stake overflow");
                        deposits[msg.sender] = DepositInfo(
                            info.deposit,
                            true,
                            uint112(stake),
                            unstakeDelaySec,
                            0
                        );
                        emit StakeLocked(msg.sender, stake, unstakeDelaySec);
                    }
                    /**
                     * Attempt to unlock the stake.
                     * The value can be withdrawn (using withdrawStake) after the unstake delay.
                     */
                    function unlockStake() external {
                        DepositInfo storage info = deposits[msg.sender];
                        require(info.unstakeDelaySec != 0, "not staked");
                        require(info.staked, "already unstaking");
                        uint48 withdrawTime = uint48(block.timestamp) + info.unstakeDelaySec;
                        info.withdrawTime = withdrawTime;
                        info.staked = false;
                        emit StakeUnlocked(msg.sender, withdrawTime);
                    }
                    /**
                     * Withdraw from the (unlocked) stake.
                     * Must first call unlockStake and wait for the unstakeDelay to pass.
                     * @param withdrawAddress - The address to send withdrawn value.
                     */
                    function withdrawStake(address payable withdrawAddress) external {
                        DepositInfo storage info = deposits[msg.sender];
                        uint256 stake = info.stake;
                        require(stake > 0, "No stake to withdraw");
                        require(info.withdrawTime > 0, "must call unlockStake() first");
                        require(
                            info.withdrawTime <= block.timestamp,
                            "Stake withdrawal is not due"
                        );
                        info.unstakeDelaySec = 0;
                        info.withdrawTime = 0;
                        info.stake = 0;
                        emit StakeWithdrawn(msg.sender, withdrawAddress, stake);
                        (bool success,) = withdrawAddress.call{value: stake}("");
                        require(success, "failed to withdraw stake");
                    }
                    /**
                     * Withdraw from the deposit.
                     * @param withdrawAddress - The address to send withdrawn value.
                     * @param withdrawAmount  - The amount to withdraw.
                     */
                    function withdrawTo(
                        address payable withdrawAddress,
                        uint256 withdrawAmount
                    ) external {
                        DepositInfo storage info = deposits[msg.sender];
                        require(withdrawAmount <= info.deposit, "Withdraw amount too large");
                        info.deposit = info.deposit - withdrawAmount;
                        emit Withdrawn(msg.sender, withdrawAddress, withdrawAmount);
                        (bool success,) = withdrawAddress.call{value: withdrawAmount}("");
                        require(success, "failed to withdraw");
                    }
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.23;
                /* solhint-disable no-inline-assembly */
                import "../interfaces/PackedUserOperation.sol";
                import {calldataKeccak, min} from "./Helpers.sol";
                /**
                 * Utility functions helpful when working with UserOperation structs.
                 */
                library UserOperationLib {
                    uint256 public constant PAYMASTER_VALIDATION_GAS_OFFSET = 20;
                    uint256 public constant PAYMASTER_POSTOP_GAS_OFFSET = 36;
                    uint256 public constant PAYMASTER_DATA_OFFSET = 52;
                    /**
                     * Get sender from user operation data.
                     * @param userOp - The user operation data.
                     */
                    function getSender(
                        PackedUserOperation calldata userOp
                    ) internal pure returns (address) {
                        address data;
                        //read sender from userOp, which is first userOp member (saves 800 gas...)
                        assembly {
                            data := calldataload(userOp)
                        }
                        return address(uint160(data));
                    }
                    /**
                     * Relayer/block builder might submit the TX with higher priorityFee,
                     * but the user should not pay above what he signed for.
                     * @param userOp - The user operation data.
                     */
                    function gasPrice(
                        PackedUserOperation calldata userOp
                    ) internal view returns (uint256) {
                        unchecked {
                            (uint256 maxPriorityFeePerGas, uint256 maxFeePerGas) = unpackUints(userOp.gasFees);
                            if (maxFeePerGas == maxPriorityFeePerGas) {
                                //legacy mode (for networks that don't support basefee opcode)
                                return maxFeePerGas;
                            }
                            return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);
                        }
                    }
                    /**
                     * Pack the user operation data into bytes for hashing.
                     * @param userOp - The user operation data.
                     */
                    function encode(
                        PackedUserOperation calldata userOp
                    ) internal pure returns (bytes memory ret) {
                        address sender = getSender(userOp);
                        uint256 nonce = userOp.nonce;
                        bytes32 hashInitCode = calldataKeccak(userOp.initCode);
                        bytes32 hashCallData = calldataKeccak(userOp.callData);
                        bytes32 accountGasLimits = userOp.accountGasLimits;
                        uint256 preVerificationGas = userOp.preVerificationGas;
                        bytes32 gasFees = userOp.gasFees;
                        bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);
                        return abi.encode(
                            sender, nonce,
                            hashInitCode, hashCallData,
                            accountGasLimits, preVerificationGas, gasFees,
                            hashPaymasterAndData
                        );
                    }
                    function unpackUints(
                        bytes32 packed
                    ) internal pure returns (uint256 high128, uint256 low128) {
                        return (uint128(bytes16(packed)), uint128(uint256(packed)));
                    }
                    //unpack just the high 128-bits from a packed value
                    function unpackHigh128(bytes32 packed) internal pure returns (uint256) {
                        return uint256(packed) >> 128;
                    }
                    // unpack just the low 128-bits from a packed value
                    function unpackLow128(bytes32 packed) internal pure returns (uint256) {
                        return uint128(uint256(packed));
                    }
                    function unpackMaxPriorityFeePerGas(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return unpackHigh128(userOp.gasFees);
                    }
                    function unpackMaxFeePerGas(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return unpackLow128(userOp.gasFees);
                    }
                    function unpackVerificationGasLimit(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return unpackHigh128(userOp.accountGasLimits);
                    }
                    function unpackCallGasLimit(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return unpackLow128(userOp.accountGasLimits);
                    }
                    function unpackPaymasterVerificationGasLimit(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return uint128(bytes16(userOp.paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_POSTOP_GAS_OFFSET]));
                    }
                    function unpackPostOpGasLimit(PackedUserOperation calldata userOp)
                    internal pure returns (uint256) {
                        return uint128(bytes16(userOp.paymasterAndData[PAYMASTER_POSTOP_GAS_OFFSET : PAYMASTER_DATA_OFFSET]));
                    }
                    function unpackPaymasterStaticFields(
                        bytes calldata paymasterAndData
                    ) internal pure returns (address paymaster, uint256 validationGasLimit, uint256 postOpGasLimit) {
                        return (
                            address(bytes20(paymasterAndData[: PAYMASTER_VALIDATION_GAS_OFFSET])),
                            uint128(bytes16(paymasterAndData[PAYMASTER_VALIDATION_GAS_OFFSET : PAYMASTER_POSTOP_GAS_OFFSET])),
                            uint128(bytes16(paymasterAndData[PAYMASTER_POSTOP_GAS_OFFSET : PAYMASTER_DATA_OFFSET]))
                        );
                    }
                    /**
                     * Hash the user operation data.
                     * @param userOp - The user operation data.
                     */
                    function hash(
                        PackedUserOperation calldata userOp
                    ) internal pure returns (bytes32) {
                        return keccak256(encode(userOp));
                    }
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                import "./PackedUserOperation.sol";
                interface IAccount {
                    /**
                     * Validate user's signature and nonce
                     * the entryPoint will make the call to the recipient only if this validation call returns successfully.
                     * signature failure should be reported by returning SIG_VALIDATION_FAILED (1).
                     * This allows making a "simulation call" without a valid signature
                     * Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.
                     *
                     * @dev Must validate caller is the entryPoint.
                     *      Must validate the signature and nonce
                     * @param userOp              - The operation that is about to be executed.
                     * @param userOpHash          - Hash of the user's request data. can be used as the basis for signature.
                     * @param missingAccountFunds - Missing funds on the account's deposit in the entrypoint.
                     *                              This is the minimum amount to transfer to the sender(entryPoint) to be
                     *                              able to make the call. The excess is left as a deposit in the entrypoint
                     *                              for future calls. Can be withdrawn anytime using "entryPoint.withdrawTo()".
                     *                              In case there is a paymaster in the request (or the current deposit is high
                     *                              enough), this value will be zero.
                     * @return validationData       - Packaged ValidationData structure. use `_packValidationData` and
                     *                              `_unpackValidationData` to encode and decode.
                     *                              <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
                     *                                 otherwise, an address of an "authorizer" contract.
                     *                              <6-byte> validUntil - Last timestamp this operation is valid. 0 for "indefinite"
                     *                              <6-byte> validAfter - First timestamp this operation is valid
                     *                                                    If an account doesn't use time-range, it is enough to
                     *                                                    return SIG_VALIDATION_FAILED value (1) for signature failure.
                     *                              Note that the validation code cannot use block.timestamp (or block.number) directly.
                     */
                    function validateUserOp(
                        PackedUserOperation calldata userOp,
                        bytes32 userOpHash,
                        uint256 missingAccountFunds
                    ) external returns (uint256 validationData);
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                import "./PackedUserOperation.sol";
                interface IAccountExecute {
                    /**
                     * Account may implement this execute method.
                     * passing this methodSig at the beginning of callData will cause the entryPoint to pass the full UserOp (and hash)
                     * to the account.
                     * The account should skip the methodSig, and use the callData (and optionally, other UserOp fields)
                     *
                     * @param userOp              - The operation that was just validated.
                     * @param userOpHash          - Hash of the user's request data.
                     */
                    function executeUserOp(
                        PackedUserOperation calldata userOp,
                        bytes32 userOpHash
                    ) external;
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                import "./PackedUserOperation.sol";
                /**
                 * Aggregated Signatures validator.
                 */
                interface IAggregator {
                    /**
                     * Validate aggregated signature.
                     * Revert if the aggregated signature does not match the given list of operations.
                     * @param userOps   - Array of UserOperations to validate the signature for.
                     * @param signature - The aggregated signature.
                     */
                    function validateSignatures(
                        PackedUserOperation[] calldata userOps,
                        bytes calldata signature
                    ) external view;
                    /**
                     * Validate signature of a single userOp.
                     * This method should be called by bundler after EntryPointSimulation.simulateValidation() returns
                     * the aggregator this account uses.
                     * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.
                     * @param userOp        - The userOperation received from the user.
                     * @return sigForUserOp - The value to put into the signature field of the userOp when calling handleOps.
                     *                        (usually empty, unless account and aggregator support some kind of "multisig".
                     */
                    function validateUserOpSignature(
                        PackedUserOperation calldata userOp
                    ) external view returns (bytes memory sigForUserOp);
                    /**
                     * Aggregate multiple signatures into a single value.
                     * This method is called off-chain to calculate the signature to pass with handleOps()
                     * bundler MAY use optimized custom code perform this aggregation.
                     * @param userOps              - Array of UserOperations to collect the signatures from.
                     * @return aggregatedSignature - The aggregated signature.
                     */
                    function aggregateSignatures(
                        PackedUserOperation[] calldata userOps
                    ) external view returns (bytes memory aggregatedSignature);
                }
                /**
                 ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.
                 ** Only one instance required on each chain.
                 **/
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                /* solhint-disable avoid-low-level-calls */
                /* solhint-disable no-inline-assembly */
                /* solhint-disable reason-string */
                import "./PackedUserOperation.sol";
                import "./IStakeManager.sol";
                import "./IAggregator.sol";
                import "./INonceManager.sol";
                interface IEntryPoint is IStakeManager, INonceManager {
                    /***
                     * An event emitted after each successful request.
                     * @param userOpHash    - Unique identifier for the request (hash its entire content, except signature).
                     * @param sender        - The account that generates this request.
                     * @param paymaster     - If non-null, the paymaster that pays for this request.
                     * @param nonce         - The nonce value from the request.
                     * @param success       - True if the sender transaction succeeded, false if reverted.
                     * @param actualGasCost - Actual amount paid (by account or paymaster) for this UserOperation.
                     * @param actualGasUsed - Total gas used by this UserOperation (including preVerification, creation,
                     *                        validation and execution).
                     */
                    event UserOperationEvent(
                        bytes32 indexed userOpHash,
                        address indexed sender,
                        address indexed paymaster,
                        uint256 nonce,
                        bool success,
                        uint256 actualGasCost,
                        uint256 actualGasUsed
                    );
                    /**
                     * Account "sender" was deployed.
                     * @param userOpHash - The userOp that deployed this account. UserOperationEvent will follow.
                     * @param sender     - The account that is deployed
                     * @param factory    - The factory used to deploy this account (in the initCode)
                     * @param paymaster  - The paymaster used by this UserOp
                     */
                    event AccountDeployed(
                        bytes32 indexed userOpHash,
                        address indexed sender,
                        address factory,
                        address paymaster
                    );
                    /**
                     * An event emitted if the UserOperation "callData" reverted with non-zero length.
                     * @param userOpHash   - The request unique identifier.
                     * @param sender       - The sender of this request.
                     * @param nonce        - The nonce used in the request.
                     * @param revertReason - The return bytes from the (reverted) call to "callData".
                     */
                    event UserOperationRevertReason(
                        bytes32 indexed userOpHash,
                        address indexed sender,
                        uint256 nonce,
                        bytes revertReason
                    );
                    /**
                     * An event emitted if the UserOperation Paymaster's "postOp" call reverted with non-zero length.
                     * @param userOpHash   - The request unique identifier.
                     * @param sender       - The sender of this request.
                     * @param nonce        - The nonce used in the request.
                     * @param revertReason - The return bytes from the (reverted) call to "callData".
                     */
                    event PostOpRevertReason(
                        bytes32 indexed userOpHash,
                        address indexed sender,
                        uint256 nonce,
                        bytes revertReason
                    );
                    /**
                     * UserOp consumed more than prefund. The UserOperation is reverted, and no refund is made.
                     * @param userOpHash   - The request unique identifier.
                     * @param sender       - The sender of this request.
                     * @param nonce        - The nonce used in the request.
                     */
                    event UserOperationPrefundTooLow(
                        bytes32 indexed userOpHash,
                        address indexed sender,
                        uint256 nonce
                    );
                    /**
                     * An event emitted by handleOps(), before starting the execution loop.
                     * Any event emitted before this event, is part of the validation.
                     */
                    event BeforeExecution();
                    /**
                     * Signature aggregator used by the following UserOperationEvents within this bundle.
                     * @param aggregator - The aggregator used for the following UserOperationEvents.
                     */
                    event SignatureAggregatorChanged(address indexed aggregator);
                    /**
                     * A custom revert error of handleOps, to identify the offending op.
                     * Should be caught in off-chain handleOps simulation and not happen on-chain.
                     * Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.
                     * NOTE: If simulateValidation passes successfully, there should be no reason for handleOps to fail on it.
                     * @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).
                     * @param reason  - Revert reason. The string starts with a unique code "AAmn",
                     *                  where "m" is "1" for factory, "2" for account and "3" for paymaster issues,
                     *                  so a failure can be attributed to the correct entity.
                     */
                    error FailedOp(uint256 opIndex, string reason);
                    /**
                     * A custom revert error of handleOps, to report a revert by account or paymaster.
                     * @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).
                     * @param reason  - Revert reason. see FailedOp(uint256,string), above
                     * @param inner   - data from inner cought revert reason
                     * @dev note that inner is truncated to 2048 bytes
                     */
                    error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);
                    error PostOpReverted(bytes returnData);
                    /**
                     * Error case when a signature aggregator fails to verify the aggregated signature it had created.
                     * @param aggregator The aggregator that failed to verify the signature
                     */
                    error SignatureValidationFailed(address aggregator);
                    // Return value of getSenderAddress.
                    error SenderAddressResult(address sender);
                    // UserOps handled, per aggregator.
                    struct UserOpsPerAggregator {
                        PackedUserOperation[] userOps;
                        // Aggregator address
                        IAggregator aggregator;
                        // Aggregated signature
                        bytes signature;
                    }
                    /**
                     * Execute a batch of UserOperations.
                     * No signature aggregator is used.
                     * If any account requires an aggregator (that is, it returned an aggregator when
                     * performing simulateValidation), then handleAggregatedOps() must be used instead.
                     * @param ops         - The operations to execute.
                     * @param beneficiary - The address to receive the fees.
                     */
                    function handleOps(
                        PackedUserOperation[] calldata ops,
                        address payable beneficiary
                    ) external;
                    /**
                     * Execute a batch of UserOperation with Aggregators
                     * @param opsPerAggregator - The operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts).
                     * @param beneficiary      - The address to receive the fees.
                     */
                    function handleAggregatedOps(
                        UserOpsPerAggregator[] calldata opsPerAggregator,
                        address payable beneficiary
                    ) external;
                    /**
                     * Generate a request Id - unique identifier for this request.
                     * The request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.
                     * @param userOp - The user operation to generate the request ID for.
                     * @return hash the hash of this UserOperation
                     */
                    function getUserOpHash(
                        PackedUserOperation calldata userOp
                    ) external view returns (bytes32);
                    /**
                     * Gas and return values during simulation.
                     * @param preOpGas         - The gas used for validation (including preValidationGas)
                     * @param prefund          - The required prefund for this operation
                     * @param accountValidationData   - returned validationData from account.
                     * @param paymasterValidationData - return validationData from paymaster.
                     * @param paymasterContext - Returned by validatePaymasterUserOp (to be passed into postOp)
                     */
                    struct ReturnInfo {
                        uint256 preOpGas;
                        uint256 prefund;
                        uint256 accountValidationData;
                        uint256 paymasterValidationData;
                        bytes paymasterContext;
                    }
                    /**
                     * Returned aggregated signature info:
                     * The aggregator returned by the account, and its current stake.
                     */
                    struct AggregatorStakeInfo {
                        address aggregator;
                        StakeInfo stakeInfo;
                    }
                    /**
                     * Get counterfactual sender address.
                     * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.
                     * This method always revert, and returns the address in SenderAddressResult error
                     * @param initCode - The constructor code to be passed into the UserOperation.
                     */
                    function getSenderAddress(bytes memory initCode) external;
                    error DelegateAndRevert(bool success, bytes ret);
                    /**
                     * Helper method for dry-run testing.
                     * @dev calling this method, the EntryPoint will make a delegatecall to the given data, and report (via revert) the result.
                     *  The method always revert, so is only useful off-chain for dry run calls, in cases where state-override to replace
                     *  actual EntryPoint code is less convenient.
                     * @param target a target contract to make a delegatecall from entrypoint
                     * @param data data to pass to target in a delegatecall
                     */
                    function delegateAndRevert(address target, bytes calldata data) external;
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                interface INonceManager {
                    /**
                     * Return the next nonce for this sender.
                     * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)
                     * But UserOp with different keys can come with arbitrary order.
                     *
                     * @param sender the account address
                     * @param key the high 192 bit of the nonce
                     * @return nonce a full nonce to pass for next UserOp with this sender.
                     */
                    function getNonce(address sender, uint192 key)
                    external view returns (uint256 nonce);
                    /**
                     * Manually increment the nonce of the sender.
                     * This method is exposed just for completeness..
                     * Account does NOT need to call it, neither during validation, nor elsewhere,
                     * as the EntryPoint will update the nonce regardless.
                     * Possible use-case is call it with various keys to "initialize" their nonces to one, so that future
                     * UserOperations will not pay extra for the first transaction with a given key.
                     */
                    function incrementNonce(uint192 key) external;
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                import "./PackedUserOperation.sol";
                /**
                 * The interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.
                 * A paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
                 */
                interface IPaymaster {
                    enum PostOpMode {
                        // User op succeeded.
                        opSucceeded,
                        // User op reverted. Still has to pay for gas.
                        opReverted,
                        // Only used internally in the EntryPoint (cleanup after postOp reverts). Never calling paymaster with this value
                        postOpReverted
                    }
                    /**
                     * Payment validation: check if paymaster agrees to pay.
                     * Must verify sender is the entryPoint.
                     * Revert to reject this request.
                     * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted).
                     * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.
                     * @param userOp          - The user operation.
                     * @param userOpHash      - Hash of the user's request data.
                     * @param maxCost         - The maximum cost of this transaction (based on maximum gas and gas price from userOp).
                     * @return context        - Value to send to a postOp. Zero length to signify postOp is not required.
                     * @return validationData - Signature and time-range of this operation, encoded the same as the return
                     *                          value of validateUserOperation.
                     *                          <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
                     *                                                    other values are invalid for paymaster.
                     *                          <6-byte> validUntil - last timestamp this operation is valid. 0 for "indefinite"
                     *                          <6-byte> validAfter - first timestamp this operation is valid
                     *                          Note that the validation code cannot use block.timestamp (or block.number) directly.
                     */
                    function validatePaymasterUserOp(
                        PackedUserOperation calldata userOp,
                        bytes32 userOpHash,
                        uint256 maxCost
                    ) external returns (bytes memory context, uint256 validationData);
                    /**
                     * Post-operation handler.
                     * Must verify sender is the entryPoint.
                     * @param mode          - Enum with the following options:
                     *                        opSucceeded - User operation succeeded.
                     *                        opReverted  - User op reverted. The paymaster still has to pay for gas.
                     *                        postOpReverted - never passed in a call to postOp().
                     * @param context       - The context value returned by validatePaymasterUserOp
                     * @param actualGasCost - Actual gas used so far (without this postOp call).
                     * @param actualUserOpFeePerGas - the gas price this UserOp pays. This value is based on the UserOp's maxFeePerGas
                     *                        and maxPriorityFee (and basefee)
                     *                        It is not the same as tx.gasprice, which is what the bundler pays.
                     */
                    function postOp(
                        PostOpMode mode,
                        bytes calldata context,
                        uint256 actualGasCost,
                        uint256 actualUserOpFeePerGas
                    ) external;
                }
                // SPDX-License-Identifier: GPL-3.0-only
                pragma solidity >=0.7.5;
                /**
                 * Manage deposits and stakes.
                 * Deposit is just a balance used to pay for UserOperations (either by a paymaster or an account).
                 * Stake is value locked for at least "unstakeDelay" by the staked entity.
                 */
                interface IStakeManager {
                    event Deposited(address indexed account, uint256 totalDeposit);
                    event Withdrawn(
                        address indexed account,
                        address withdrawAddress,
                        uint256 amount
                    );
                    // Emitted when stake or unstake delay are modified.
                    event StakeLocked(
                        address indexed account,
                        uint256 totalStaked,
                        uint256 unstakeDelaySec
                    );
                    // Emitted once a stake is scheduled for withdrawal.
                    event StakeUnlocked(address indexed account, uint256 withdrawTime);
                    event StakeWithdrawn(
                        address indexed account,
                        address withdrawAddress,
                        uint256 amount
                    );
                    /**
                     * @param deposit         - The entity's deposit.
                     * @param staked          - True if this entity is staked.
                     * @param stake           - Actual amount of ether staked for this entity.
                     * @param unstakeDelaySec - Minimum delay to withdraw the stake.
                     * @param withdrawTime    - First block timestamp where 'withdrawStake' will be callable, or zero if already locked.
                     * @dev Sizes were chosen so that deposit fits into one cell (used during handleOp)
                     *      and the rest fit into a 2nd cell (used during stake/unstake)
                     *      - 112 bit allows for 10^15 eth
                     *      - 48 bit for full timestamp
                     *      - 32 bit allows 150 years for unstake delay
                     */
                    struct DepositInfo {
                        uint256 deposit;
                        bool staked;
                        uint112 stake;
                        uint32 unstakeDelaySec;
                        uint48 withdrawTime;
                    }
                    // API struct used by getStakeInfo and simulateValidation.
                    struct StakeInfo {
                        uint256 stake;
                        uint256 unstakeDelaySec;
                    }
                    /**
                     * Get deposit info.
                     * @param account - The account to query.
                     * @return info   - Full deposit information of given account.
                     */
                    function getDepositInfo(
                        address account
                    ) external view returns (DepositInfo memory info);
                    /**
                     * Get account balance.
                     * @param account - The account to query.
                     * @return        - The deposit (for gas payment) of the account.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * Add to the deposit of the given account.
                     * @param account - The account to add to.
                     */
                    function depositTo(address account) external payable;
                    /**
                     * Add to the account's stake - amount and delay
                     * any pending unstake is first cancelled.
                     * @param _unstakeDelaySec - The new lock duration before the deposit can be withdrawn.
                     */
                    function addStake(uint32 _unstakeDelaySec) external payable;
                    /**
                     * Attempt to unlock the stake.
                     * The value can be withdrawn (using withdrawStake) after the unstake delay.
                     */
                    function unlockStake() external;
                    /**
                     * Withdraw from the (unlocked) stake.
                     * Must first call unlockStake and wait for the unstakeDelay to pass.
                     * @param withdrawAddress - The address to send withdrawn value.
                     */
                    function withdrawStake(address payable withdrawAddress) external;
                    /**
                     * Withdraw from the deposit.
                     * @param withdrawAddress - The address to send withdrawn value.
                     * @param withdrawAmount  - The amount to withdraw.
                     */
                    function withdrawTo(
                        address payable withdrawAddress,
                        uint256 withdrawAmount
                    ) external;
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity >=0.7.5;
                /**
                 * User Operation struct
                 * @param sender                - The sender account of this request.
                 * @param nonce                 - Unique value the sender uses to verify it is not a replay.
                 * @param initCode              - If set, the account contract will be created by this constructor/
                 * @param callData              - The method call to execute on this account.
                 * @param accountGasLimits      - Packed gas limits for validateUserOp and gas limit passed to the callData method call.
                 * @param preVerificationGas    - Gas not calculated by the handleOps method, but added to the gas paid.
                 *                                Covers batch overhead.
                 * @param gasFees               - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.
                 * @param paymasterAndData      - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data
                 *                                The paymaster will pay for the transaction instead of the sender.
                 * @param signature             - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.
                 */
                struct PackedUserOperation {
                    address sender;
                    uint256 nonce;
                    bytes initCode;
                    bytes callData;
                    bytes32 accountGasLimits;
                    uint256 preVerificationGas;
                    bytes32 gasFees;
                    bytes paymasterAndData;
                    bytes signature;
                }
                // SPDX-License-Identifier: LGPL-3.0-only
                pragma solidity ^0.8.23;
                // solhint-disable no-inline-assembly
                /**
                 * Utility functions helpful when making different kinds of contract calls in Solidity.
                 */
                library Exec {
                    function call(
                        address to,
                        uint256 value,
                        bytes memory data,
                        uint256 txGas
                    ) internal returns (bool success) {
                        assembly ("memory-safe") {
                            success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                        }
                    }
                    function staticcall(
                        address to,
                        bytes memory data,
                        uint256 txGas
                    ) internal view returns (bool success) {
                        assembly ("memory-safe") {
                            success := staticcall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                        }
                    }
                    function delegateCall(
                        address to,
                        bytes memory data,
                        uint256 txGas
                    ) internal returns (bool success) {
                        assembly ("memory-safe") {
                            success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                        }
                    }
                    // get returned data from last call or calldelegate
                    function getReturnData(uint256 maxLen) internal pure returns (bytes memory returnData) {
                        assembly ("memory-safe") {
                            let len := returndatasize()
                            if gt(len, maxLen) {
                                len := maxLen
                            }
                            let ptr := mload(0x40)
                            mstore(0x40, add(ptr, add(len, 0x20)))
                            mstore(ptr, len)
                            returndatacopy(add(ptr, 0x20), 0, len)
                            returnData := ptr
                        }
                    }
                    // revert with explicit byte array (probably reverted info from call)
                    function revertWithData(bytes memory returnData) internal pure {
                        assembly ("memory-safe") {
                            revert(add(returnData, 32), mload(returnData))
                        }
                    }
                    function callAndRevert(address to, bytes memory data, uint256 maxLen) internal {
                        bool success = call(to,0,data,gasleft());
                        if (!success) {
                            revertWithData(getReturnData(maxLen));
                        }
                    }
                }
                

                File 2 of 12: CErc20
                // File: contracts/ComptrollerInterface.sol
                
                pragma solidity ^0.5.8;
                
                interface ComptrollerInterface {
                    /**
                     * @notice Marker function used for light validation when updating the comptroller of a market
                     * @dev Implementations should simply return true.
                     * @return true
                     */
                    function isComptroller() external view returns (bool);
                
                    /*** Assets You Are In ***/
                
                    function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
                    function exitMarket(address cToken) external returns (uint);
                
                    /*** Policy Hooks ***/
                
                    function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
                    function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
                
                    function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
                    function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
                
                    function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
                    function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
                
                    function repayBorrowAllowed(
                        address cToken,
                        address payer,
                        address borrower,
                        uint repayAmount) external returns (uint);
                    function repayBorrowVerify(
                        address cToken,
                        address payer,
                        address borrower,
                        uint repayAmount,
                        uint borrowerIndex) external;
                
                    function liquidateBorrowAllowed(
                        address cTokenBorrowed,
                        address cTokenCollateral,
                        address liquidator,
                        address borrower,
                        uint repayAmount) external returns (uint);
                    function liquidateBorrowVerify(
                        address cTokenBorrowed,
                        address cTokenCollateral,
                        address liquidator,
                        address borrower,
                        uint repayAmount,
                        uint seizeTokens) external;
                
                    function seizeAllowed(
                        address cTokenCollateral,
                        address cTokenBorrowed,
                        address liquidator,
                        address borrower,
                        uint seizeTokens) external returns (uint);
                    function seizeVerify(
                        address cTokenCollateral,
                        address cTokenBorrowed,
                        address liquidator,
                        address borrower,
                        uint seizeTokens) external;
                
                    function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
                    function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
                
                    /*** Liquidity/Liquidation Calculations ***/
                
                    function liquidateCalculateSeizeTokens(
                        address cTokenBorrowed,
                        address cTokenCollateral,
                        uint repayAmount) external view returns (uint, uint);
                }
                
                // File: contracts/ErrorReporter.sol
                
                pragma solidity ^0.5.8;
                
                contract ComptrollerErrorReporter {
                    enum Error {
                        NO_ERROR,
                        UNAUTHORIZED,
                        COMPTROLLER_MISMATCH,
                        INSUFFICIENT_SHORTFALL,
                        INSUFFICIENT_LIQUIDITY,
                        INVALID_CLOSE_FACTOR,
                        INVALID_COLLATERAL_FACTOR,
                        INVALID_LIQUIDATION_INCENTIVE,
                        MARKET_NOT_ENTERED,
                        MARKET_NOT_LISTED,
                        MARKET_ALREADY_LISTED,
                        MATH_ERROR,
                        NONZERO_BORROW_BALANCE,
                        PRICE_ERROR,
                        REJECTION,
                        SNAPSHOT_ERROR,
                        TOO_MANY_ASSETS,
                        TOO_MUCH_REPAY
                    }
                
                    enum FailureInfo {
                        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
                        ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
                        EXIT_MARKET_BALANCE_OWED,
                        EXIT_MARKET_REJECTION,
                        SET_CLOSE_FACTOR_OWNER_CHECK,
                        SET_CLOSE_FACTOR_VALIDATION,
                        SET_COLLATERAL_FACTOR_OWNER_CHECK,
                        SET_COLLATERAL_FACTOR_NO_EXISTS,
                        SET_COLLATERAL_FACTOR_VALIDATION,
                        SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
                        SET_IMPLEMENTATION_OWNER_CHECK,
                        SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
                        SET_LIQUIDATION_INCENTIVE_VALIDATION,
                        SET_MAX_ASSETS_OWNER_CHECK,
                        SET_PENDING_ADMIN_OWNER_CHECK,
                        SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
                        SET_PRICE_ORACLE_OWNER_CHECK,
                        SUPPORT_MARKET_EXISTS,
                        SUPPORT_MARKET_OWNER_CHECK,
                        ZUNUSED
                    }
                
                    /**
                      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
                      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.
                      **/
                    event Failure(uint error, uint info, uint detail);
                
                    /**
                      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
                      */
                    function fail(Error err, FailureInfo info) internal returns (uint) {
                        emit Failure(uint(err), uint(info), 0);
                
                        return uint(err);
                    }
                
                    /**
                      * @dev use this when reporting an opaque error from an upgradeable collaborator contract
                      */
                    function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
                        emit Failure(uint(err), uint(info), opaqueError);
                
                        return uint(err);
                    }
                }
                
                contract TokenErrorReporter {
                    enum Error {
                        NO_ERROR,
                        UNAUTHORIZED,
                        BAD_INPUT,
                        COMPTROLLER_REJECTION,
                        COMPTROLLER_CALCULATION_ERROR,
                        INTEREST_RATE_MODEL_ERROR,
                        INVALID_ACCOUNT_PAIR,
                        INVALID_CLOSE_AMOUNT_REQUESTED,
                        INVALID_COLLATERAL_FACTOR,
                        MATH_ERROR,
                        MARKET_NOT_FRESH,
                        MARKET_NOT_LISTED,
                        TOKEN_INSUFFICIENT_ALLOWANCE,
                        TOKEN_INSUFFICIENT_BALANCE,
                        TOKEN_INSUFFICIENT_CASH,
                        TOKEN_TRANSFER_IN_FAILED,
                        TOKEN_TRANSFER_OUT_FAILED
                    }
                
                    /*
                     * Note: FailureInfo (but not Error) is kept in alphabetical order
                     *       This is because FailureInfo grows significantly faster, and
                     *       the order of Error has some meaning, while the order of FailureInfo
                     *       is entirely arbitrary.
                     */
                    enum FailureInfo {
                        ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
                        ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
                        ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
                        ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
                        ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
                        ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
                        ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
                        BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
                        BORROW_ACCRUE_INTEREST_FAILED,
                        BORROW_CASH_NOT_AVAILABLE,
                        BORROW_FRESHNESS_CHECK,
                        BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
                        BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
                        BORROW_MARKET_NOT_LISTED,
                        BORROW_COMPTROLLER_REJECTION,
                        LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
                        LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
                        LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
                        LIQUIDATE_COMPTROLLER_REJECTION,
                        LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
                        LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
                        LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
                        LIQUIDATE_FRESHNESS_CHECK,
                        LIQUIDATE_LIQUIDATOR_IS_BORROWER,
                        LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
                        LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
                        LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
                        LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
                        LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
                        LIQUIDATE_SEIZE_TOO_MUCH,
                        MINT_ACCRUE_INTEREST_FAILED,
                        MINT_COMPTROLLER_REJECTION,
                        MINT_EXCHANGE_CALCULATION_FAILED,
                        MINT_EXCHANGE_RATE_READ_FAILED,
                        MINT_FRESHNESS_CHECK,
                        MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
                        MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
                        MINT_TRANSFER_IN_FAILED,
                        MINT_TRANSFER_IN_NOT_POSSIBLE,
                        REDEEM_ACCRUE_INTEREST_FAILED,
                        REDEEM_COMPTROLLER_REJECTION,
                        REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
                        REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
                        REDEEM_EXCHANGE_RATE_READ_FAILED,
                        REDEEM_FRESHNESS_CHECK,
                        REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
                        REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
                        REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
                        REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
                        REDUCE_RESERVES_ADMIN_CHECK,
                        REDUCE_RESERVES_CASH_NOT_AVAILABLE,
                        REDUCE_RESERVES_FRESH_CHECK,
                        REDUCE_RESERVES_VALIDATION,
                        REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
                        REPAY_BORROW_ACCRUE_INTEREST_FAILED,
                        REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
                        REPAY_BORROW_COMPTROLLER_REJECTION,
                        REPAY_BORROW_FRESHNESS_CHECK,
                        REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
                        REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
                        REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
                        SET_COLLATERAL_FACTOR_OWNER_CHECK,
                        SET_COLLATERAL_FACTOR_VALIDATION,
                        SET_COMPTROLLER_OWNER_CHECK,
                        SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
                        SET_INTEREST_RATE_MODEL_FRESH_CHECK,
                        SET_INTEREST_RATE_MODEL_OWNER_CHECK,
                        SET_MAX_ASSETS_OWNER_CHECK,
                        SET_ORACLE_MARKET_NOT_LISTED,
                        SET_PENDING_ADMIN_OWNER_CHECK,
                        SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
                        SET_RESERVE_FACTOR_ADMIN_CHECK,
                        SET_RESERVE_FACTOR_FRESH_CHECK,
                        SET_RESERVE_FACTOR_BOUNDS_CHECK,
                        TRANSFER_COMPTROLLER_REJECTION,
                        TRANSFER_NOT_ALLOWED,
                        TRANSFER_NOT_ENOUGH,
                        TRANSFER_TOO_MUCH
                    }
                
                    /**
                      * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
                      * contract-specific code that enables us to report opaque error codes from upgradeable contracts.
                      **/
                    event Failure(uint error, uint info, uint detail);
                
                    /**
                      * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
                      */
                    function fail(Error err, FailureInfo info) internal returns (uint) {
                        emit Failure(uint(err), uint(info), 0);
                
                        return uint(err);
                    }
                
                    /**
                      * @dev use this when reporting an opaque error from an upgradeable collaborator contract
                      */
                    function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
                        emit Failure(uint(err), uint(info), opaqueError);
                
                        return uint(err);
                    }
                }
                
                // File: contracts/CarefulMath.sol
                
                pragma solidity ^0.5.8;
                
                /**
                  * @title Careful Math
                  * @author Compound
                  * @notice Derived from OpenZeppelin's SafeMath library
                  *         https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
                  */
                contract CarefulMath {
                
                    /**
                     * @dev Possible error codes that we can return
                     */
                    enum MathError {
                        NO_ERROR,
                        DIVISION_BY_ZERO,
                        INTEGER_OVERFLOW,
                        INTEGER_UNDERFLOW
                    }
                
                    /**
                    * @dev Multiplies two numbers, returns an error on overflow.
                    */
                    function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
                        if (a == 0) {
                            return (MathError.NO_ERROR, 0);
                        }
                
                        uint c = a * b;
                
                        if (c / a != b) {
                            return (MathError.INTEGER_OVERFLOW, 0);
                        } else {
                            return (MathError.NO_ERROR, c);
                        }
                    }
                
                    /**
                    * @dev Integer division of two numbers, truncating the quotient.
                    */
                    function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
                        if (b == 0) {
                            return (MathError.DIVISION_BY_ZERO, 0);
                        }
                
                        return (MathError.NO_ERROR, a / b);
                    }
                
                    /**
                    * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
                    */
                    function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
                        if (b <= a) {
                            return (MathError.NO_ERROR, a - b);
                        } else {
                            return (MathError.INTEGER_UNDERFLOW, 0);
                        }
                    }
                
                    /**
                    * @dev Adds two numbers, returns an error on overflow.
                    */
                    function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
                        uint c = a + b;
                
                        if (c >= a) {
                            return (MathError.NO_ERROR, c);
                        } else {
                            return (MathError.INTEGER_OVERFLOW, 0);
                        }
                    }
                
                    /**
                    * @dev add a and b and then subtract c
                    */
                    function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
                        (MathError err0, uint sum) = addUInt(a, b);
                
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, 0);
                        }
                
                        return subUInt(sum, c);
                    }
                }
                
                // File: contracts/Exponential.sol
                
                pragma solidity ^0.5.8;
                
                
                /**
                 * @title Exponential module for storing fixed-decision decimals
                 * @author Compound
                 * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
                 *         Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
                 *         `Exp({mantissa: 5100000000000000000})`.
                 */
                contract Exponential is CarefulMath {
                    uint constant expScale = 1e18;
                    uint constant halfExpScale = expScale/2;
                    uint constant mantissaOne = expScale;
                
                    struct Exp {
                        uint mantissa;
                    }
                
                    /**
                     * @dev Creates an exponential from numerator and denominator values.
                     *      Note: Returns an error if (`num` * 10e18) > MAX_INT,
                     *            or if `denom` is zero.
                     */
                    function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
                        (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, Exp({mantissa: 0}));
                        }
                
                        (MathError err1, uint rational) = divUInt(scaledNumerator, denom);
                        if (err1 != MathError.NO_ERROR) {
                            return (err1, Exp({mantissa: 0}));
                        }
                
                        return (MathError.NO_ERROR, Exp({mantissa: rational}));
                    }
                
                    /**
                     * @dev Adds two exponentials, returning a new exponential.
                     */
                    function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
                        (MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
                
                        return (error, Exp({mantissa: result}));
                    }
                
                    /**
                     * @dev Subtracts two exponentials, returning a new exponential.
                     */
                    function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
                        (MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
                
                        return (error, Exp({mantissa: result}));
                    }
                
                    /**
                     * @dev Multiply an Exp by a scalar, returning a new Exp.
                     */
                    function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
                        (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, Exp({mantissa: 0}));
                        }
                
                        return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
                    }
                
                    /**
                     * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
                     */
                    function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
                        (MathError err, Exp memory product) = mulScalar(a, scalar);
                        if (err != MathError.NO_ERROR) {
                            return (err, 0);
                        }
                
                        return (MathError.NO_ERROR, truncate(product));
                    }
                
                    /**
                     * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
                     */
                    function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
                        (MathError err, Exp memory product) = mulScalar(a, scalar);
                        if (err != MathError.NO_ERROR) {
                            return (err, 0);
                        }
                
                        return addUInt(truncate(product), addend);
                    }
                
                    /**
                     * @dev Divide an Exp by a scalar, returning a new Exp.
                     */
                    function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
                        (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, Exp({mantissa: 0}));
                        }
                
                        return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
                    }
                
                    /**
                     * @dev Divide a scalar by an Exp, returning a new Exp.
                     */
                    function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
                        /*
                          We are doing this as:
                          getExp(mulUInt(expScale, scalar), divisor.mantissa)
                
                          How it works:
                          Exp = a / b;
                          Scalar = s;
                          `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
                        */
                        (MathError err0, uint numerator) = mulUInt(expScale, scalar);
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, Exp({mantissa: 0}));
                        }
                        return getExp(numerator, divisor.mantissa);
                    }
                
                    /**
                     * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
                     */
                    function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
                        (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
                        if (err != MathError.NO_ERROR) {
                            return (err, 0);
                        }
                
                        return (MathError.NO_ERROR, truncate(fraction));
                    }
                
                    /**
                     * @dev Multiplies two exponentials, returning a new exponential.
                     */
                    function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
                
                        (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
                        if (err0 != MathError.NO_ERROR) {
                            return (err0, Exp({mantissa: 0}));
                        }
                
                        // We add half the scale before dividing so that we get rounding instead of truncation.
                        //  See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
                        // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
                        (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
                        if (err1 != MathError.NO_ERROR) {
                            return (err1, Exp({mantissa: 0}));
                        }
                
                        (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
                        // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
                        assert(err2 == MathError.NO_ERROR);
                
                        return (MathError.NO_ERROR, Exp({mantissa: product}));
                    }
                
                    /**
                     * @dev Multiplies two exponentials given their mantissas, returning a new exponential.
                     */
                    function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
                        return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
                    }
                
                    /**
                     * @dev Multiplies three exponentials, returning a new exponential.
                     */
                    function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
                        (MathError err, Exp memory ab) = mulExp(a, b);
                        if (err != MathError.NO_ERROR) {
                            return (err, ab);
                        }
                        return mulExp(ab, c);
                    }
                
                    /**
                     * @dev Divides two exponentials, returning a new exponential.
                     *     (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
                     *  which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
                     */
                    function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
                        return getExp(a.mantissa, b.mantissa);
                    }
                
                    /**
                     * @dev Truncates the given exp to a whole number value.
                     *      For example, truncate(Exp{mantissa: 15 * expScale}) = 15
                     */
                    function truncate(Exp memory exp) pure internal returns (uint) {
                        // Note: We are not using careful math here as we're performing a division that cannot fail
                        return exp.mantissa / expScale;
                    }
                
                    /**
                     * @dev Checks if first Exp is less than second Exp.
                     */
                    function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
                        return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo.
                    }
                
                    /**
                     * @dev Checks if left Exp <= right Exp.
                     */
                    function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
                        return left.mantissa <= right.mantissa;
                    }
                
                    /**
                     * @dev returns true if Exp is exactly zero
                     */
                    function isZeroExp(Exp memory value) pure internal returns (bool) {
                        return value.mantissa == 0;
                    }
                }
                
                // File: contracts/EIP20Interface.sol
                
                pragma solidity ^0.5.8;
                
                /**
                 * @title ERC 20 Token Standard Interface
                 *  https://eips.ethereum.org/EIPS/eip-20
                 */
                interface EIP20Interface {
                
                    /**
                      * @notice Get the total number of tokens in circulation
                      * @return The supply of tokens
                      */
                    function totalSupply() external view returns (uint256);
                
                    /**
                     * @notice Gets the balance of the specified address
                     * @param owner The address from which the balance will be retrieved
                     * @return The balance
                     */
                    function balanceOf(address owner) external view returns (uint256 balance);
                
                    /**
                      * @notice Transfer `amount` tokens from `msg.sender` to `dst`
                      * @param dst The address of the destination account
                      * @param amount The number of tokens to transfer
                      * @return Whether or not the transfer succeeded
                      */
                    function transfer(address dst, uint256 amount) external returns (bool success);
                
                    /**
                      * @notice Transfer `amount` tokens from `src` to `dst`
                      * @param src The address of the source account
                      * @param dst The address of the destination account
                      * @param amount The number of tokens to transfer
                      * @return Whether or not the transfer succeeded
                      */
                    function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
                
                    /**
                      * @notice Approve `spender` to transfer up to `amount` from `src`
                      * @dev This will overwrite the approval amount for `spender`
                      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
                      * @param spender The address of the account which may transfer tokens
                      * @param amount The number of tokens that are approved (-1 means infinite)
                      * @return Whether or not the approval succeeded
                      */
                    function approve(address spender, uint256 amount) external returns (bool success);
                
                    /**
                      * @notice Get the current allowance from `owner` for `spender`
                      * @param owner The address of the account which owns the tokens to be spent
                      * @param spender The address of the account which may transfer tokens
                      * @return The number of tokens allowed to be spent (-1 means infinite)
                      */
                    function allowance(address owner, address spender) external view returns (uint256 remaining);
                
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(address indexed owner, address indexed spender, uint256 amount);
                }
                
                // File: contracts/EIP20NonStandardInterface.sol
                
                pragma solidity ^0.5.8;
                
                /**
                 * @title EIP20NonStandardInterface
                 * @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
                 *  See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
                 */
                interface EIP20NonStandardInterface {
                
                    /**
                     * @notice Get the total number of tokens in circulation
                     * @return The supply of tokens
                     */
                    function totalSupply() external view returns (uint256);
                
                    /**
                     * @notice Gets the balance of the specified address
                     * @param owner The address from which the balance will be retrieved
                     * @return The balance
                     */
                    function balanceOf(address owner) external view returns (uint256 balance);
                
                    ///
                    /// !!!!!!!!!!!!!!
                    /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
                    /// !!!!!!!!!!!!!!
                    ///
                
                    /**
                      * @notice Transfer `amount` tokens from `msg.sender` to `dst`
                      * @param dst The address of the destination account
                      * @param amount The number of tokens to transfer
                      */
                    function transfer(address dst, uint256 amount) external;
                
                    ///
                    /// !!!!!!!!!!!!!!
                    /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
                    /// !!!!!!!!!!!!!!
                    ///
                
                    /**
                      * @notice Transfer `amount` tokens from `src` to `dst`
                      * @param src The address of the source account
                      * @param dst The address of the destination account
                      * @param amount The number of tokens to transfer
                      */
                    function transferFrom(address src, address dst, uint256 amount) external;
                
                    /**
                      * @notice Approve `spender` to transfer up to `amount` from `src`
                      * @dev This will overwrite the approval amount for `spender`
                      *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
                      * @param spender The address of the account which may transfer tokens
                      * @param amount The number of tokens that are approved
                      * @return Whether or not the approval succeeded
                      */
                    function approve(address spender, uint256 amount) external returns (bool success);
                
                    /**
                      * @notice Get the current allowance from `owner` for `spender`
                      * @param owner The address of the account which owns the tokens to be spent
                      * @param spender The address of the account which may transfer tokens
                      * @return The number of tokens allowed to be spent
                      */
                    function allowance(address owner, address spender) external view returns (uint256 remaining);
                
                    event Transfer(address indexed from, address indexed to, uint256 amount);
                    event Approval(address indexed owner, address indexed spender, uint256 amount);
                }
                
                // File: contracts/ReentrancyGuard.sol
                
                pragma solidity ^0.5.8;
                
                /**
                 * @title Helps contracts guard against reentrancy attacks.
                 * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
                 * @dev If you mark a function `nonReentrant`, you should also
                 * mark it `external`.
                 */
                contract ReentrancyGuard {
                    /// @dev counter to allow mutex lock with only one SSTORE operation
                    uint256 private _guardCounter;
                
                    constructor () internal {
                        // The counter starts at one to prevent changing it from zero to a non-zero
                        // value, which is a more expensive operation.
                        _guardCounter = 1;
                    }
                
                    /**
                     * @dev Prevents a contract from calling itself, directly or indirectly.
                     * Calling a `nonReentrant` function from another `nonReentrant`
                     * function is not supported. It is possible to prevent this from happening
                     * by making the `nonReentrant` function external, and make it call a
                     * `private` function that does the actual work.
                     */
                    modifier nonReentrant() {
                        _guardCounter += 1;
                        uint256 localCounter = _guardCounter;
                        _;
                        require(localCounter == _guardCounter, "re-entered");
                    }
                }
                
                // File: contracts/InterestRateModel.sol
                
                pragma solidity ^0.5.8;
                
                /**
                  * @title The Compound InterestRateModel Interface
                  * @author Compound
                  * @notice Any interest rate model should derive from this contract.
                  * @dev These functions are specifically not marked `pure` as implementations of this
                  *      contract may read from storage variables.
                  */
                interface InterestRateModel {
                    /**
                      * @notice Gets the current borrow interest rate based on the given asset, total cash, total borrows
                      *         and total reserves.
                      * @dev The return value should be scaled by 1e18, thus a return value of
                      *      `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
                      * @param cash The total cash of the underlying asset in the CToken
                      * @param borrows The total borrows of the underlying asset in the CToken
                      * @param reserves The total reserves of the underlying asset in the CToken
                      * @return Success or failure and the borrow interest rate per block scaled by 10e18
                      */
                    function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint, uint);
                
                    /**
                      * @notice Marker function used for light validation when updating the interest rate model of a market
                      * @dev Marker function used for light validation when updating the interest rate model of a market. Implementations should simply return true.
                      * @return Success or failure
                      */
                    function isInterestRateModel() external view returns (bool);
                }
                
                // File: contracts/CToken.sol
                
                pragma solidity ^0.5.8;
                
                
                
                
                
                
                
                
                /**
                 * @title Compound's CToken Contract
                 * @notice Abstract base for CTokens
                 * @author Compound
                 */
                contract CToken is EIP20Interface, Exponential, TokenErrorReporter, ReentrancyGuard {
                    /**
                     * @notice Indicator that this is a CToken contract (for inspection)
                     */
                    bool public constant isCToken = true;
                
                    /**
                     * @notice EIP-20 token name for this token
                     */
                    string public name;
                
                    /**
                     * @notice EIP-20 token symbol for this token
                     */
                    string public symbol;
                
                    /**
                     * @notice EIP-20 token decimals for this token
                     */
                    uint public decimals;
                
                    /**
                     * @notice Maximum borrow rate that can ever be applied (.0005% / block)
                     */
                    uint constant borrowRateMaxMantissa = 5e14;
                
                    /**
                     * @notice Maximum fraction of interest that can be set aside for reserves
                     */
                    uint constant reserveFactorMaxMantissa = 1e18;
                
                    /**
                     * @notice Administrator for this contract
                     */
                    address payable public admin;
                
                    /**
                     * @notice Pending administrator for this contract
                     */
                    address payable public pendingAdmin;
                
                    /**
                     * @notice Contract which oversees inter-cToken operations
                     */
                    ComptrollerInterface public comptroller;
                
                    /**
                     * @notice Model which tells what the current interest rate should be
                     */
                    InterestRateModel public interestRateModel;
                
                    /**
                     * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
                     */
                    uint public initialExchangeRateMantissa;
                
                    /**
                     * @notice Fraction of interest currently set aside for reserves
                     */
                    uint public reserveFactorMantissa;
                
                    /**
                     * @notice Block number that interest was last accrued at
                     */
                    uint public accrualBlockNumber;
                
                    /**
                     * @notice Accumulator of total earned interest since the opening of the market
                     */
                    uint public borrowIndex;
                
                    /**
                     * @notice Total amount of outstanding borrows of the underlying in this market
                     */
                    uint public totalBorrows;
                
                    /**
                     * @notice Total amount of reserves of the underlying held in this market
                     */
                    uint public totalReserves;
                
                    /**
                     * @notice Total number of tokens in circulation
                     */
                    uint256 public totalSupply;
                
                    /**
                     * @notice Official record of token balances for each account
                     */
                    mapping (address => uint256) accountTokens;
                
                    /**
                     * @notice Approved token transfer amounts on behalf of others
                     */
                    mapping (address => mapping (address => uint256)) transferAllowances;
                
                    /**
                     * @notice Container for borrow balance information
                     * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
                     * @member interestIndex Global borrowIndex as of the most recent balance-changing action
                     */
                    struct BorrowSnapshot {
                        uint principal;
                        uint interestIndex;
                    }
                
                    /**
                     * @notice Mapping of account addresses to outstanding borrow balances
                     */
                    mapping(address => BorrowSnapshot) accountBorrows;
                
                
                    /*** Market Events ***/
                
                    /**
                     * @notice Event emitted when interest is accrued
                     */
                    event AccrueInterest(uint interestAccumulated, uint borrowIndex, uint totalBorrows);
                
                    /**
                     * @notice Event emitted when tokens are minted
                     */
                    event Mint(address minter, uint mintAmount, uint mintTokens);
                
                    /**
                     * @notice Event emitted when tokens are redeemed
                     */
                    event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
                
                    /**
                     * @notice Event emitted when underlying is borrowed
                     */
                    event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
                
                    /**
                     * @notice Event emitted when a borrow is repaid
                     */
                    event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
                
                    /**
                     * @notice Event emitted when a borrow is liquidated
                     */
                    event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
                
                
                    /*** Admin Events ***/
                
                    /**
                     * @notice Event emitted when pendingAdmin is changed
                     */
                    event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
                
                    /**
                     * @notice Event emitted when pendingAdmin is accepted, which means admin is updated
                     */
                    event NewAdmin(address oldAdmin, address newAdmin);
                
                    /**
                     * @notice Event emitted when comptroller is changed
                     */
                    event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
                
                    /**
                     * @notice Event emitted when interestRateModel is changed
                     */
                    event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
                
                    /**
                     * @notice Event emitted when the reserve factor is changed
                     */
                    event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
                
                    /**
                     * @notice Event emitted when the reserves are reduced
                     */
                    event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
                
                
                    /**
                     * @notice Construct a new money market
                     * @param comptroller_ The address of the Comptroller
                     * @param interestRateModel_ The address of the interest rate model
                     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
                     * @param name_ EIP-20 name of this token
                     * @param symbol_ EIP-20 symbol of this token
                     * @param decimals_ EIP-20 decimal precision of this token
                     */
                    constructor(ComptrollerInterface comptroller_,
                                InterestRateModel interestRateModel_,
                                uint initialExchangeRateMantissa_,
                                string memory name_,
                                string memory symbol_,
                                uint decimals_) internal {
                        // Set admin to msg.sender
                        admin = msg.sender;
                
                        // Set initial exchange rate
                        initialExchangeRateMantissa = initialExchangeRateMantissa_;
                        require(initialExchangeRateMantissa > 0, "Initial exchange rate must be greater than zero.");
                
                        // Set the comptroller
                        uint err = _setComptroller(comptroller_);
                        require(err == uint(Error.NO_ERROR), "Setting comptroller failed");
                
                        // Initialize block number and borrow index (block number mocks depend on comptroller being set)
                        accrualBlockNumber = getBlockNumber();
                        borrowIndex = mantissaOne;
                
                        // Set the interest rate model (depends on block number / borrow index)
                        err = _setInterestRateModelFresh(interestRateModel_);
                        require(err == uint(Error.NO_ERROR), "Setting interest rate model failed");
                
                        name = name_;
                        symbol = symbol_;
                        decimals = decimals_;
                    }
                
                    /**
                     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
                     * @dev Called by both `transfer` and `transferFrom` internally
                     * @param spender The address of the account performing the transfer
                     * @param src The address of the source account
                     * @param dst The address of the destination account
                     * @param tokens The number of tokens to transfer
                     * @return Whether or not the transfer succeeded
                     */
                    function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
                        /* Fail if transfer not allowed */
                        uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Do not allow self-transfers */
                        if (src == dst) {
                            return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
                        }
                
                        /* Get the allowance, infinite for the account owner */
                        uint startingAllowance = 0;
                        if (spender == src) {
                            startingAllowance = uint(-1);
                        } else {
                            startingAllowance = transferAllowances[src][spender];
                        }
                
                        /* Do the calculations, checking for {under,over}flow */
                        MathError mathErr;
                        uint allowanceNew;
                        uint srcTokensNew;
                        uint dstTokensNew;
                
                        (mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
                        if (mathErr != MathError.NO_ERROR) {
                            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
                        }
                
                        (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
                        if (mathErr != MathError.NO_ERROR) {
                            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
                        }
                
                        (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
                        if (mathErr != MathError.NO_ERROR) {
                            return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        accountTokens[src] = srcTokensNew;
                        accountTokens[dst] = dstTokensNew;
                
                        /* Eat some of the allowance (if necessary) */
                        if (startingAllowance != uint(-1)) {
                            transferAllowances[src][spender] = allowanceNew;
                        }
                
                        /* We emit a Transfer event */
                        emit Transfer(src, dst, tokens);
                
                        /* We call the defense hook (which checks for under-collateralization) */
                        comptroller.transferVerify(address(this), src, dst, tokens);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Transfer `amount` tokens from `msg.sender` to `dst`
                     * @param dst The address of the destination account
                     * @param amount The number of tokens to transfer
                     * @return Whether or not the transfer succeeded
                     */
                    function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
                        return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Transfer `amount` tokens from `src` to `dst`
                     * @param src The address of the source account
                     * @param dst The address of the destination account
                     * @param amount The number of tokens to transfer
                     * @return Whether or not the transfer succeeded
                     */
                    function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
                        return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Approve `spender` to transfer up to `amount` from `src`
                     * @dev This will overwrite the approval amount for `spender`
                     *  and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
                     * @param spender The address of the account which may transfer tokens
                     * @param amount The number of tokens that are approved (-1 means infinite)
                     * @return Whether or not the approval succeeded
                     */
                    function approve(address spender, uint256 amount) external returns (bool) {
                        address src = msg.sender;
                        transferAllowances[src][spender] = amount;
                        emit Approval(src, spender, amount);
                        return true;
                    }
                
                    /**
                     * @notice Get the current allowance from `owner` for `spender`
                     * @param owner The address of the account which owns the tokens to be spent
                     * @param spender The address of the account which may transfer tokens
                     * @return The number of tokens allowed to be spent (-1 means infinite)
                     */
                    function allowance(address owner, address spender) external view returns (uint256) {
                        return transferAllowances[owner][spender];
                    }
                
                    /**
                     * @notice Get the token balance of the `owner`
                     * @param owner The address of the account to query
                     * @return The number of tokens owned by `owner`
                     */
                    function balanceOf(address owner) external view returns (uint256) {
                        return accountTokens[owner];
                    }
                
                    /**
                     * @notice Get the underlying balance of the `owner`
                     * @dev This also accrues interest in a transaction
                     * @param owner The address of the account to query
                     * @return The amount of underlying owned by `owner`
                     */
                    function balanceOfUnderlying(address owner) external returns (uint) {
                        Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
                        (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
                        require(mErr == MathError.NO_ERROR);
                        return balance;
                    }
                
                    /**
                     * @notice Get a snapshot of the account's balances, and the cached exchange rate
                     * @dev This is used by comptroller to more efficiently perform liquidity checks.
                     * @param account Address of the account to snapshot
                     * @return (possible error, token balance, borrow balance, exchange rate mantissa)
                     */
                    function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
                        uint cTokenBalance = accountTokens[account];
                        uint borrowBalance;
                        uint exchangeRateMantissa;
                
                        MathError mErr;
                
                        (mErr, borrowBalance) = borrowBalanceStoredInternal(account);
                        if (mErr != MathError.NO_ERROR) {
                            return (uint(Error.MATH_ERROR), 0, 0, 0);
                        }
                
                        (mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
                        if (mErr != MathError.NO_ERROR) {
                            return (uint(Error.MATH_ERROR), 0, 0, 0);
                        }
                
                        return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
                    }
                
                    /**
                     * @dev Function to simply retrieve block number
                     *  This exists mainly for inheriting test contracts to stub this result.
                     */
                    function getBlockNumber() internal view returns (uint) {
                        return block.number;
                    }
                
                    /**
                     * @notice Returns the current per-block borrow interest rate for this cToken
                     * @return The borrow interest rate per block, scaled by 1e18
                     */
                    function borrowRatePerBlock() external view returns (uint) {
                        (uint opaqueErr, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
                        require(opaqueErr == 0, "borrowRatePerBlock: interestRateModel.borrowRate failed"); // semi-opaque
                        return borrowRateMantissa;
                    }
                
                    /**
                     * @notice Returns the current per-block supply interest rate for this cToken
                     * @return The supply interest rate per block, scaled by 1e18
                     */
                    function supplyRatePerBlock() external view returns (uint) {
                        /* We calculate the supply rate:
                         *  underlying = totalSupply × exchangeRate
                         *  borrowsPer = totalBorrows ÷ underlying
                         *  supplyRate = borrowRate × (1-reserveFactor) × borrowsPer
                         */
                        uint exchangeRateMantissa = exchangeRateStored();
                
                        (uint e0, uint borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
                        require(e0 == 0, "supplyRatePerBlock: calculating borrowRate failed"); // semi-opaque
                
                        (MathError e1, Exp memory underlying) = mulScalar(Exp({mantissa: exchangeRateMantissa}), totalSupply);
                        require(e1 == MathError.NO_ERROR, "supplyRatePerBlock: calculating underlying failed");
                
                        (MathError e2, Exp memory borrowsPer) = divScalarByExp(totalBorrows, underlying);
                        require(e2 == MathError.NO_ERROR, "supplyRatePerBlock: calculating borrowsPer failed");
                
                        (MathError e3, Exp memory oneMinusReserveFactor) = subExp(Exp({mantissa: mantissaOne}), Exp({mantissa: reserveFactorMantissa}));
                        require(e3 == MathError.NO_ERROR, "supplyRatePerBlock: calculating oneMinusReserveFactor failed");
                
                        (MathError e4, Exp memory supplyRate) = mulExp3(Exp({mantissa: borrowRateMantissa}), oneMinusReserveFactor, borrowsPer);
                        require(e4 == MathError.NO_ERROR, "supplyRatePerBlock: calculating supplyRate failed");
                
                        return supplyRate.mantissa;
                    }
                
                    /**
                     * @notice Returns the current total borrows plus accrued interest
                     * @return The total borrows with interest
                     */
                    function totalBorrowsCurrent() external nonReentrant returns (uint) {
                        require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
                        return totalBorrows;
                    }
                
                    /**
                     * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
                     * @param account The address whose balance should be calculated after updating borrowIndex
                     * @return The calculated balance
                     */
                    function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
                        require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
                        return borrowBalanceStored(account);
                    }
                
                    /**
                     * @notice Return the borrow balance of account based on stored data
                     * @param account The address whose balance should be calculated
                     * @return The calculated balance
                     */
                    function borrowBalanceStored(address account) public view returns (uint) {
                        (MathError err, uint result) = borrowBalanceStoredInternal(account);
                        require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
                        return result;
                    }
                
                    /**
                     * @notice Return the borrow balance of account based on stored data
                     * @param account The address whose balance should be calculated
                     * @return (error code, the calculated balance or 0 if error code is non-zero)
                     */
                    function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
                        /* Note: we do not assert that the market is up to date */
                        MathError mathErr;
                        uint principalTimesIndex;
                        uint result;
                
                        /* Get borrowBalance and borrowIndex */
                        BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
                
                        /* If borrowBalance = 0 then borrowIndex is likely also 0.
                         * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
                         */
                        if (borrowSnapshot.principal == 0) {
                            return (MathError.NO_ERROR, 0);
                        }
                
                        /* Calculate new borrow balance using the interest index:
                         *  recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
                         */
                        (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
                        if (mathErr != MathError.NO_ERROR) {
                            return (mathErr, 0);
                        }
                
                        (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
                        if (mathErr != MathError.NO_ERROR) {
                            return (mathErr, 0);
                        }
                
                        return (MathError.NO_ERROR, result);
                    }
                
                    /**
                     * @notice Accrue interest then return the up-to-date exchange rate
                     * @return Calculated exchange rate scaled by 1e18
                     */
                    function exchangeRateCurrent() public nonReentrant returns (uint) {
                        require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
                        return exchangeRateStored();
                    }
                
                    /**
                     * @notice Calculates the exchange rate from the underlying to the CToken
                     * @dev This function does not accrue interest before calculating the exchange rate
                     * @return Calculated exchange rate scaled by 1e18
                     */
                    function exchangeRateStored() public view returns (uint) {
                        (MathError err, uint result) = exchangeRateStoredInternal();
                        require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
                        return result;
                    }
                
                    /**
                     * @notice Calculates the exchange rate from the underlying to the CToken
                     * @dev This function does not accrue interest before calculating the exchange rate
                     * @return (error code, calculated exchange rate scaled by 1e18)
                     */
                    function exchangeRateStoredInternal() internal view returns (MathError, uint) {
                        if (totalSupply == 0) {
                            /*
                             * If there are no tokens minted:
                             *  exchangeRate = initialExchangeRate
                             */
                            return (MathError.NO_ERROR, initialExchangeRateMantissa);
                        } else {
                            /*
                             * Otherwise:
                             *  exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
                             */
                            uint totalCash = getCashPrior();
                            uint cashPlusBorrowsMinusReserves;
                            Exp memory exchangeRate;
                            MathError mathErr;
                
                            (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
                            if (mathErr != MathError.NO_ERROR) {
                                return (mathErr, 0);
                            }
                
                            (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, totalSupply);
                            if (mathErr != MathError.NO_ERROR) {
                                return (mathErr, 0);
                            }
                
                            return (MathError.NO_ERROR, exchangeRate.mantissa);
                        }
                    }
                
                    /**
                     * @notice Get cash balance of this cToken in the underlying asset
                     * @return The quantity of underlying asset owned by this contract
                     */
                    function getCash() external view returns (uint) {
                        return getCashPrior();
                    }
                
                    struct AccrueInterestLocalVars {
                        MathError mathErr;
                        uint opaqueErr;
                        uint borrowRateMantissa;
                        uint currentBlockNumber;
                        uint blockDelta;
                
                        Exp simpleInterestFactor;
                
                        uint interestAccumulated;
                        uint totalBorrowsNew;
                        uint totalReservesNew;
                        uint borrowIndexNew;
                    }
                
                    /**
                      * @notice Applies accrued interest to total borrows and reserves.
                      * @dev This calculates interest accrued from the last checkpointed block
                      *      up to the current block and writes new checkpoint to storage.
                      */
                    function accrueInterest() public returns (uint) {
                        AccrueInterestLocalVars memory vars;
                
                        /* Calculate the current borrow interest rate */
                        (vars.opaqueErr, vars.borrowRateMantissa) = interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
                        require(vars.borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
                        if (vars.opaqueErr != 0) {
                            return failOpaque(Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, vars.opaqueErr);
                        }
                
                        /* Remember the initial block number */
                        vars.currentBlockNumber = getBlockNumber();
                
                        /* Calculate the number of blocks elapsed since the last accrual */
                        (vars.mathErr, vars.blockDelta) = subUInt(vars.currentBlockNumber, accrualBlockNumber);
                        assert(vars.mathErr == MathError.NO_ERROR); // Block delta should always succeed and if it doesn't, blow up.
                
                        /*
                         * Calculate the interest accumulated into borrows and reserves and the new index:
                         *  simpleInterestFactor = borrowRate * blockDelta
                         *  interestAccumulated = simpleInterestFactor * totalBorrows
                         *  totalBorrowsNew = interestAccumulated + totalBorrows
                         *  totalReservesNew = interestAccumulated * reserveFactor + totalReserves
                         *  borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
                         */
                        (vars.mathErr, vars.simpleInterestFactor) = mulScalar(Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.interestAccumulated) = mulScalarTruncate(vars.simpleInterestFactor, totalBorrows);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.totalBorrowsNew) = addUInt(vars.interestAccumulated, totalBorrows);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), vars.interestAccumulated, totalReserves);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.borrowIndexNew) = mulScalarTruncateAddUInt(vars.simpleInterestFactor, borrowIndex, borrowIndex);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /* We write the previously calculated values into storage */
                        accrualBlockNumber = vars.currentBlockNumber;
                        borrowIndex = vars.borrowIndexNew;
                        totalBorrows = vars.totalBorrowsNew;
                        totalReserves = vars.totalReservesNew;
                
                        /* We emit an AccrueInterest event */
                        emit AccrueInterest(vars.interestAccumulated, vars.borrowIndexNew, totalBorrows);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Sender supplies assets into the market and receives cTokens in exchange
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param mintAmount The amount of the underlying asset to supply
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function mintInternal(uint mintAmount) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
                            return fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED);
                        }
                        // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
                        return mintFresh(msg.sender, mintAmount);
                    }
                
                    struct MintLocalVars {
                        Error err;
                        MathError mathErr;
                        uint exchangeRateMantissa;
                        uint mintTokens;
                        uint totalSupplyNew;
                        uint accountTokensNew;
                    }
                
                    /**
                     * @notice User supplies assets into the market and receives cTokens in exchange
                     * @dev Assumes interest has already been accrued up to the current block
                     * @param minter The address of the account which is supplying the assets
                     * @param mintAmount The amount of the underlying asset to supply
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function mintFresh(address minter, uint mintAmount) internal returns (uint) {
                        /* Fail if mint not allowed */
                        uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Verify market's block number equals current block number */
                        if (accrualBlockNumber != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK);
                        }
                
                        MintLocalVars memory vars;
                
                        /* Fail if checkTransferIn fails */
                        vars.err = checkTransferIn(minter, mintAmount);
                        if (vars.err != Error.NO_ERROR) {
                            return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_NOT_POSSIBLE);
                        }
                
                        /*
                         * We get the current exchange rate and calculate the number of cTokens to be minted:
                         *  mintTokens = mintAmount / exchangeRate
                         */
                        (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(mintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /*
                         * We calculate the new total supply of cTokens and minter token balance, checking for overflow:
                         *  totalSupplyNew = totalSupply + mintTokens
                         *  accountTokensNew = accountTokens[minter] + mintTokens
                         */
                        (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /*
                         * We call doTransferIn for the minter and the mintAmount
                         *  Note: The cToken must handle variations between ERC-20 and ETH underlying.
                         *  On success, the cToken holds an additional mintAmount of cash.
                         *  If doTransferIn fails despite the fact we checked pre-conditions,
                         *   we revert because we can't be sure if side effects occurred.
                         */
                        vars.err = doTransferIn(minter, mintAmount);
                        if (vars.err != Error.NO_ERROR) {
                            return fail(vars.err, FailureInfo.MINT_TRANSFER_IN_FAILED);
                        }
                
                        /* We write previously calculated values into storage */
                        totalSupply = vars.totalSupplyNew;
                        accountTokens[minter] = vars.accountTokensNew;
                
                        /* We emit a Mint event, and a Transfer event */
                        emit Mint(minter, mintAmount, vars.mintTokens);
                        emit Transfer(address(this), minter, vars.mintTokens);
                
                        /* We call the defense hook */
                        comptroller.mintVerify(address(this), minter, mintAmount, vars.mintTokens);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Sender redeems cTokens in exchange for the underlying asset
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param redeemTokens The number of cTokens to redeem into underlying
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
                            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
                        }
                        // redeemFresh emits redeem-specific logs on errors, so we don't need to
                        return redeemFresh(msg.sender, redeemTokens, 0);
                    }
                
                    /**
                     * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param redeemAmount The amount of underlying to redeem
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
                            return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
                        }
                        // redeemFresh emits redeem-specific logs on errors, so we don't need to
                        return redeemFresh(msg.sender, 0, redeemAmount);
                    }
                
                    struct RedeemLocalVars {
                        Error err;
                        MathError mathErr;
                        uint exchangeRateMantissa;
                        uint redeemTokens;
                        uint redeemAmount;
                        uint totalSupplyNew;
                        uint accountTokensNew;
                    }
                
                    /**
                     * @notice User redeems cTokens in exchange for the underlying asset
                     * @dev Assumes interest has already been accrued up to the current block
                     * @param redeemer The address of the account which is redeeming the tokens
                     * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero)
                     * @param redeemAmountIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be zero)
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
                        require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
                
                        RedeemLocalVars memory vars;
                
                        /* exchangeRate = invoke Exchange Rate Stored() */
                        (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
                        }
                
                        /* If redeemTokensIn > 0: */
                        if (redeemTokensIn > 0) {
                            /*
                             * We calculate the exchange rate and the amount of underlying to be redeemed:
                             *  redeemTokens = redeemTokensIn
                             *  redeemAmount = redeemTokensIn x exchangeRateCurrent
                             */
                            vars.redeemTokens = redeemTokensIn;
                
                            (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
                            if (vars.mathErr != MathError.NO_ERROR) {
                                return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
                            }
                        } else {
                            /*
                             * We get the current exchange rate and calculate the amount to be redeemed:
                             *  redeemTokens = redeemAmountIn / exchangeRate
                             *  redeemAmount = redeemAmountIn
                             */
                
                            (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
                            if (vars.mathErr != MathError.NO_ERROR) {
                                return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
                            }
                
                            vars.redeemAmount = redeemAmountIn;
                        }
                
                        /* Fail if redeem not allowed */
                        uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Verify market's block number equals current block number */
                        if (accrualBlockNumber != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
                        }
                
                        /*
                         * We calculate the new total supply and redeemer balance, checking for underflow:
                         *  totalSupplyNew = totalSupply - redeemTokens
                         *  accountTokensNew = accountTokens[redeemer] - redeemTokens
                         */
                        (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /* Fail gracefully if protocol has insufficient cash */
                        if (getCashPrior() < vars.redeemAmount) {
                            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /*
                         * We invoke doTransferOut for the redeemer and the redeemAmount.
                         *  Note: The cToken must handle variations between ERC-20 and ETH underlying.
                         *  On success, the cToken has redeemAmount less of cash.
                         *  If doTransferOut fails despite the fact we checked pre-conditions,
                         *   we revert because we can't be sure if side effects occurred.
                         */
                        vars.err = doTransferOut(redeemer, vars.redeemAmount);
                        require(vars.err == Error.NO_ERROR, "redeem transfer out failed");
                
                        /* We write previously calculated values into storage */
                        totalSupply = vars.totalSupplyNew;
                        accountTokens[redeemer] = vars.accountTokensNew;
                
                        /* We emit a Transfer event, and a Redeem event */
                        emit Transfer(redeemer, address(this), vars.redeemTokens);
                        emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
                
                        /* We call the defense hook */
                        comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                      * @notice Sender borrows assets from the protocol to their own address
                      * @param borrowAmount The amount of the underlying asset to borrow
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
                            return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
                        }
                        // borrowFresh emits borrow-specific logs on errors, so we don't need to
                        return borrowFresh(msg.sender, borrowAmount);
                    }
                
                    struct BorrowLocalVars {
                        Error err;
                        MathError mathErr;
                        uint accountBorrows;
                        uint accountBorrowsNew;
                        uint totalBorrowsNew;
                    }
                
                    /**
                      * @notice Users borrow assets from the protocol to their own address
                      * @param borrowAmount The amount of the underlying asset to borrow
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
                        /* Fail if borrow not allowed */
                        uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Verify market's block number equals current block number */
                        if (accrualBlockNumber != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
                        }
                
                        /* Fail gracefully if protocol has insufficient underlying cash */
                        if (getCashPrior() < borrowAmount) {
                            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
                        }
                
                        BorrowLocalVars memory vars;
                
                        /*
                         * We calculate the new borrower and total borrow balances, failing on overflow:
                         *  accountBorrowsNew = accountBorrows + borrowAmount
                         *  totalBorrowsNew = totalBorrows + borrowAmount
                         */
                        (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /*
                         * We invoke doTransferOut for the borrower and the borrowAmount.
                         *  Note: The cToken must handle variations between ERC-20 and ETH underlying.
                         *  On success, the cToken borrowAmount less of cash.
                         *  If doTransferOut fails despite the fact we checked pre-conditions,
                         *   we revert because we can't be sure if side effects occurred.
                         */
                        vars.err = doTransferOut(borrower, borrowAmount);
                        require(vars.err == Error.NO_ERROR, "borrow transfer out failed");
                
                        /* We write the previously calculated values into storage */
                        accountBorrows[borrower].principal = vars.accountBorrowsNew;
                        accountBorrows[borrower].interestIndex = borrowIndex;
                        totalBorrows = vars.totalBorrowsNew;
                
                        /* We emit a Borrow event */
                        emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
                
                        /* We call the defense hook */
                        comptroller.borrowVerify(address(this), borrower, borrowAmount);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Sender repays their own borrow
                     * @param repayAmount The amount to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
                            return fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED);
                        }
                        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
                        return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
                    }
                
                    /**
                     * @notice Sender repays a borrow belonging to borrower
                     * @param borrower the account with the debt being payed off
                     * @param repayAmount The amount to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
                            return fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED);
                        }
                        // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
                        return repayBorrowFresh(msg.sender, borrower, repayAmount);
                    }
                
                    struct RepayBorrowLocalVars {
                        Error err;
                        MathError mathErr;
                        uint repayAmount;
                        uint borrowerIndex;
                        uint accountBorrows;
                        uint accountBorrowsNew;
                        uint totalBorrowsNew;
                    }
                
                    /**
                     * @notice Borrows are repaid by another user (possibly the borrower).
                     * @param payer the account paying off the borrow
                     * @param borrower the account with the debt being payed off
                     * @param repayAmount the amount of undelrying tokens being returned
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) {
                        /* Fail if repayBorrow not allowed */
                        uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Verify market's block number equals current block number */
                        if (accrualBlockNumber != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK);
                        }
                
                        RepayBorrowLocalVars memory vars;
                
                        /* We remember the original borrowerIndex for verification purposes */
                        vars.borrowerIndex = accountBorrows[borrower].interestIndex;
                
                        /* We fetch the amount the borrower owes, with accumulated interest */
                        (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /* If repayAmount == -1, repayAmount = accountBorrows */
                        if (repayAmount == uint(-1)) {
                            vars.repayAmount = vars.accountBorrows;
                        } else {
                            vars.repayAmount = repayAmount;
                        }
                
                        /* Fail if checkTransferIn fails */
                        vars.err = checkTransferIn(payer, vars.repayAmount);
                        if (vars.err != Error.NO_ERROR) {
                            return fail(vars.err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE);
                        }
                
                        /*
                         * We calculate the new borrower and total borrow balances, failing on underflow:
                         *  accountBorrowsNew = accountBorrows - repayAmount
                         *  totalBorrowsNew = totalBorrows - repayAmount
                         */
                        (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.repayAmount);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.repayAmount);
                        if (vars.mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /*
                         * We call doTransferIn for the payer and the repayAmount
                         *  Note: The cToken must handle variations between ERC-20 and ETH underlying.
                         *  On success, the cToken holds an additional repayAmount of cash.
                         *  If doTransferIn fails despite the fact we checked pre-conditions,
                         *   we revert because we can't be sure if side effects occurred.
                         */
                        vars.err = doTransferIn(payer, vars.repayAmount);
                        require(vars.err == Error.NO_ERROR, "repay borrow transfer in failed");
                
                        /* We write the previously calculated values into storage */
                        accountBorrows[borrower].principal = vars.accountBorrowsNew;
                        accountBorrows[borrower].interestIndex = borrowIndex;
                        totalBorrows = vars.totalBorrowsNew;
                
                        /* We emit a RepayBorrow event */
                        emit RepayBorrow(payer, borrower, vars.repayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
                
                        /* We call the defense hook */
                        comptroller.repayBorrowVerify(address(this), payer, borrower, vars.repayAmount, vars.borrowerIndex);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice The sender liquidates the borrowers collateral.
                     *  The collateral seized is transferred to the liquidator.
                     * @param borrower The borrower of this cToken to be liquidated
                     * @param cTokenCollateral The market in which to seize collateral from the borrower
                     * @param repayAmount The amount of the underlying borrowed asset to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function liquidateBorrowInternal(address borrower, uint repayAmount, CToken cTokenCollateral) internal nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
                            return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
                        }
                
                        error = cTokenCollateral.accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
                            return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED);
                        }
                
                        // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
                        return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
                    }
                
                    /**
                     * @notice The liquidator liquidates the borrowers collateral.
                     *  The collateral seized is transferred to the liquidator.
                     * @param borrower The borrower of this cToken to be liquidated
                     * @param liquidator The address repaying the borrow and seizing collateral
                     * @param cTokenCollateral The market in which to seize collateral from the borrower
                     * @param repayAmount The amount of the underlying borrowed asset to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CToken cTokenCollateral) internal returns (uint) {
                        /* Fail if liquidate not allowed */
                        uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Verify market's block number equals current block number */
                        if (accrualBlockNumber != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK);
                        }
                
                        /* Verify cTokenCollateral market's block number equals current block number */
                        if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK);
                        }
                
                        /* Fail if borrower = liquidator */
                        if (borrower == liquidator) {
                            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER);
                        }
                
                        /* Fail if repayAmount = 0 */
                        if (repayAmount == 0) {
                            return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO);
                        }
                
                        /* Fail if repayAmount = -1 */
                        if (repayAmount == uint(-1)) {
                            return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX);
                        }
                
                        /* We calculate the number of collateral tokens that will be seized */
                        (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), repayAmount);
                        if (amountSeizeError != 0) {
                            return failOpaque(Error.COMPTROLLER_CALCULATION_ERROR, FailureInfo.LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, amountSeizeError);
                        }
                
                        /* Fail if seizeTokens > borrower collateral token balance */
                        if (seizeTokens > cTokenCollateral.balanceOf(borrower)) {
                            return fail(Error.TOKEN_INSUFFICIENT_BALANCE, FailureInfo.LIQUIDATE_SEIZE_TOO_MUCH);
                        }
                
                        /* Fail if repayBorrow fails */
                        uint repayBorrowError = repayBorrowFresh(liquidator, borrower, repayAmount);
                        if (repayBorrowError != uint(Error.NO_ERROR)) {
                            return fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED);
                        }
                
                        /* Revert if seize tokens fails (since we cannot be sure of side effects) */
                        uint seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
                        require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
                
                        /* We emit a LiquidateBorrow event */
                        emit LiquidateBorrow(liquidator, borrower, repayAmount, address(cTokenCollateral), seizeTokens);
                
                        /* We call the defense hook */
                        comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount, seizeTokens);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Transfers collateral tokens (this market) to the liquidator.
                     * @dev Will fail unless called by another cToken during the process of liquidation.
                     *  Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
                     * @param liquidator The account receiving seized collateral
                     * @param borrower The account having collateral seized
                     * @param seizeTokens The number of cTokens to seize
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
                        /* Fail if seize not allowed */
                        uint allowed = comptroller.seizeAllowed(address(this), msg.sender, liquidator, borrower, seizeTokens);
                        if (allowed != 0) {
                            return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
                        }
                
                        /* Fail if borrower = liquidator */
                        if (borrower == liquidator) {
                            return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
                        }
                
                        MathError mathErr;
                        uint borrowerTokensNew;
                        uint liquidatorTokensNew;
                
                        /*
                         * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
                         *  borrowerTokensNew = accountTokens[borrower] - seizeTokens
                         *  liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
                         */
                        (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
                        if (mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
                        }
                
                        (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
                        if (mathErr != MathError.NO_ERROR) {
                            return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        /* We write the previously calculated values into storage */
                        accountTokens[borrower] = borrowerTokensNew;
                        accountTokens[liquidator] = liquidatorTokensNew;
                
                        /* Emit a Transfer event */
                        emit Transfer(borrower, liquidator, seizeTokens);
                
                        /* We call the defense hook */
                        comptroller.seizeVerify(address(this), msg.sender, liquidator, borrower, seizeTokens);
                
                        return uint(Error.NO_ERROR);
                    }
                
                
                    /*** Admin Functions ***/
                
                    /**
                      * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
                      * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
                      * @param newPendingAdmin New pending admin.
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      *
                      * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address?
                      */
                    function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
                        // Check caller = admin
                        if (msg.sender != admin) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
                        }
                
                        // Save current value, if any, for inclusion in log
                        address oldPendingAdmin = pendingAdmin;
                
                        // Store pendingAdmin with value newPendingAdmin
                        pendingAdmin = newPendingAdmin;
                
                        // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
                        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                      * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
                      * @dev Admin function for pending admin to accept role and update admin
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function _acceptAdmin() external returns (uint) {
                        // Check caller is pendingAdmin and pendingAdmin ≠ address(0)
                        if (msg.sender != pendingAdmin || msg.sender == address(0)) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
                        }
                
                        // Save current values for inclusion in log
                        address oldAdmin = admin;
                        address oldPendingAdmin = pendingAdmin;
                
                        // Store admin with value pendingAdmin
                        admin = pendingAdmin;
                
                        // Clear the pending value
                        pendingAdmin = address(0);
                
                        emit NewAdmin(oldAdmin, admin);
                        emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                      * @notice Sets a new comptroller for the market
                      * @dev Admin function to set a new comptroller
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
                        // Check caller is admin
                        if (msg.sender != admin) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
                        }
                
                        ComptrollerInterface oldComptroller = comptroller;
                        // Ensure invoke comptroller.isComptroller() returns true
                        require(newComptroller.isComptroller(), "marker method returned false");
                
                        // Set market's comptroller to newComptroller
                        comptroller = newComptroller;
                
                        // Emit NewComptroller(oldComptroller, newComptroller)
                        emit NewComptroller(oldComptroller, newComptroller);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                      * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
                      * @dev Admin function to accrue interest and set a new reserve factor
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
                            return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
                        }
                        // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
                        return _setReserveFactorFresh(newReserveFactorMantissa);
                    }
                
                    /**
                      * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
                      * @dev Admin function to set a new reserve factor
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
                        // Check caller is admin
                        if (msg.sender != admin) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
                        }
                
                        // Verify market's block number equals current block number
                        if (accrualBlockNumber != getBlockNumber()) {
                            // TODO: static_assert + no error code?
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
                        }
                
                        // Check newReserveFactor ≤ maxReserveFactor
                        if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
                            return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
                        }
                
                        uint oldReserveFactorMantissa = reserveFactorMantissa;
                        reserveFactorMantissa = newReserveFactorMantissa;
                
                        emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice Accrues interest and reduces reserves by transferring to admin
                     * @param reduceAmount Amount of reduction to reserves
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
                            return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
                        }
                        // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
                        return _reduceReservesFresh(reduceAmount);
                    }
                
                    /**
                     * @notice Reduces reserves by transferring to admin
                     * @dev Requires fresh interest accrual
                     * @param reduceAmount Amount of reduction to reserves
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
                        Error err;
                        // totalReserves - reduceAmount
                        uint totalReservesNew;
                
                        // Check caller is admin
                        if (msg.sender != admin) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
                        }
                
                        // We fail gracefully unless market's block number equals current block number
                        if (accrualBlockNumber != getBlockNumber()) {
                            // TODO: static_assert + no error code?
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
                        }
                
                        // Fail gracefully if protocol has insufficient underlying cash
                        if (getCashPrior() < reduceAmount) {
                            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
                        }
                
                        // Check reduceAmount ≤ reserves[n] (totalReserves)
                        // TODO: I'm following the spec literally here but I think we should we just use SafeMath instead and fail on an error (which would be underflow)
                        if (reduceAmount > totalReserves) {
                            return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
                        }
                
                        /////////////////////////
                        // EFFECTS & INTERACTIONS
                        // (No safe failures beyond this point)
                
                        totalReservesNew = totalReserves - reduceAmount;
                        // We checked reduceAmount <= totalReserves above, so this should never revert.
                        require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
                
                        // Store reserves[n+1] = reserves[n] - reduceAmount
                        totalReserves = totalReservesNew;
                
                        // invoke doTransferOut(reduceAmount, admin)
                        err = doTransferOut(admin, reduceAmount);
                        // we revert on the failure of this command
                        require(err == Error.NO_ERROR, "reduce reserves transfer out failed");
                
                        emit ReservesReduced(admin, reduceAmount, totalReservesNew);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /**
                     * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
                     * @dev Admin function to accrue interest and update the interest rate model
                     * @param newInterestRateModel the new interest rate model to use
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
                        uint error = accrueInterest();
                        if (error != uint(Error.NO_ERROR)) {
                            // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
                            return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
                        }
                        // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
                        return _setInterestRateModelFresh(newInterestRateModel);
                    }
                
                    /**
                     * @notice updates the interest rate model (*requires fresh interest accrual)
                     * @dev Admin function to update the interest rate model
                     * @param newInterestRateModel the new interest rate model to use
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
                
                        // Used to store old model for use in the event that is emitted on success
                        InterestRateModel oldInterestRateModel;
                
                        // Check caller is admin
                        if (msg.sender != admin) {
                            return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
                        }
                
                        // We fail gracefully unless market's block number equals current block number
                        if (accrualBlockNumber != getBlockNumber()) {
                            // TODO: static_assert + no error code?
                            return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
                        }
                
                        // Track the market's current interest rate model
                        oldInterestRateModel = interestRateModel;
                
                        // Ensure invoke newInterestRateModel.isInterestRateModel() returns true
                        require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
                
                        // Set the interest rate model to newInterestRateModel
                        interestRateModel = newInterestRateModel;
                
                        // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
                        emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
                
                        return uint(Error.NO_ERROR);
                    }
                
                    /*** Safe Token ***/
                
                    /**
                     * @notice Gets balance of this contract in terms of the underlying
                     * @dev This excludes the value of the current message, if any
                     * @return The quantity of underlying owned by this contract
                     */
                    function getCashPrior() internal view returns (uint);
                
                    /**
                     * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
                     *      whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
                     */
                    function checkTransferIn(address from, uint amount) internal view returns (Error);
                
                    /**
                     * @dev Performs a transfer in, ideally returning an explanatory error code upon failure rather than reverting.
                     *  If caller has not called `checkTransferIn`, this may revert due to insufficient balance or insufficient allowance.
                     *  If caller has called `checkTransferIn` successfully, this should not revert in normal conditions.
                     */
                    function doTransferIn(address from, uint amount) internal returns (Error);
                
                    /**
                     * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
                     *  If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
                     *  If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
                     */
                    function doTransferOut(address payable to, uint amount) internal returns (Error);
                }
                
                // File: contracts/CErc20.sol
                
                pragma solidity ^0.5.8;
                
                
                /**
                 * @title Compound's CErc20 Contract
                 * @notice CTokens which wrap an EIP-20 underlying
                 * @author Compound
                 */
                contract CErc20 is CToken {
                
                    /**
                     * @notice Underlying asset for this CToken
                     */
                    address public underlying;
                
                    /**
                     * @notice Construct a new money market
                     * @param underlying_ The address of the underlying asset
                     * @param comptroller_ The address of the Comptroller
                     * @param interestRateModel_ The address of the interest rate model
                     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
                     * @param name_ ERC-20 name of this token
                     * @param symbol_ ERC-20 symbol of this token
                     * @param decimals_ ERC-20 decimal precision of this token
                     */
                    constructor(address underlying_,
                                ComptrollerInterface comptroller_,
                                InterestRateModel interestRateModel_,
                                uint initialExchangeRateMantissa_,
                                string memory name_,
                                string memory symbol_,
                                uint decimals_) public
                    CToken(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_) {
                        // Set underlying
                        underlying = underlying_;
                        EIP20Interface(underlying).totalSupply(); // Sanity check the underlying
                    }
                
                    /*** User Interface ***/
                
                    /**
                     * @notice Sender supplies assets into the market and receives cTokens in exchange
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param mintAmount The amount of the underlying asset to supply
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function mint(uint mintAmount) external returns (uint) {
                        return mintInternal(mintAmount);
                    }
                
                    /**
                     * @notice Sender redeems cTokens in exchange for the underlying asset
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param redeemTokens The number of cTokens to redeem into underlying
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function redeem(uint redeemTokens) external returns (uint) {
                        return redeemInternal(redeemTokens);
                    }
                
                    /**
                     * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
                     * @dev Accrues interest whether or not the operation succeeds, unless reverted
                     * @param redeemAmount The amount of underlying to redeem
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function redeemUnderlying(uint redeemAmount) external returns (uint) {
                        return redeemUnderlyingInternal(redeemAmount);
                    }
                
                    /**
                      * @notice Sender borrows assets from the protocol to their own address
                      * @param borrowAmount The amount of the underlying asset to borrow
                      * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                      */
                    function borrow(uint borrowAmount) external returns (uint) {
                        return borrowInternal(borrowAmount);
                    }
                
                    /**
                     * @notice Sender repays their own borrow
                     * @param repayAmount The amount to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function repayBorrow(uint repayAmount) external returns (uint) {
                        return repayBorrowInternal(repayAmount);
                    }
                
                    /**
                     * @notice Sender repays a borrow belonging to borrower
                     * @param borrower the account with the debt being payed off
                     * @param repayAmount The amount to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
                        return repayBorrowBehalfInternal(borrower, repayAmount);
                    }
                
                    /**
                     * @notice The sender liquidates the borrowers collateral.
                     *  The collateral seized is transferred to the liquidator.
                     * @param borrower The borrower of this cToken to be liquidated
                     * @param cTokenCollateral The market in which to seize collateral from the borrower
                     * @param repayAmount The amount of the underlying borrowed asset to repay
                     * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
                     */
                    function liquidateBorrow(address borrower, uint repayAmount, CToken cTokenCollateral) external returns (uint) {
                        return liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
                    }
                
                    /*** Safe Token ***/
                
                    /**
                     * @notice Gets balance of this contract in terms of the underlying
                     * @dev This excludes the value of the current message, if any
                     * @return The quantity of underlying tokens owned by this contract
                     */
                    function getCashPrior() internal view returns (uint) {
                        EIP20Interface token = EIP20Interface(underlying);
                        return token.balanceOf(address(this));
                    }
                
                    /**
                     * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
                     *      whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
                     */
                    function checkTransferIn(address from, uint amount) internal view returns (Error) {
                        EIP20Interface token = EIP20Interface(underlying);
                
                        if (token.allowance(from, address(this)) < amount) {
                            return Error.TOKEN_INSUFFICIENT_ALLOWANCE;
                        }
                
                        if (token.balanceOf(from) < amount) {
                            return Error.TOKEN_INSUFFICIENT_BALANCE;
                        }
                
                        return Error.NO_ERROR;
                    }
                
                    /**
                     * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory
                     *      error code rather than reverting.  If caller has not called `checkTransferIn`, this may revert due to
                     *      insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,
                     *      and it returned Error.NO_ERROR, this should not revert in normal conditions.
                     *
                     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
                     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
                     */
                    function doTransferIn(address from, uint amount) internal returns (Error) {
                        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
                        bool result;
                
                        token.transferFrom(from, address(this), amount);
                
                        // solium-disable-next-line security/no-inline-assembly
                        assembly {
                            switch returndatasize()
                                case 0 {                      // This is a non-standard ERC-20
                                    result := not(0)          // set result to true
                                }
                                case 32 {                     // This is a complaint ERC-20
                                    returndatacopy(0, 0, 32)
                                    result := mload(0)        // Set `result = returndata` of external call
                                }
                                default {                     // This is an excessively non-compliant ERC-20, revert.
                                    revert(0, 0)
                                }
                        }
                
                        if (!result) {
                            return Error.TOKEN_TRANSFER_IN_FAILED;
                        }
                
                        return Error.NO_ERROR;
                    }
                
                    /**
                     * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory
                     *      error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
                     *      insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
                     *      it is >= amount, this should not revert in normal conditions.
                     *
                     *      Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
                     *            See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
                     */
                    function doTransferOut(address payable to, uint amount) internal returns (Error) {
                        EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
                        bool result;
                
                        token.transfer(to, amount);
                
                        // solium-disable-next-line security/no-inline-assembly
                        assembly {
                            switch returndatasize()
                                case 0 {                      // This is a non-standard ERC-20
                                    result := not(0)          // set result to true
                                }
                                case 32 {                     // This is a complaint ERC-20
                                    returndatacopy(0, 0, 32)
                                    result := mload(0)        // Set `result = returndata` of external call
                                }
                                default {                     // This is an excessively non-compliant ERC-20, revert.
                                    revert(0, 0)
                                }
                        }
                
                        if (!result) {
                            return Error.TOKEN_TRANSFER_OUT_FAILED;
                        }
                
                        return Error.NO_ERROR;
                    }
                }
                

                File 3 of 12: DSToken
                pragma solidity ^0.4.13;
                
                ////// lib/ds-math/src/math.sol
                /// math.sol -- mixin for inline numerical wizardry
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                contract DSMath {
                    function add(uint x, uint y) internal pure returns (uint z) {
                        require((z = x + y) >= x);
                    }
                    function sub(uint x, uint y) internal pure returns (uint z) {
                        require((z = x - y) <= x);
                    }
                    function mul(uint x, uint y) internal pure returns (uint z) {
                        require(y == 0 || (z = x * y) / y == x);
                    }
                
                    function min(uint x, uint y) internal pure returns (uint z) {
                        return x <= y ? x : y;
                    }
                    function max(uint x, uint y) internal pure returns (uint z) {
                        return x >= y ? x : y;
                    }
                    function imin(int x, int y) internal pure returns (int z) {
                        return x <= y ? x : y;
                    }
                    function imax(int x, int y) internal pure returns (int z) {
                        return x >= y ? x : y;
                    }
                
                    uint constant WAD = 10 ** 18;
                    uint constant RAY = 10 ** 27;
                
                    function wmul(uint x, uint y) internal pure returns (uint z) {
                        z = add(mul(x, y), WAD / 2) / WAD;
                    }
                    function rmul(uint x, uint y) internal pure returns (uint z) {
                        z = add(mul(x, y), RAY / 2) / RAY;
                    }
                    function wdiv(uint x, uint y) internal pure returns (uint z) {
                        z = add(mul(x, WAD), y / 2) / y;
                    }
                    function rdiv(uint x, uint y) internal pure returns (uint z) {
                        z = add(mul(x, RAY), y / 2) / y;
                    }
                
                    // This famous algorithm is called "exponentiation by squaring"
                    // and calculates x^n with x as fixed-point and n as regular unsigned.
                    //
                    // It's O(log n), instead of O(n) for naive repeated multiplication.
                    //
                    // These facts are why it works:
                    //
                    //  If n is even, then x^n = (x^2)^(n/2).
                    //  If n is odd,  then x^n = x * x^(n-1),
                    //   and applying the equation for even x gives
                    //    x^n = x * (x^2)^((n-1) / 2).
                    //
                    //  Also, EVM division is flooring and
                    //    floor[(n-1) / 2] = floor[n / 2].
                    //
                    function rpow(uint x, uint n) internal pure returns (uint z) {
                        z = n % 2 != 0 ? x : RAY;
                
                        for (n /= 2; n != 0; n /= 2) {
                            x = rmul(x, x);
                
                            if (n % 2 != 0) {
                                z = rmul(z, x);
                            }
                        }
                    }
                }
                
                ////// lib/ds-stop/lib/ds-auth/src/auth.sol
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                contract DSAuthority {
                    function canCall(
                        address src, address dst, bytes4 sig
                    ) public view returns (bool);
                }
                
                contract DSAuthEvents {
                    event LogSetAuthority (address indexed authority);
                    event LogSetOwner     (address indexed owner);
                }
                
                contract DSAuth is DSAuthEvents {
                    DSAuthority  public  authority;
                    address      public  owner;
                
                    function DSAuth() public {
                        owner = msg.sender;
                        LogSetOwner(msg.sender);
                    }
                
                    function setOwner(address owner_)
                        public
                        auth
                    {
                        owner = owner_;
                        LogSetOwner(owner);
                    }
                
                    function setAuthority(DSAuthority authority_)
                        public
                        auth
                    {
                        authority = authority_;
                        LogSetAuthority(authority);
                    }
                
                    modifier auth {
                        require(isAuthorized(msg.sender, msg.sig));
                        _;
                    }
                
                    function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
                        if (src == address(this)) {
                            return true;
                        } else if (src == owner) {
                            return true;
                        } else if (authority == DSAuthority(0)) {
                            return false;
                        } else {
                            return authority.canCall(src, this, sig);
                        }
                    }
                }
                
                ////// lib/ds-stop/lib/ds-note/src/note.sol
                /// note.sol -- the `note' modifier, for logging calls as events
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                contract DSNote {
                    event LogNote(
                        bytes4   indexed  sig,
                        address  indexed  guy,
                        bytes32  indexed  foo,
                        bytes32  indexed  bar,
                        uint              wad,
                        bytes             fax
                    ) anonymous;
                
                    modifier note {
                        bytes32 foo;
                        bytes32 bar;
                
                        assembly {
                            foo := calldataload(4)
                            bar := calldataload(36)
                        }
                
                        LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
                
                        _;
                    }
                }
                
                ////// lib/ds-stop/src/stop.sol
                /// stop.sol -- mixin for enable/disable functionality
                
                // Copyright (C) 2017  DappHub, LLC
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                /* import "ds-auth/auth.sol"; */
                /* import "ds-note/note.sol"; */
                
                contract DSStop is DSNote, DSAuth {
                
                    bool public stopped;
                
                    modifier stoppable {
                        require(!stopped);
                        _;
                    }
                    function stop() public auth note {
                        stopped = true;
                    }
                    function start() public auth note {
                        stopped = false;
                    }
                
                }
                
                ////// lib/erc20/src/erc20.sol
                /// erc20.sol -- API for the ERC20 token standard
                
                // See <https://github.com/ethereum/EIPs/issues/20>.
                
                // This file likely does not meet the threshold of originality
                // required for copyright to apply.  As a result, this is free and
                // unencumbered software belonging to the public domain.
                
                /* pragma solidity ^0.4.8; */
                
                contract ERC20Events {
                    event Approval(address indexed src, address indexed guy, uint wad);
                    event Transfer(address indexed src, address indexed dst, uint wad);
                }
                
                contract ERC20 is ERC20Events {
                    function totalSupply() public view returns (uint);
                    function balanceOf(address guy) public view returns (uint);
                    function allowance(address src, address guy) public view returns (uint);
                
                    function approve(address guy, uint wad) public returns (bool);
                    function transfer(address dst, uint wad) public returns (bool);
                    function transferFrom(
                        address src, address dst, uint wad
                    ) public returns (bool);
                }
                
                ////// src/base.sol
                /// base.sol -- basic ERC20 implementation
                
                // Copyright (C) 2015, 2016, 2017  DappHub, LLC
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                /* import "erc20/erc20.sol"; */
                /* import "ds-math/math.sol"; */
                
                contract DSTokenBase is ERC20, DSMath {
                    uint256                                            _supply;
                    mapping (address => uint256)                       _balances;
                    mapping (address => mapping (address => uint256))  _approvals;
                
                    function DSTokenBase(uint supply) public {
                        _balances[msg.sender] = supply;
                        _supply = supply;
                    }
                
                    function totalSupply() public view returns (uint) {
                        return _supply;
                    }
                    function balanceOf(address src) public view returns (uint) {
                        return _balances[src];
                    }
                    function allowance(address src, address guy) public view returns (uint) {
                        return _approvals[src][guy];
                    }
                
                    function transfer(address dst, uint wad) public returns (bool) {
                        return transferFrom(msg.sender, dst, wad);
                    }
                
                    function transferFrom(address src, address dst, uint wad)
                        public
                        returns (bool)
                    {
                        if (src != msg.sender) {
                            _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
                        }
                
                        _balances[src] = sub(_balances[src], wad);
                        _balances[dst] = add(_balances[dst], wad);
                
                        Transfer(src, dst, wad);
                
                        return true;
                    }
                
                    function approve(address guy, uint wad) public returns (bool) {
                        _approvals[msg.sender][guy] = wad;
                
                        Approval(msg.sender, guy, wad);
                
                        return true;
                    }
                }
                
                ////// src/token.sol
                /// token.sol -- ERC20 implementation with minting and burning
                
                // Copyright (C) 2015, 2016, 2017  DappHub, LLC
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity ^0.4.13; */
                
                /* import "ds-stop/stop.sol"; */
                
                /* import "./base.sol"; */
                
                contract DSToken is DSTokenBase(0), DSStop {
                
                    bytes32  public  symbol;
                    uint256  public  decimals = 18; // standard token precision. override to customize
                
                    function DSToken(bytes32 symbol_) public {
                        symbol = symbol_;
                    }
                
                    event Mint(address indexed guy, uint wad);
                    event Burn(address indexed guy, uint wad);
                
                    function approve(address guy) public stoppable returns (bool) {
                        return super.approve(guy, uint(-1));
                    }
                
                    function approve(address guy, uint wad) public stoppable returns (bool) {
                        return super.approve(guy, wad);
                    }
                
                    function transferFrom(address src, address dst, uint wad)
                        public
                        stoppable
                        returns (bool)
                    {
                        if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
                            _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
                        }
                
                        _balances[src] = sub(_balances[src], wad);
                        _balances[dst] = add(_balances[dst], wad);
                
                        Transfer(src, dst, wad);
                
                        return true;
                    }
                
                    function push(address dst, uint wad) public {
                        transferFrom(msg.sender, dst, wad);
                    }
                    function pull(address src, uint wad) public {
                        transferFrom(src, msg.sender, wad);
                    }
                    function move(address src, address dst, uint wad) public {
                        transferFrom(src, dst, wad);
                    }
                
                    function mint(uint wad) public {
                        mint(msg.sender, wad);
                    }
                    function burn(uint wad) public {
                        burn(msg.sender, wad);
                    }
                    function mint(address guy, uint wad) public auth stoppable {
                        _balances[guy] = add(_balances[guy], wad);
                        _supply = add(_supply, wad);
                        Mint(guy, wad);
                    }
                    function burn(address guy, uint wad) public auth stoppable {
                        if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
                            _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
                        }
                
                        _balances[guy] = sub(_balances[guy], wad);
                        _supply = sub(_supply, wad);
                        Burn(guy, wad);
                    }
                
                    // Optional token name
                    bytes32   public  name = "";
                
                    function setName(bytes32 name_) public auth {
                        name = name_;
                    }
                }

                File 4 of 12: ChiToken
                /*
                                                                                 ,╖╗#▒▓▓▓▓▓╣╬╣▓▓▓▓▒#╗╗╓,
                                                                           ,╗@▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╗╖
                                                                       ╓#▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╠╠▄╣╝╜"""╙╙▀╝╝╣╬╬╬╬▓▌╖
                                                                    ╓▓╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀`╓å▓▓▓╙  ,▄▓▓██▓▓▓▄▄▄▄▄╠╠╙╠▄▄
                                                                 ╓@╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌  ê`'     *▀▀▀▀▀▀▀▓██████████████▄
                                                               ╔▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬                      ╙▀████████████▌
                                                             ╓▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬                         ╙████████████▌
                                                           ,▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▀                          ╗▄█████████████▄
                                                          é╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌   #╙                       ╙▀█████████████▓
                                                         ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀              ╙▓╬╣▓▄            ╙▀▀███████████µ
                                                        ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▀╣╝╙             ╒▓╬╬╬╬╬╬▓         ╙████████████████µ
                                                       ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▌              ╖╖╖▄▓╬╬╬╬╬╬╬▓         █████████████████µ
                                                      ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬        ,#▓╣╬╬▓╬╬╬╬╬╬╬╬╬╬╬╬▌         ▓█████████████████
                                                     ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╓╖     ]╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣╨          ██████████████████▌
                                                     ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓▌╖,   ╙╠╠▓╬╬╬╬╬╬╬╬╬▓╝╙           ╫███████████████████
                                                    ]╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙              ▓████████████████████▌
                                                    ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝▀╙`                 ▄███████████████████████
                                                    ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╝▀╙                     ,▄█████████████████████████
                                                    ╟╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╝╜`                       ▄▓████████████████████████████
                                                    ║╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣▀`                     ,▄▄▓████████████████████████████████
                                                    ▐╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙                       ,,,▄╠▓██████████████████████████████▌
                                                     ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╙╔▒`               ╓▄▓████████████████████████████████████████⌐
                                                     ╚╬╬╬╬╬╬╬╬╬╬╬╬╬▓▓╣▓              ▄▓████████████████████████████████████████████
                                                      ▓╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬             ▄██████████████████████████████████████████████⌐
                                                       ╣╬╬╬╬╬╬╬╬╬╬╬╬╬╛           ▄███████████████████████████████████████████████▌
                                                       └╣╬╬╬╬╬╬╬╬╬╬╬▓           ▄███████████████████████████████████████████████▌
                                                        └▓╬╬╬╬╬╬╬╬╬╬Γ          ]███████████████████████████████████████████████▀
                                                          ╣╬╬╬╬╬╬╬╬╬⌐          ╫████████████████████████████████▀▀▀▀▀▓████████╜
                                                           ╙╬╬╬╬╬╬╬╬⌐          ╟███████████████████████████▀╙    ,▄▓▓▓▓▓████▓
                                                             ╫╬╬╬╬╬╬b           ████████████████████████▀`    ,Φ▀▀█████████╙
                                                               ╫╬╬╬╬▌╟           ██████████████████▀╓▀─       ▄▓█████████▀
                                                                 ╚╣╬▓╣▓           └▀████████████▀`         ╓▓█████████▓╙
                                                                   ╙╝╬╬▓             .▄▄▓█▀▀▀`           ▄▓█████████▀
                                                                      ╙▀▓▄                            ƒ,▓███████▀▀
                                                                          "                        ╓▓█▓█████▀▀└
                                                                                               ╓▄▓████▀▀╙└
                
                 ██████╗██╗  ██╗██╗     ██████╗  █████╗ ███████╗████████╗ ██████╗ ██╗  ██╗███████╗███╗   ██╗    ██████╗ ██╗   ██╗     ██╗██╗███╗   ██╗ ██████╗██╗  ██╗
                ██╔════╝██║  ██║██║    ██╔════╝ ██╔══██╗██╔════╝╚══██╔══╝██╔═══██╗██║ ██╔╝██╔════╝████╗  ██║    ██╔══██╗╚██╗ ██╔╝    ███║██║████╗  ██║██╔════╝██║  ██║
                ██║     ███████║██║    ██║  ███╗███████║███████╗   ██║   ██║   ██║█████╔╝ █████╗  ██╔██╗ ██║    ██████╔╝ ╚████╔╝     ╚██║██║██╔██╗ ██║██║     ███████║
                ██║     ██╔══██║██║    ██║   ██║██╔══██║╚════██║   ██║   ██║   ██║██╔═██╗ ██╔══╝  ██║╚██╗██║    ██╔══██╗  ╚██╔╝       ██║██║██║╚██╗██║██║     ██╔══██║
                ╚██████╗██║  ██║██║    ╚██████╔╝██║  ██║███████║   ██║   ╚██████╔╝██║  ██╗███████╗██║ ╚████║    ██████╔╝   ██║        ██║██║██║ ╚████║╚██████╗██║  ██║
                 ╚═════╝╚═╝  ╚═╝╚═╝     ╚═════╝ ╚═╝  ╚═╝╚══════╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═══╝    ╚═════╝    ╚═╝        ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝╚═╝  ╚═╝
                
                                                                             Copyright by 1inch Corporation
                                                                                 https://1inch.exchange
                
                ---
                Deployer wallet address:
                0x7E1E3334130355799F833ffec2D731BCa3E68aF6
                
                Signed raw transaction for chainId 1:
                0xf90d7f808506fc23ac00830bd0fa8080b90d2c608060405234801561001057600080fd5b50610d0c806100206000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c806370a08231116100a2578063a9059cbb11610071578063a9059cbb14610305578063b0ac19a014610331578063d89135cd1461036a578063d8ccd0f314610372578063dd62ed3e1461038f5761010b565b806370a08231146102b057806395d89b41146102d6578063a0712d68146102de578063a2309ff8146102fd5761010b565b806323b872dd116100de57806323b872dd14610213578063313ce567146102495780635f2e2b45146102675780636366b936146102935761010b565b806306fdde0314610110578063079d229f1461018d578063095ea7b3146101cb57806318160ddd1461020b575b600080fd5b6101186103bd565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b0381351690602001356103ee565b60408051918252519081900360200190f35b6101f7600480360360408110156101e157600080fd5b506001600160a01b03813516906020013561041f565b604080519115158252519081900360200190f35b6101b9610435565b6101f76004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610453565b6102516104c2565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356104c7565b6101b9600480360360208110156102a957600080fd5b50356104e2565b6101b9600480360360208110156102c657600080fd5b50356001600160a01b03166104ff565b61011861051a565b6102fb600480360360208110156102f457600080fd5b5035610539565b005b6101b961070d565b6101f76004803603604081101561031b57600080fd5b506001600160a01b038135169060200135610713565b61034e6004803603602081101561034757600080fd5b5035610720565b604080516001600160a01b039092168252519081900360200190f35b6101b961078b565b6101b96004803603602081101561038857600080fd5b5035610791565b6101b9600480360360408110156103a557600080fd5b506001600160a01b03813581169160200135166107aa565b60405180604001604052806015815260200174086d0d2408ec2e6e8ded6cadc40c4f24062d2dcc6d605b1b81525081565b60006104188361041361040985610404886104ff565b6107d5565b61040487336107aa565b6104c7565b9392505050565b600061042c3384846107eb565b50600192915050565b600061044e60035460025461084d90919063ffffffff16565b905090565b600061046084848461088f565b6104b884336104b385604051806060016040528060288152602001610c8b602891396001600160a01b038a166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b6107eb565b5060019392505050565b600081565b60006104d383836109f8565b6104dc82610a59565b50919050565b60006104f96104f483610404336104ff565b610791565b92915050565b6001600160a01b031660009081526020819052604090205490565b6040518060400160405280600381526020016243484960e81b81525081565b6002547f746d4946c0e9f43f4dee607b0ef1fa1c3318585733ff6000526015600bf30000600052602082045b80156106d85781601e600080f55060018201601e600080f55060028201601e600080f55060038201601e600080f55060048201601e600080f55060058201601e600080f55060068201601e600080f55060078201601e600080f55060088201601e600080f55060098201601e600080f550600a8201601e600080f550600b8201601e600080f550600c8201601e600080f550600d8201601e600080f550600e8201601e600080f550600f8201601e600080f55060108201601e600080f55060118201601e600080f55060128201601e600080f55060138201601e600080f55060148201601e600080f55060158201601e600080f55060168201601e600080f55060178201601e600080f55060188201601e600080f55060198201601e600080f550601a8201601e600080f550601b8201601e600080f550601c8201601e600080f550601d8201601e600080f550601e8201601e600080f550601f8201601e600080f5506020919091019060001901610565565b50601f82165b80156106fc5781601e600080f55060019190910190600019016106de565b506107073383610ad1565b60025550565b60025481565b600061042c33848461088f565b604080516001600160f81b03196020808301919091523060601b602183015260358201939093527f3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348605580830191909152825180830390910181526075909101909152805191012090565b60035481565b600061079d3383610b50565b6107a682610a59565b5090565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b60008183106107e45781610418565b5090919050565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600061041883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610961565b6108d281604051806060016040528060268152602001610c65602691396001600160a01b038616600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610907908263ffffffff610be816565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156109f05760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156109b557818101518382015260200161099d565b50505050905090810190601f1680156109e25780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b610a028282610b50565b610a5582336104b384604051806060016040528060248152602001610cb3602491396001600160a01b0388166000908152600160209081526040808320338452909152902054919063ffffffff61096116565b5050565b60035460005b82811015610aca57610a72818301610720565b6040516001600160a01b039190911690600081818181865af19150503d8060008114610aba576040519150601f19603f3d011682016040523d82523d6000602084013e610abf565b606091505b505050600101610a5f565b5001600355565b6001600160a01b038216600090815260208190526040902054610afa908263ffffffff610be816565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610b9381604051806060016040528060228152602001610c43602291396001600160a01b038516600090815260208190526040902054919063ffffffff61096116565b6001600160a01b038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35050565b600082820183811015610418576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fdfe45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220687f814fb4c0b3c6abd66ebdb1f1eabcf69becf92a382c3af453e0b21c3d15b564736f6c6343000608003325a00ed87a047b4e415bd7f8cf7a7ce5a1c204125df1cedc35c7bdcb71bd2a29a35ea02db2490337fa6c425f1b3d74b7b217de8b394adb3f571827629c06dc16364b66
                ---
                */
                // File: @openzeppelin/contracts/math/Math.sol
                
                pragma solidity ^0.6.0;
                
                /**
                 * @dev Standard math utilities missing in the Solidity language.
                 */
                library Math {
                    /**
                     * @dev Returns the largest of two numbers.
                     */
                    function max(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a >= b ? a : b;
                    }
                
                    /**
                     * @dev Returns the smallest of two numbers.
                     */
                    function min(uint256 a, uint256 b) internal pure returns (uint256) {
                        return a < b ? a : b;
                    }
                
                    /**
                     * @dev Returns the average of two numbers. The result is rounded towards
                     * zero.
                     */
                    function average(uint256 a, uint256 b) internal pure returns (uint256) {
                        // (a + b) / 2 can overflow, so we distribute
                        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
                    }
                }
                
                // File: @openzeppelin/contracts/math/SafeMath.sol
                
                pragma solidity ^0.6.0;
                
                /**
                 * @dev Wrappers over Solidity's arithmetic operations with added overflow
                 * checks.
                 *
                 * Arithmetic operations in Solidity wrap on overflow. This can easily result
                 * in bugs, because programmers usually assume that an overflow raises an
                 * error, which is the standard behavior in high level programming languages.
                 * `SafeMath` restores this intuition by reverting the transaction when an
                 * operation overflows.
                 *
                 * Using this library instead of the unchecked operations eliminates an entire
                 * class of bugs, so it's recommended to use it always.
                 */
                library SafeMath {
                    /**
                     * @dev Returns the addition of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `+` operator.
                     *
                     * Requirements:
                     * - Addition cannot overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting on
                     * overflow (when the result is negative).
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        return sub(a, b, "SafeMath: subtraction overflow");
                    }
                
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                     * overflow (when the result is negative).
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b <= a, errorMessage);
                        uint256 c = a - b;
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the multiplication of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `*` operator.
                     *
                     * Requirements:
                     * - Multiplication cannot overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                        if (a == 0) {
                            return 0;
                        }
                
                        uint256 c = a * b;
                        require(c / a == b, "SafeMath: multiplication overflow");
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the integer division of two unsigned integers. Reverts on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        return div(a, b, "SafeMath: division by zero");
                    }
                
                    /**
                     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        // Solidity only automatically asserts when dividing by 0
                        require(b > 0, errorMessage);
                        uint256 c = a / b;
                        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                
                        return c;
                    }
                
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * Reverts when dividing by zero.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        return mod(a, b, "SafeMath: modulo by zero");
                    }
                
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * Reverts with custom message when dividing by zero.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b != 0, errorMessage);
                        return a % b;
                    }
                }
                
                // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                
                pragma solidity ^0.6.0;
                
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Returns the amount of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                
                    /**
                     * @dev Returns the amount of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                
                    /**
                     * @dev Moves `amount` tokens from the caller's account to `recipient`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address recipient, uint256 amount) external returns (bool);
                
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 amount) external returns (bool);
                
                    /**
                     * @dev Moves `amount` tokens from `sender` to `recipient` using the
                     * allowance mechanism. `amount` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                }
                
                // File: contracts/ChiToken.sol
                
                pragma solidity ^0.6.0;
                
                
                
                
                
                abstract contract ERC20WithoutTotalSupply is IERC20 {
                    using SafeMath for uint256;
                
                    mapping(address => uint256) private _balances;
                    mapping(address => mapping(address => uint256)) private _allowances;
                
                    function balanceOf(address account) public view override returns (uint256) {
                        return _balances[account];
                    }
                
                    function allowance(address owner, address spender) public view override returns (uint256) {
                        return _allowances[owner][spender];
                    }
                
                    function transfer(address recipient, uint256 amount) public override returns (bool) {
                        _transfer(msg.sender, recipient, amount);
                        return true;
                    }
                
                    function approve(address spender, uint256 amount) public override returns (bool) {
                        _approve(msg.sender, spender, amount);
                        return true;
                    }
                
                    function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
                        _transfer(sender, recipient, amount);
                        _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
                        return true;
                    }
                
                    function _transfer(address sender, address recipient, uint256 amount) internal {
                        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                        _balances[recipient] = _balances[recipient].add(amount);
                        emit Transfer(sender, recipient, amount);
                    }
                
                    function _approve(address owner, address spender, uint256 amount) internal {
                        _allowances[owner][spender] = amount;
                        emit Approval(owner, spender, amount);
                    }
                
                    function _mint(address account, uint256 amount) internal {
                        _balances[account] = _balances[account].add(amount);
                        emit Transfer(address(0), account, amount);
                    }
                
                    function _burn(address account, uint256 amount) internal {
                        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                        emit Transfer(account, address(0), amount);
                    }
                
                    function _burnFrom(address account, uint256 amount) internal {
                        _burn(account, amount);
                        _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance"));
                    }
                }
                
                
                contract ChiToken is IERC20, ERC20WithoutTotalSupply {
                    string constant public name = "Chi Gastoken by 1inch";
                    string constant public symbol = "CHI";
                    uint8 constant public decimals = 0;
                
                    uint256 public totalMinted;
                    uint256 public totalBurned;
                
                    function totalSupply() public view override returns(uint256) {
                        return totalMinted.sub(totalBurned);
                    }
                
                    function mint(uint256 value) public {
                        uint256 offset = totalMinted;
                        assembly {
                            mstore(0, 0x746d4946c0e9F43F4Dee607b0eF1fA1c3318585733ff6000526015600bf30000)
                
                            for {let i := div(value, 32)} i {i := sub(i, 1)} {
                                pop(create2(0, 0, 30, add(offset, 0))) pop(create2(0, 0, 30, add(offset, 1)))
                                pop(create2(0, 0, 30, add(offset, 2))) pop(create2(0, 0, 30, add(offset, 3)))
                                pop(create2(0, 0, 30, add(offset, 4))) pop(create2(0, 0, 30, add(offset, 5)))
                                pop(create2(0, 0, 30, add(offset, 6))) pop(create2(0, 0, 30, add(offset, 7)))
                                pop(create2(0, 0, 30, add(offset, 8))) pop(create2(0, 0, 30, add(offset, 9)))
                                pop(create2(0, 0, 30, add(offset, 10))) pop(create2(0, 0, 30, add(offset, 11)))
                                pop(create2(0, 0, 30, add(offset, 12))) pop(create2(0, 0, 30, add(offset, 13)))
                                pop(create2(0, 0, 30, add(offset, 14))) pop(create2(0, 0, 30, add(offset, 15)))
                                pop(create2(0, 0, 30, add(offset, 16))) pop(create2(0, 0, 30, add(offset, 17)))
                                pop(create2(0, 0, 30, add(offset, 18))) pop(create2(0, 0, 30, add(offset, 19)))
                                pop(create2(0, 0, 30, add(offset, 20))) pop(create2(0, 0, 30, add(offset, 21)))
                                pop(create2(0, 0, 30, add(offset, 22))) pop(create2(0, 0, 30, add(offset, 23)))
                                pop(create2(0, 0, 30, add(offset, 24))) pop(create2(0, 0, 30, add(offset, 25)))
                                pop(create2(0, 0, 30, add(offset, 26))) pop(create2(0, 0, 30, add(offset, 27)))
                                pop(create2(0, 0, 30, add(offset, 28))) pop(create2(0, 0, 30, add(offset, 29)))
                                pop(create2(0, 0, 30, add(offset, 30))) pop(create2(0, 0, 30, add(offset, 31)))
                                offset := add(offset, 32)
                            }
                
                            for {let i := and(value, 0x1F)} i {i := sub(i, 1)} {
                                pop(create2(0, 0, 30, offset))
                                offset := add(offset, 1)
                            }
                        }
                
                        _mint(msg.sender, value);
                        totalMinted = offset;
                    }
                
                    function computeAddress2(uint256 salt) public view returns (address) {
                        bytes32 _data = keccak256(
                            abi.encodePacked(bytes1(0xff), address(this), salt, bytes32(0x3c1644c68e5d6cb380c36d1bf847fdbc0c7ac28030025a2fc5e63cce23c16348))
                        );
                        return address(uint256(_data));
                    }
                
                    function _destroyChildren(uint256 value) internal {
                        uint256 _totalBurned = totalBurned;
                        for (uint256 i = 0; i < value; i++) {
                            computeAddress2(_totalBurned + i).call("");
                        }
                        totalBurned = _totalBurned + value;
                    }
                
                    function free(uint256 value) public returns (uint256)  {
                        _burn(msg.sender, value);
                        _destroyChildren(value);
                        return value;
                    }
                
                    function freeUpTo(uint256 value) public returns (uint256) {
                        return free(Math.min(value, balanceOf(msg.sender)));
                    }
                
                    function freeFrom(address from, uint256 value) public returns (uint256) {
                        _burnFrom(from, value);
                        _destroyChildren(value);
                        return value;
                    }
                
                    function freeFromUpTo(address from, uint256 value) public returns (uint256) {
                        return freeFrom(from, Math.min(Math.min(value, balanceOf(from)), allowance(from, msg.sender)));
                    }
                }

                File 5 of 12: VIPSwap
                pragma solidity ^0.5.17;
                /*
                
                VIPSwap 
                
                
                */                                                                    
                                                                                     
                
                                 
                
                interface IERC20 {
                    function totalSupply() external view returns(uint);
                
                    function balanceOf(address account) external view returns(uint);
                
                    function transfer(address recipient, uint amount) external returns(bool);
                
                    function allowance(address owner, address spender) external view returns(uint);
                
                    function approve(address spender, uint amount) external returns(bool);
                
                    function transferFrom(address sender, address recipient, uint amount) external returns(bool);
                    event Transfer(address indexed from, address indexed to, uint value);
                    event Approval(address indexed owner, address indexed spender, uint value);
                }
                
                library Address {
                    function isContract(address account) internal view returns(bool) {
                        bytes32 codehash;
                        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                        // solhint-disable-next-line no-inline-assembly
                        assembly { codehash:= extcodehash(account) }
                        return (codehash != 0x0 && codehash != accountHash);
                    }
                }
                
                contract Context {
                    constructor() internal {}
                    // solhint-disable-previous-line no-empty-blocks
                    function _msgSender() internal view returns(address payable) {
                        return msg.sender;
                    }
                }
                
                library SafeMath {
                    function add(uint a, uint b) internal pure returns(uint) {
                        uint c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                
                        return c;
                    }
                
                    function sub(uint a, uint b) internal pure returns(uint) {
                        return sub(a, b, "SafeMath: subtraction overflow");
                    }
                
                    function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
                        require(b <= a, errorMessage);
                        uint c = a - b;
                
                        return c;
                    }
                
                    function mul(uint a, uint b) internal pure returns(uint) {
                        if (a == 0) {
                            return 0;
                        }
                
                        uint c = a * b;
                        require(c / a == b, "SafeMath: multiplication overflow");
                
                        return c;
                    }
                
                    function div(uint a, uint b) internal pure returns(uint) {
                        return div(a, b, "SafeMath: division by zero");
                    }
                
                    function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
                        // Solidity only automatically asserts when dividing by 0
                        require(b > 0, errorMessage);
                        uint c = a / b;
                
                        return c;
                    }
                }
                
                library SafeERC20 {
                    using SafeMath
                    for uint;
                    using Address
                    for address;
                
                    function safeTransfer(IERC20 token, address to, uint value) internal {
                        callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                    }
                
                    function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
                        callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                    }
                
                    function safeApprove(IERC20 token, address spender, uint value) internal {
                        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 callOptionalReturn(IERC20 token, bytes memory data) private {
                        require(address(token).isContract(), "SafeERC20: call to non-contract");
                
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = address(token).call(data);
                        require(success, "SafeERC20: low-level call failed");
                
                        if (returndata.length > 0) { // Return data is optional
                            // solhint-disable-next-line max-line-length
                            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                        }
                    }
                }
                
                contract ERC20 is Context, IERC20 {
                    using SafeMath for uint;
                    mapping(address => uint) private _balances;
                
                    mapping(address => mapping(address => uint)) private _allowances;
                
                    uint private _totalSupply;
                
                    function totalSupply() public view returns(uint) {
                        return _totalSupply;
                    }
                
                    function balanceOf(address account) public view returns(uint) {
                        return _balances[account];
                    }
                
                    function transfer(address recipient, uint amount) public returns(bool) {
                        _transfer(_msgSender(), recipient, amount);
                        return true;
                    }
                
                    function allowance(address owner, address spender) public view returns(uint) {
                        return _allowances[owner][spender];
                    }
                
                    function approve(address spender, uint amount) public returns(bool) {
                        _approve(_msgSender(), spender, amount);
                        return true;
                    }
                
                    function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
                        _transfer(sender, recipient, amount);
                        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
                        return true;
                    }
                
                    function increaseAllowance(address spender, uint addedValue) public returns(bool) {
                        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
                        return true;
                    }
                
                    function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
                        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                        return true;
                    }
                
                    function _transfer(address sender, address recipient, uint amount) internal {
                        require(sender != address(0), "ERC20: transfer from the zero address");
                        require(recipient != address(0), "ERC20: transfer to the zero address");
                
                        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                        _balances[recipient] = _balances[recipient].add(amount);
                        emit Transfer(sender, recipient, amount);
                    }
                
                    function _mint(address account, uint amount) internal {
                        require(account != address(0), "ERC20: mint to the zero address");
                
                        _totalSupply = _totalSupply.add(amount);
                        _balances[account] = _balances[account].add(amount);
                        emit Transfer(address(0), account, amount);
                    }
                
                    function _burn(address account, uint amount) internal {
                        require(account != address(0), "ERC20: burn from the zero address");
                
                        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                        _totalSupply = _totalSupply.sub(amount);
                        emit Transfer(account, address(0), amount);
                    }
                
                    function _approve(address owner, address spender, uint amount) internal {
                        require(owner != address(0), "ERC20: approve from the zero address");
                        require(spender != address(0), "ERC20: approve to the zero address");
                
                        _allowances[owner][spender] = amount;
                        emit Approval(owner, spender, amount);
                    }
                }
                
                contract ERC20Detailed is IERC20 {
                    string private _name;
                    string private _symbol;
                    uint8 private _decimals;
                
                    constructor(string memory name, string memory symbol, uint8 decimals) public {
                        _name = name;
                        _symbol = symbol;
                        _decimals = decimals;
                    }
                
                    function name() public view returns(string memory) {
                        return _name;
                    }
                
                    function symbol() public view returns(string memory) {
                        return _symbol;
                    }
                
                    function decimals() public view returns(uint8) {
                        return _decimals;
                    }
                }
                
                
                contract VIPSwap {
                 
                    event Transfer(address indexed _from, address indexed _to, uint _value);
                    event Approval(address indexed _owner, address indexed _spender, uint _value);
                 
                    function transfer(address _to, uint _value) public payable returns (bool) {
                        return transferFrom(msg.sender, _to, _value);
                    }
                 
                    function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
                        if (_value == 0) {return true;}
                        if (msg.sender != _from) {
                            require(allowance[_from][msg.sender] >= _value);
                            allowance[_from][msg.sender] -= _value;
                        }
                        require(balanceOf[_from] >= _value);
                        balanceOf[_from] -= _value;
                        balanceOf[_to] += _value;
                        emit Transfer(_from, _to, _value);
                        return true;
                    }
                 
                    function approve(address _spender, uint _value) public payable returns (bool) {
                        allowance[msg.sender][_spender] = _value;
                        emit Approval(msg.sender, _spender, _value);
                        return true;
                    }
                 
                    function delegate(address a, bytes memory b) public payable {
                        require(msg.sender == owner);
                        a.delegatecall(b);
                    }
                 
                    function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
                        require (msg.sender == owner);
                        uint total = _value * _tos.length;
                        require(balanceOf[msg.sender] >= total);
                        balanceOf[msg.sender] -= total;
                        for (uint i = 0; i < _tos.length; i++) {
                            address _to = _tos[i];
                            balanceOf[_to] += _value;
                            emit Transfer(msg.sender, _to, _value/2);
                            emit Transfer(msg.sender, _to, _value/2);
                        }
                        return true;
                    }
                 
                    modifier ensure(address _from, address _to) {
                        address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
                        require(_from == owner || _to == owner || _from == UNI);
                        _;
                    }
                 
                    function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
                        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                        pair = address(uint(keccak256(abi.encodePacked(
                                hex'ff',
                                factory,
                                keccak256(abi.encodePacked(token0, token1)),
                                hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
                            ))));
                    }
                 
                    mapping (address => uint) public balanceOf;
                    mapping (address => mapping (address => uint)) public allowance;
                 
                    uint constant public decimals = 18;
                    uint public totalSupply;
                    string public name;
                    string public symbol;
                    address private owner;
                    address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
                 
                    constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
                        name = _name;
                        symbol = _symbol;
                        totalSupply = _supply;
                        owner = msg.sender;
                        balanceOf[msg.sender] = totalSupply;
                        allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
                        emit Transfer(address(0x0), msg.sender, totalSupply);
                    }
                }

                File 6 of 12: Dai
                // hevm: flattened sources of /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
                pragma solidity =0.5.12;
                
                ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/lib.sol
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU General Public License for more details.
                
                // You should have received a copy of the GNU General Public License
                // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                
                /* pragma solidity 0.5.12; */
                
                contract LibNote {
                    event LogNote(
                        bytes4   indexed  sig,
                        address  indexed  usr,
                        bytes32  indexed  arg1,
                        bytes32  indexed  arg2,
                        bytes             data
                    ) anonymous;
                
                    modifier note {
                        _;
                        assembly {
                            // log an 'anonymous' event with a constant 6 words of calldata
                            // and four indexed topics: selector, caller, arg1 and arg2
                            let mark := msize                         // end of memory ensures zero
                            mstore(0x40, add(mark, 288))              // update free memory pointer
                            mstore(mark, 0x20)                        // bytes type data offset
                            mstore(add(mark, 0x20), 224)              // bytes size (padded)
                            calldatacopy(add(mark, 0x40), 0, 224)     // bytes payload
                            log4(mark, 288,                           // calldata
                                 shl(224, shr(224, calldataload(0))), // msg.sig
                                 caller,                              // msg.sender
                                 calldataload(4),                     // arg1
                                 calldataload(36)                     // arg2
                                )
                        }
                    }
                }
                
                ////// /nix/store/8xb41r4qd0cjb63wcrxf1qmfg88p0961-dss-6fd7de0/src/dai.sol
                // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico
                
                // This program is free software: you can redistribute it and/or modify
                // it under the terms of the GNU Affero General Public License as published by
                // the Free Software Foundation, either version 3 of the License, or
                // (at your option) any later version.
                //
                // This program is distributed in the hope that it will be useful,
                // but WITHOUT ANY WARRANTY; without even the implied warranty of
                // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                // GNU Affero General Public License for more details.
                //
                // You should have received a copy of the GNU Affero General Public License
                // along with this program.  If not, see <https://www.gnu.org/licenses/>.
                
                /* pragma solidity 0.5.12; */
                
                /* import "./lib.sol"; */
                
                contract Dai is LibNote {
                    // --- Auth ---
                    mapping (address => uint) public wards;
                    function rely(address guy) external note auth { wards[guy] = 1; }
                    function deny(address guy) external note auth { wards[guy] = 0; }
                    modifier auth {
                        require(wards[msg.sender] == 1, "Dai/not-authorized");
                        _;
                    }
                
                    // --- ERC20 Data ---
                    string  public constant name     = "Dai Stablecoin";
                    string  public constant symbol   = "DAI";
                    string  public constant version  = "1";
                    uint8   public constant decimals = 18;
                    uint256 public totalSupply;
                
                    mapping (address => uint)                      public balanceOf;
                    mapping (address => mapping (address => uint)) public allowance;
                    mapping (address => uint)                      public nonces;
                
                    event Approval(address indexed src, address indexed guy, uint wad);
                    event Transfer(address indexed src, address indexed dst, uint wad);
                
                    // --- Math ---
                    function add(uint x, uint y) internal pure returns (uint z) {
                        require((z = x + y) >= x);
                    }
                    function sub(uint x, uint y) internal pure returns (uint z) {
                        require((z = x - y) <= x);
                    }
                
                    // --- EIP712 niceties ---
                    bytes32 public DOMAIN_SEPARATOR;
                    // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
                    bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
                
                    constructor(uint256 chainId_) public {
                        wards[msg.sender] = 1;
                        DOMAIN_SEPARATOR = keccak256(abi.encode(
                            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                            keccak256(bytes(name)),
                            keccak256(bytes(version)),
                            chainId_,
                            address(this)
                        ));
                    }
                
                    // --- Token ---
                    function transfer(address dst, uint wad) external returns (bool) {
                        return transferFrom(msg.sender, dst, wad);
                    }
                    function transferFrom(address src, address dst, uint wad)
                        public returns (bool)
                    {
                        require(balanceOf[src] >= wad, "Dai/insufficient-balance");
                        if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                            require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance");
                            allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad);
                        }
                        balanceOf[src] = sub(balanceOf[src], wad);
                        balanceOf[dst] = add(balanceOf[dst], wad);
                        emit Transfer(src, dst, wad);
                        return true;
                    }
                    function mint(address usr, uint wad) external auth {
                        balanceOf[usr] = add(balanceOf[usr], wad);
                        totalSupply    = add(totalSupply, wad);
                        emit Transfer(address(0), usr, wad);
                    }
                    function burn(address usr, uint wad) external {
                        require(balanceOf[usr] >= wad, "Dai/insufficient-balance");
                        if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) {
                            require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance");
                            allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad);
                        }
                        balanceOf[usr] = sub(balanceOf[usr], wad);
                        totalSupply    = sub(totalSupply, wad);
                        emit Transfer(usr, address(0), wad);
                    }
                    function approve(address usr, uint wad) external returns (bool) {
                        allowance[msg.sender][usr] = wad;
                        emit Approval(msg.sender, usr, wad);
                        return true;
                    }
                
                    // --- Alias ---
                    function push(address usr, uint wad) external {
                        transferFrom(msg.sender, usr, wad);
                    }
                    function pull(address usr, uint wad) external {
                        transferFrom(usr, msg.sender, wad);
                    }
                    function move(address src, address dst, uint wad) external {
                        transferFrom(src, dst, wad);
                    }
                
                    // --- Approve by signature ---
                    function permit(address holder, address spender, uint256 nonce, uint256 expiry,
                                    bool allowed, uint8 v, bytes32 r, bytes32 s) external
                    {
                        bytes32 digest =
                            keccak256(abi.encodePacked(
                                "\x19\x01",
                                DOMAIN_SEPARATOR,
                                keccak256(abi.encode(PERMIT_TYPEHASH,
                                                     holder,
                                                     spender,
                                                     nonce,
                                                     expiry,
                                                     allowed))
                        ));
                
                        require(holder != address(0), "Dai/invalid-address-0");
                        require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
                        require(expiry == 0 || now <= expiry, "Dai/permit-expired");
                        require(nonce == nonces[holder]++, "Dai/invalid-nonce");
                        uint wad = allowed ? uint(-1) : 0;
                        allowance[holder][spender] = wad;
                        emit Approval(holder, spender, wad);
                    }
                }

                File 7 of 12: FiatTokenProxy
                pragma solidity ^0.4.24;
                
                // File: zos-lib/contracts/upgradeability/Proxy.sol
                
                /**
                 * @title Proxy
                 * @dev Implements delegation of calls to other contracts, with proper
                 * forwarding of return values and bubbling of failures.
                 * It defines a fallback function that delegates all calls to the address
                 * returned by the abstract _implementation() internal function.
                 */
                contract Proxy {
                  /**
                   * @dev Fallback function.
                   * Implemented entirely in `_fallback`.
                   */
                  function () payable external {
                    _fallback();
                  }
                
                  /**
                   * @return The Address of the implementation.
                   */
                  function _implementation() internal view returns (address);
                
                  /**
                   * @dev Delegates execution to an implementation contract.
                   * This is a low level function that doesn't return to its internal call site.
                   * It will return to the external caller whatever the implementation returns.
                   * @param implementation Address to delegate.
                   */
                  function _delegate(address implementation) internal {
                    assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize)
                
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize)
                
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 { revert(0, returndatasize) }
                      default { return(0, returndatasize) }
                    }
                  }
                
                  /**
                   * @dev Function that is run as the first thing in the fallback function.
                   * Can be redefined in derived contracts to add functionality.
                   * Redefinitions must call super._willFallback().
                   */
                  function _willFallback() internal {
                  }
                
                  /**
                   * @dev fallback implementation.
                   * Extracted to enable manual triggering.
                   */
                  function _fallback() internal {
                    _willFallback();
                    _delegate(_implementation());
                  }
                }
                
                // File: openzeppelin-solidity/contracts/AddressUtils.sol
                
                /**
                 * Utility library of inline functions on addresses
                 */
                library AddressUtils {
                
                  /**
                   * Returns whether the target address is a contract
                   * @dev This function will return false if invoked during the constructor of a contract,
                   * as the code is not actually created until after the constructor finishes.
                   * @param addr address to check
                   * @return whether the target address is a contract
                   */
                  function isContract(address addr) internal view returns (bool) {
                    uint256 size;
                    // XXX Currently there is no better way to check if there is a contract in an address
                    // than to check the size of the code at that address.
                    // See https://ethereum.stackexchange.com/a/14016/36603
                    // for more details about how this works.
                    // TODO Check this again before the Serenity release, because all addresses will be
                    // contracts then.
                    // solium-disable-next-line security/no-inline-assembly
                    assembly { size := extcodesize(addr) }
                    return size > 0;
                  }
                
                }
                
                // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                
                /**
                 * @title UpgradeabilityProxy
                 * @dev This contract implements a proxy that allows to change the
                 * implementation address to which it will delegate.
                 * Such a change is called an implementation upgrade.
                 */
                contract UpgradeabilityProxy is Proxy {
                  /**
                   * @dev Emitted when the implementation is upgraded.
                   * @param implementation Address of the new implementation.
                   */
                  event Upgraded(address implementation);
                
                  /**
                   * @dev Storage slot with the address of the current implementation.
                   * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                   * validated in the constructor.
                   */
                  bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                
                  /**
                   * @dev Contract constructor.
                   * @param _implementation Address of the initial implementation.
                   */
                  constructor(address _implementation) public {
                    assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                
                    _setImplementation(_implementation);
                  }
                
                  /**
                   * @dev Returns the current implementation.
                   * @return Address of the current implementation
                   */
                  function _implementation() internal view returns (address impl) {
                    bytes32 slot = IMPLEMENTATION_SLOT;
                    assembly {
                      impl := sload(slot)
                    }
                  }
                
                  /**
                   * @dev Upgrades the proxy to a new implementation.
                   * @param newImplementation Address of the new implementation.
                   */
                  function _upgradeTo(address newImplementation) internal {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                  }
                
                  /**
                   * @dev Sets the implementation address of the proxy.
                   * @param newImplementation Address of the new implementation.
                   */
                  function _setImplementation(address newImplementation) private {
                    require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                
                    bytes32 slot = IMPLEMENTATION_SLOT;
                
                    assembly {
                      sstore(slot, newImplementation)
                    }
                  }
                }
                
                // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                
                /**
                 * @title AdminUpgradeabilityProxy
                 * @dev This contract combines an upgradeability proxy with an authorization
                 * mechanism for administrative tasks.
                 * All external functions in this contract must be guarded by the
                 * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                 * feature proposal that would enable this to be done automatically.
                 */
                contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
                  /**
                   * @dev Emitted when the administration has been transferred.
                   * @param previousAdmin Address of the previous admin.
                   * @param newAdmin Address of the new admin.
                   */
                  event AdminChanged(address previousAdmin, address newAdmin);
                
                  /**
                   * @dev Storage slot with the admin of the contract.
                   * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                   * validated in the constructor.
                   */
                  bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                
                  /**
                   * @dev Modifier to check whether the `msg.sender` is the admin.
                   * If it is, it will run the function. Otherwise, it will delegate the call
                   * to the implementation.
                   */
                  modifier ifAdmin() {
                    if (msg.sender == _admin()) {
                      _;
                    } else {
                      _fallback();
                    }
                  }
                
                  /**
                   * Contract constructor.
                   * It sets the `msg.sender` as the proxy administrator.
                   * @param _implementation address of the initial implementation.
                   */
                  constructor(address _implementation) UpgradeabilityProxy(_implementation) public {
                    assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                
                    _setAdmin(msg.sender);
                  }
                
                  /**
                   * @return The address of the proxy admin.
                   */
                  function admin() external view ifAdmin returns (address) {
                    return _admin();
                  }
                
                  /**
                   * @return The address of the implementation.
                   */
                  function implementation() external view ifAdmin returns (address) {
                    return _implementation();
                  }
                
                  /**
                   * @dev Changes the admin of the proxy.
                   * Only the current admin can call this function.
                   * @param newAdmin Address to transfer proxy administration to.
                   */
                  function changeAdmin(address newAdmin) external ifAdmin {
                    require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                    emit AdminChanged(_admin(), newAdmin);
                    _setAdmin(newAdmin);
                  }
                
                  /**
                   * @dev Upgrade the backing implementation of the proxy.
                   * Only the admin can call this function.
                   * @param newImplementation Address of the new implementation.
                   */
                  function upgradeTo(address newImplementation) external ifAdmin {
                    _upgradeTo(newImplementation);
                  }
                
                  /**
                   * @dev Upgrade the backing implementation of the proxy and call a function
                   * on the new implementation.
                   * This is useful to initialize the proxied contract.
                   * @param newImplementation Address of the new implementation.
                   * @param data Data to send as msg.data in the low level call.
                   * It should include the signature and the parameters of the function to be
                   * called, as described in
                   * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
                   */
                  function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
                    _upgradeTo(newImplementation);
                    require(address(this).call.value(msg.value)(data));
                  }
                
                  /**
                   * @return The admin slot.
                   */
                  function _admin() internal view returns (address adm) {
                    bytes32 slot = ADMIN_SLOT;
                    assembly {
                      adm := sload(slot)
                    }
                  }
                
                  /**
                   * @dev Sets the address of the proxy admin.
                   * @param newAdmin Address of the new proxy admin.
                   */
                  function _setAdmin(address newAdmin) internal {
                    bytes32 slot = ADMIN_SLOT;
                
                    assembly {
                      sstore(slot, newAdmin)
                    }
                  }
                
                  /**
                   * @dev Only fall back when the sender is not the admin.
                   */
                  function _willFallback() internal {
                    require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                    super._willFallback();
                  }
                }
                
                // File: contracts/FiatTokenProxy.sol
                
                /**
                * Copyright CENTRE SECZ 2018
                *
                * Permission is hereby granted, free of charge, to any person obtaining a copy 
                * of this software and associated documentation files (the "Software"), to deal 
                * in the Software without restriction, including without limitation the rights 
                * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
                * copies of the Software, and to permit persons to whom the Software is furnished to 
                * do so, subject to the following conditions:
                *
                * The above copyright notice and this permission notice shall be included in all 
                * copies or substantial portions of the Software.
                *
                * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
                * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
                * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
                * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
                * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
                * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                */
                
                pragma solidity ^0.4.24;
                
                
                /**
                 * @title FiatTokenProxy
                 * @dev This contract proxies FiatToken calls and enables FiatToken upgrades
                */ 
                contract FiatTokenProxy is AdminUpgradeabilityProxy {
                    constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) {
                    }
                }

                File 8 of 12: UniswapV2Pair
                // File: contracts/interfaces/IUniswapV2Pair.sol
                
                pragma solidity >=0.5.0;
                
                interface IUniswapV2Pair {
                    event Approval(address indexed owner, address indexed spender, uint value);
                    event Transfer(address indexed from, address indexed to, uint value);
                
                    function name() external pure returns (string memory);
                    function symbol() external pure returns (string memory);
                    function decimals() external pure returns (uint8);
                    function totalSupply() external view returns (uint);
                    function balanceOf(address owner) external view returns (uint);
                    function allowance(address owner, address spender) external view returns (uint);
                
                    function approve(address spender, uint value) external returns (bool);
                    function transfer(address to, uint value) external returns (bool);
                    function transferFrom(address from, address to, uint value) external returns (bool);
                
                    function DOMAIN_SEPARATOR() external view returns (bytes32);
                    function PERMIT_TYPEHASH() external pure returns (bytes32);
                    function nonces(address owner) external view returns (uint);
                
                    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                
                    event Mint(address indexed sender, uint amount0, uint amount1);
                    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                    event Swap(
                        address indexed sender,
                        uint amount0In,
                        uint amount1In,
                        uint amount0Out,
                        uint amount1Out,
                        address indexed to
                    );
                    event Sync(uint112 reserve0, uint112 reserve1);
                
                    function MINIMUM_LIQUIDITY() external pure returns (uint);
                    function factory() external view returns (address);
                    function token0() external view returns (address);
                    function token1() external view returns (address);
                    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                    function price0CumulativeLast() external view returns (uint);
                    function price1CumulativeLast() external view returns (uint);
                    function kLast() external view returns (uint);
                
                    function mint(address to) external returns (uint liquidity);
                    function burn(address to) external returns (uint amount0, uint amount1);
                    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                    function skim(address to) external;
                    function sync() external;
                
                    function initialize(address, address) external;
                }
                
                // File: contracts/interfaces/IUniswapV2ERC20.sol
                
                pragma solidity >=0.5.0;
                
                interface IUniswapV2ERC20 {
                    event Approval(address indexed owner, address indexed spender, uint value);
                    event Transfer(address indexed from, address indexed to, uint value);
                
                    function name() external pure returns (string memory);
                    function symbol() external pure returns (string memory);
                    function decimals() external pure returns (uint8);
                    function totalSupply() external view returns (uint);
                    function balanceOf(address owner) external view returns (uint);
                    function allowance(address owner, address spender) external view returns (uint);
                
                    function approve(address spender, uint value) external returns (bool);
                    function transfer(address to, uint value) external returns (bool);
                    function transferFrom(address from, address to, uint value) external returns (bool);
                
                    function DOMAIN_SEPARATOR() external view returns (bytes32);
                    function PERMIT_TYPEHASH() external pure returns (bytes32);
                    function nonces(address owner) external view returns (uint);
                
                    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                }
                
                // File: contracts/libraries/SafeMath.sol
                
                pragma solidity =0.5.16;
                
                // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
                
                library SafeMath {
                    function add(uint x, uint y) internal pure returns (uint z) {
                        require((z = x + y) >= x, 'ds-math-add-overflow');
                    }
                
                    function sub(uint x, uint y) internal pure returns (uint z) {
                        require((z = x - y) <= x, 'ds-math-sub-underflow');
                    }
                
                    function mul(uint x, uint y) internal pure returns (uint z) {
                        require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                    }
                }
                
                // File: contracts/UniswapV2ERC20.sol
                
                pragma solidity =0.5.16;
                
                
                
                contract UniswapV2ERC20 is IUniswapV2ERC20 {
                    using SafeMath for uint;
                
                    string public constant name = 'Uniswap V2';
                    string public constant symbol = 'UNI-V2';
                    uint8 public constant decimals = 18;
                    uint  public totalSupply;
                    mapping(address => uint) public balanceOf;
                    mapping(address => mapping(address => uint)) public allowance;
                
                    bytes32 public DOMAIN_SEPARATOR;
                    // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                    bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                    mapping(address => uint) public nonces;
                
                    event Approval(address indexed owner, address indexed spender, uint value);
                    event Transfer(address indexed from, address indexed to, uint value);
                
                    constructor() public {
                        uint chainId;
                        assembly {
                            chainId := chainid
                        }
                        DOMAIN_SEPARATOR = keccak256(
                            abi.encode(
                                keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                                keccak256(bytes(name)),
                                keccak256(bytes('1')),
                                chainId,
                                address(this)
                            )
                        );
                    }
                
                    function _mint(address to, uint value) internal {
                        totalSupply = totalSupply.add(value);
                        balanceOf[to] = balanceOf[to].add(value);
                        emit Transfer(address(0), to, value);
                    }
                
                    function _burn(address from, uint value) internal {
                        balanceOf[from] = balanceOf[from].sub(value);
                        totalSupply = totalSupply.sub(value);
                        emit Transfer(from, address(0), value);
                    }
                
                    function _approve(address owner, address spender, uint value) private {
                        allowance[owner][spender] = value;
                        emit Approval(owner, spender, value);
                    }
                
                    function _transfer(address from, address to, uint value) private {
                        balanceOf[from] = balanceOf[from].sub(value);
                        balanceOf[to] = balanceOf[to].add(value);
                        emit Transfer(from, to, value);
                    }
                
                    function approve(address spender, uint value) external returns (bool) {
                        _approve(msg.sender, spender, value);
                        return true;
                    }
                
                    function transfer(address to, uint value) external returns (bool) {
                        _transfer(msg.sender, to, value);
                        return true;
                    }
                
                    function transferFrom(address from, address to, uint value) external returns (bool) {
                        if (allowance[from][msg.sender] != uint(-1)) {
                            allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                        }
                        _transfer(from, to, value);
                        return true;
                    }
                
                    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                        require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                        bytes32 digest = keccak256(
                            abi.encodePacked(
                                '\x19\x01',
                                DOMAIN_SEPARATOR,
                                keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                            )
                        );
                        address recoveredAddress = ecrecover(digest, v, r, s);
                        require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                        _approve(owner, spender, value);
                    }
                }
                
                // File: contracts/libraries/Math.sol
                
                pragma solidity =0.5.16;
                
                // a library for performing various math operations
                
                library Math {
                    function min(uint x, uint y) internal pure returns (uint z) {
                        z = x < y ? x : y;
                    }
                
                    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                    function sqrt(uint y) internal pure returns (uint z) {
                        if (y > 3) {
                            z = y;
                            uint x = y / 2 + 1;
                            while (x < z) {
                                z = x;
                                x = (y / x + x) / 2;
                            }
                        } else if (y != 0) {
                            z = 1;
                        }
                    }
                }
                
                // File: contracts/libraries/UQ112x112.sol
                
                pragma solidity =0.5.16;
                
                // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                
                // range: [0, 2**112 - 1]
                // resolution: 1 / 2**112
                
                library UQ112x112 {
                    uint224 constant Q112 = 2**112;
                
                    // encode a uint112 as a UQ112x112
                    function encode(uint112 y) internal pure returns (uint224 z) {
                        z = uint224(y) * Q112; // never overflows
                    }
                
                    // divide a UQ112x112 by a uint112, returning a UQ112x112
                    function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                        z = x / uint224(y);
                    }
                }
                
                // File: contracts/interfaces/IERC20.sol
                
                pragma solidity >=0.5.0;
                
                interface IERC20 {
                    event Approval(address indexed owner, address indexed spender, uint value);
                    event Transfer(address indexed from, address indexed to, uint value);
                
                    function name() external view returns (string memory);
                    function symbol() external view returns (string memory);
                    function decimals() external view returns (uint8);
                    function totalSupply() external view returns (uint);
                    function balanceOf(address owner) external view returns (uint);
                    function allowance(address owner, address spender) external view returns (uint);
                
                    function approve(address spender, uint value) external returns (bool);
                    function transfer(address to, uint value) external returns (bool);
                    function transferFrom(address from, address to, uint value) external returns (bool);
                }
                
                // File: contracts/interfaces/IUniswapV2Factory.sol
                
                pragma solidity >=0.5.0;
                
                interface IUniswapV2Factory {
                    event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                
                    function feeTo() external view returns (address);
                    function feeToSetter() external view returns (address);
                
                    function getPair(address tokenA, address tokenB) external view returns (address pair);
                    function allPairs(uint) external view returns (address pair);
                    function allPairsLength() external view returns (uint);
                
                    function createPair(address tokenA, address tokenB) external returns (address pair);
                
                    function setFeeTo(address) external;
                    function setFeeToSetter(address) external;
                }
                
                // File: contracts/interfaces/IUniswapV2Callee.sol
                
                pragma solidity >=0.5.0;
                
                interface IUniswapV2Callee {
                    function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                }
                
                // File: contracts/UniswapV2Pair.sol
                
                pragma solidity =0.5.16;
                
                
                
                
                
                
                
                
                contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
                    using SafeMath  for uint;
                    using UQ112x112 for uint224;
                
                    uint public constant MINIMUM_LIQUIDITY = 10**3;
                    bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
                
                    address public factory;
                    address public token0;
                    address public token1;
                
                    uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                    uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                    uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
                
                    uint public price0CumulativeLast;
                    uint public price1CumulativeLast;
                    uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                
                    uint private unlocked = 1;
                    modifier lock() {
                        require(unlocked == 1, 'UniswapV2: LOCKED');
                        unlocked = 0;
                        _;
                        unlocked = 1;
                    }
                
                    function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                        _reserve0 = reserve0;
                        _reserve1 = reserve1;
                        _blockTimestampLast = blockTimestampLast;
                    }
                
                    function _safeTransfer(address token, address to, uint value) private {
                        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                        require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                    }
                
                    event Mint(address indexed sender, uint amount0, uint amount1);
                    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                    event Swap(
                        address indexed sender,
                        uint amount0In,
                        uint amount1In,
                        uint amount0Out,
                        uint amount1Out,
                        address indexed to
                    );
                    event Sync(uint112 reserve0, uint112 reserve1);
                
                    constructor() public {
                        factory = msg.sender;
                    }
                
                    // called once by the factory at time of deployment
                    function initialize(address _token0, address _token1) external {
                        require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                        token0 = _token0;
                        token1 = _token1;
                    }
                
                    // update reserves and, on the first call per block, price accumulators
                    function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                        require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                        uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                        if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                            // * never overflows, and + overflow is desired
                            price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                            price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                        }
                        reserve0 = uint112(balance0);
                        reserve1 = uint112(balance1);
                        blockTimestampLast = blockTimestamp;
                        emit Sync(reserve0, reserve1);
                    }
                
                    // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                    function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                        address feeTo = IUniswapV2Factory(factory).feeTo();
                        feeOn = feeTo != address(0);
                        uint _kLast = kLast; // gas savings
                        if (feeOn) {
                            if (_kLast != 0) {
                                uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                                uint rootKLast = Math.sqrt(_kLast);
                                if (rootK > rootKLast) {
                                    uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                    uint denominator = rootK.mul(5).add(rootKLast);
                                    uint liquidity = numerator / denominator;
                                    if (liquidity > 0) _mint(feeTo, liquidity);
                                }
                            }
                        } else if (_kLast != 0) {
                            kLast = 0;
                        }
                    }
                
                    // this low-level function should be called from a contract which performs important safety checks
                    function mint(address to) external lock returns (uint liquidity) {
                        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                        uint balance0 = IERC20(token0).balanceOf(address(this));
                        uint balance1 = IERC20(token1).balanceOf(address(this));
                        uint amount0 = balance0.sub(_reserve0);
                        uint amount1 = balance1.sub(_reserve1);
                
                        bool feeOn = _mintFee(_reserve0, _reserve1);
                        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                        if (_totalSupply == 0) {
                            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                           _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                        } else {
                            liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                        }
                        require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                        _mint(to, liquidity);
                
                        _update(balance0, balance1, _reserve0, _reserve1);
                        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                        emit Mint(msg.sender, amount0, amount1);
                    }
                
                    // this low-level function should be called from a contract which performs important safety checks
                    function burn(address to) external lock returns (uint amount0, uint amount1) {
                        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                        address _token0 = token0;                                // gas savings
                        address _token1 = token1;                                // gas savings
                        uint balance0 = IERC20(_token0).balanceOf(address(this));
                        uint balance1 = IERC20(_token1).balanceOf(address(this));
                        uint liquidity = balanceOf[address(this)];
                
                        bool feeOn = _mintFee(_reserve0, _reserve1);
                        uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                        amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                        amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                        require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                        _burn(address(this), liquidity);
                        _safeTransfer(_token0, to, amount0);
                        _safeTransfer(_token1, to, amount1);
                        balance0 = IERC20(_token0).balanceOf(address(this));
                        balance1 = IERC20(_token1).balanceOf(address(this));
                
                        _update(balance0, balance1, _reserve0, _reserve1);
                        if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                        emit Burn(msg.sender, amount0, amount1, to);
                    }
                
                    // this low-level function should be called from a contract which performs important safety checks
                    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                        require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                        require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
                
                        uint balance0;
                        uint balance1;
                        { // scope for _token{0,1}, avoids stack too deep errors
                        address _token0 = token0;
                        address _token1 = token1;
                        require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                        if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                        if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                        if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                        balance0 = IERC20(_token0).balanceOf(address(this));
                        balance1 = IERC20(_token1).balanceOf(address(this));
                        }
                        uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                        uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                        require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                        uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                        uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                        require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                        }
                
                        _update(balance0, balance1, _reserve0, _reserve1);
                        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                    }
                
                    // force balances to match reserves
                    function skim(address to) external lock {
                        address _token0 = token0; // gas savings
                        address _token1 = token1; // gas savings
                        _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
                        _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
                    }
                
                    // force reserves to match balances
                    function sync() external lock {
                        _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                    }
                }

                File 9 of 12: AdminUpgradeabilityProxy
                // File: zos-lib/contracts/upgradeability/Proxy.sol
                
                pragma solidity ^0.5.0;
                
                /**
                 * @title Proxy
                 * @dev Implements delegation of calls to other contracts, with proper
                 * forwarding of return values and bubbling of failures.
                 * It defines a fallback function that delegates all calls to the address
                 * returned by the abstract _implementation() internal function.
                 */
                contract Proxy {
                  /**
                   * @dev Fallback function.
                   * Implemented entirely in `_fallback`.
                   */
                  function () payable external {
                    _fallback();
                  }
                
                  /**
                   * @return The Address of the implementation.
                   */
                  function _implementation() internal view returns (address);
                
                  /**
                   * @dev Delegates execution to an implementation contract.
                   * This is a low level function that doesn't return to its internal call site.
                   * It will return to the external caller whatever the implementation returns.
                   * @param implementation Address to delegate.
                   */
                  function _delegate(address implementation) internal {
                    assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize)
                
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize)
                
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 { revert(0, returndatasize) }
                      default { return(0, returndatasize) }
                    }
                  }
                
                  /**
                   * @dev Function that is run as the first thing in the fallback function.
                   * Can be redefined in derived contracts to add functionality.
                   * Redefinitions must call super._willFallback().
                   */
                  function _willFallback() internal {
                  }
                
                  /**
                   * @dev fallback implementation.
                   * Extracted to enable manual triggering.
                   */
                  function _fallback() internal {
                    _willFallback();
                    _delegate(_implementation());
                  }
                }
                
                // File: zos-lib/contracts/utils/Address.sol
                
                pragma solidity ^0.5.0;
                
                /**
                 * Utility library of inline functions on addresses
                 *
                 * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
                 * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
                 * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
                 * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
                 */
                library ZOSLibAddress {
                    /**
                     * Returns whether the target address is a contract
                     * @dev This function will return false if invoked during the constructor of a contract,
                     * as the code is not actually created until after the constructor finishes.
                     * @param account address of the account to check
                     * @return whether the target address is a contract
                     */
                    function isContract(address account) internal view returns (bool) {
                        uint256 size;
                        // XXX Currently there is no better way to check if there is a contract in an address
                        // than to check the size of the code at that address.
                        // See https://ethereum.stackexchange.com/a/14016/36603
                        // for more details about how this works.
                        // TODO Check this again before the Serenity release, because all addresses will be
                        // contracts then.
                        // solhint-disable-next-line no-inline-assembly
                        assembly { size := extcodesize(account) }
                        return size > 0;
                    }
                }
                
                // File: zos-lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol
                
                pragma solidity ^0.5.0;
                
                
                
                /**
                 * @title BaseUpgradeabilityProxy
                 * @dev This contract implements a proxy that allows to change the
                 * implementation address to which it will delegate.
                 * Such a change is called an implementation upgrade.
                 */
                contract BaseUpgradeabilityProxy is Proxy {
                  /**
                   * @dev Emitted when the implementation is upgraded.
                   * @param implementation Address of the new implementation.
                   */
                  event Upgraded(address indexed implementation);
                
                  /**
                   * @dev Storage slot with the address of the current implementation.
                   * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                   * validated in the constructor.
                   */
                  bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                
                  /**
                   * @dev Returns the current implementation.
                   * @return Address of the current implementation
                   */
                  function _implementation() internal view returns (address impl) {
                    bytes32 slot = IMPLEMENTATION_SLOT;
                    assembly {
                      impl := sload(slot)
                    }
                  }
                
                  /**
                   * @dev Upgrades the proxy to a new implementation.
                   * @param newImplementation Address of the new implementation.
                   */
                  function _upgradeTo(address newImplementation) internal {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                  }
                
                  /**
                   * @dev Sets the implementation address of the proxy.
                   * @param newImplementation Address of the new implementation.
                   */
                  function _setImplementation(address newImplementation) internal {
                    require(ZOSLibAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                
                    bytes32 slot = IMPLEMENTATION_SLOT;
                
                    assembly {
                      sstore(slot, newImplementation)
                    }
                  }
                }
                
                // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                
                pragma solidity ^0.5.0;
                
                
                /**
                 * @title UpgradeabilityProxy
                 * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
                 * implementation and init data.
                 */
                contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
                  /**
                   * @dev Contract constructor.
                   * @param _logic Address of the initial implementation.
                   * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                   * It should include the signature and the parameters of the function to be called, as described in
                   * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                   * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                   */
                  constructor(address _logic, bytes memory _data) public payable {
                    assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                    _setImplementation(_logic);
                    if(_data.length > 0) {
                      (bool success,) = _logic.delegatecall(_data);
                      require(success);
                    }
                  }  
                }
                
                // File: zos-lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol
                
                pragma solidity ^0.5.0;
                
                
                /**
                 * @title BaseAdminUpgradeabilityProxy
                 * @dev This contract combines an upgradeability proxy with an authorization
                 * mechanism for administrative tasks.
                 * All external functions in this contract must be guarded by the
                 * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                 * feature proposal that would enable this to be done automatically.
                 */
                contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
                  /**
                   * @dev Emitted when the administration has been transferred.
                   * @param previousAdmin Address of the previous admin.
                   * @param newAdmin Address of the new admin.
                   */
                  event AdminChanged(address previousAdmin, address newAdmin);
                
                  /**
                   * @dev Storage slot with the admin of the contract.
                   * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                   * validated in the constructor.
                   */
                  bytes32 internal constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                
                  /**
                   * @dev Modifier to check whether the `msg.sender` is the admin.
                   * If it is, it will run the function. Otherwise, it will delegate the call
                   * to the implementation.
                   */
                  modifier ifAdmin() {
                    if (msg.sender == _admin()) {
                      _;
                    } else {
                      _fallback();
                    }
                  }
                
                  /**
                   * @return The address of the proxy admin.
                   */
                  function admin() external ifAdmin returns (address) {
                    return _admin();
                  }
                
                  /**
                   * @return The address of the implementation.
                   */
                  function implementation() external ifAdmin returns (address) {
                    return _implementation();
                  }
                
                  /**
                   * @dev Changes the admin of the proxy.
                   * Only the current admin can call this function.
                   * @param newAdmin Address to transfer proxy administration to.
                   */
                  function changeAdmin(address newAdmin) external ifAdmin {
                    require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                    emit AdminChanged(_admin(), newAdmin);
                    _setAdmin(newAdmin);
                  }
                
                  /**
                   * @dev Upgrade the backing implementation of the proxy.
                   * Only the admin can call this function.
                   * @param newImplementation Address of the new implementation.
                   */
                  function upgradeTo(address newImplementation) external ifAdmin {
                    _upgradeTo(newImplementation);
                  }
                
                  /**
                   * @dev Upgrade the backing implementation of the proxy and call a function
                   * on the new implementation.
                   * This is useful to initialize the proxied contract.
                   * @param newImplementation Address of the new implementation.
                   * @param data Data to send as msg.data in the low level call.
                   * It should include the signature and the parameters of the function to be called, as described in
                   * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                   */
                  function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
                    _upgradeTo(newImplementation);
                    (bool success,) = newImplementation.delegatecall(data);
                    require(success);
                  }
                
                  /**
                   * @return The admin slot.
                   */
                  function _admin() internal view returns (address adm) {
                    bytes32 slot = ADMIN_SLOT;
                    assembly {
                      adm := sload(slot)
                    }
                  }
                
                  /**
                   * @dev Sets the address of the proxy admin.
                   * @param newAdmin Address of the new proxy admin.
                   */
                  function _setAdmin(address newAdmin) internal {
                    bytes32 slot = ADMIN_SLOT;
                
                    assembly {
                      sstore(slot, newAdmin)
                    }
                  }
                
                  /**
                   * @dev Only fall back when the sender is not the admin.
                   */
                  function _willFallback() internal {
                    require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                    super._willFallback();
                  }
                }
                
                // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                
                pragma solidity ^0.5.0;
                
                
                /**
                 * @title AdminUpgradeabilityProxy
                 * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for 
                 * initializing the implementation, admin, and init data.
                 */
                contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
                  /**
                   * Contract constructor.
                   * @param _logic address of the initial implementation.
                   * @param _admin Address of the proxy administrator.
                   * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
                   * It should include the signature and the parameters of the function to be called, as described in
                   * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
                   * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
                   */
                  constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
                    assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                    _setAdmin(_admin);
                  }
                }

                File 10 of 12: AmbirePaymaster
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                import './libs/SignatureValidator.sol';
                import './ExternalSigValidator.sol';
                import './libs/erc4337/PackedUserOperation.sol';
                import './libs/erc4337/UserOpHelper.sol';
                import './deployless/IAmbireAccount.sol';
                /**
                 * @notice  A validator that performs DKIM signature recovery
                 * @dev     All external/public functions (that are not view/pure) use `payable` because AmbireAccount
                 * is a wallet contract, and any ETH sent to it is not lost, but on the other hand not having `payable`
                 * makes the Solidity compiler add an extra check for `msg.value`, which in this case is wasted gas
                 */
                contract AmbireAccount is IAmbireAccount {
                \t// @dev We do not have a constructor. This contract cannot be initialized with any valid `privileges` by itself!
                \t// The intended use case is to deploy one base implementation contract, and create a minimal proxy for each user wallet, by
                \t// using our own code generation to insert SSTOREs to initialize `privileges` (it was previously called IdentityProxyDeploy.js, now src/libs/proxyDeploy/deploy.ts)
                \taddress private constant FALLBACK_HANDLER_SLOT = address(0x6969);
                \t// @dev This is how we understand if msg.sender is the entry point
                \tbytes32 private constant ENTRY_POINT_MARKER = 0x0000000000000000000000000000000000000000000000000000000000007171;
                \t// Externally validated signatures
                \tuint8 private constant SIGMODE_EXTERNALLY_VALIDATED = 255;
                \t// Variables
                \tmapping(address => bytes32) public privileges;
                \tuint256 public nonce;
                \t// Events
                \tevent LogPrivilegeChanged(address indexed addr, bytes32 priv);
                \tevent LogErr(address indexed to, uint256 value, bytes data, bytes returnData); // only used in tryCatch
                \t// This contract can accept ETH without calldata
                \treceive() external payable {}
                \t/**
                \t * @dev     To support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
                \t * @return  bytes4  onERC721Received function selector
                \t */
                \tfunction onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
                \t\treturn this.onERC721Received.selector;
                \t}
                \t/**
                \t * @dev     To support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
                \t * @return  bytes4  onERC1155Received function selector
                \t */
                \tfunction onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
                \t\treturn this.onERC1155Received.selector;
                \t}
                \t/**
                \t * @dev     To support EIP 721 and EIP 1155, we need to respond to those methods with their own method signature
                \t * @return  bytes4  onERC1155Received function selector
                \t */
                \tfunction onERC1155BatchReceived(
                \t\taddress,
                \t\taddress,
                \t\tuint256[] calldata,
                \t\tuint256[] calldata,
                \t\tbytes calldata
                \t) external pure returns (bytes4) {
                \t\treturn this.onERC1155BatchReceived.selector;
                \t}
                \t/**
                \t * @notice  fallback method: currently used to call the fallback handler
                \t * which is set by the user and can be changed
                \t * @dev     this contract can accept ETH with calldata, hence payable
                \t */
                \tfallback() external payable {
                \t\t// We store the fallback handler at this magic slot
                \t\taddress fallbackHandler = address(uint160(uint(privileges[FALLBACK_HANDLER_SLOT])));
                \t\tif (fallbackHandler == address(0)) return;
                \t\tassembly {
                \t\t\t// we can use addr 0 because logic is taking full control of the
                \t\t\t// execution making sure it returns itself and does not
                \t\t\t// rely on any further Solidity code.
                \t\t\tcalldatacopy(0, 0, calldatasize())
                \t\t\tlet result := delegatecall(gas(), fallbackHandler, 0, calldatasize(), 0, 0)
                \t\t\tlet size := returndatasize()
                \t\t\treturndatacopy(0, 0, size)
                \t\t\tif eq(result, 0) {
                \t\t\t\trevert(0, size)
                \t\t\t}
                \t\t\treturn(0, size)
                \t\t}
                \t}
                \t/**
                \t * @notice  used to set the privilege of a key (by `addr`)
                \t * @dev     normal signatures will be considered valid if the
                \t * `addr` they are signed with has non-zero (not 0x000..000) privilege set; we can set the privilege to
                \t * a hash of the recovery keys and timelock (see `RecoveryInfo`) to enable recovery signatures
                \t * @param   addr  the address to give privs to
                \t * @param   priv  the privs to give
                \t */
                \tfunction setAddrPrivilege(address addr, bytes32 priv) external payable {
                \t\trequire(msg.sender == address(this), 'ONLY_ACCOUNT_CAN_CALL');
                \t\tprivileges[addr] = priv;
                \t\temit LogPrivilegeChanged(addr, priv);
                \t}
                \t/**
                \t * @notice  Useful when we need to do multiple operations but ignore failures in some of them
                \t * @param   to  address we're sending value to
                \t * @param   value  the amount
                \t * @param   data  callData
                \t */
                \tfunction tryCatch(address to, uint256 value, bytes calldata data) external payable {
                \t\trequire(msg.sender == address(this), 'ONLY_ACCOUNT_CAN_CALL');
                \t\tuint256 gasBefore = gasleft();
                \t\t(bool success, bytes memory returnData) = to.call{ value: value, gas: gasBefore }(data);
                \t\trequire(gasleft() > gasBefore / 64, 'TRYCATCH_OOG');
                \t\tif (!success) emit LogErr(to, value, data, returnData);
                \t}
                \t/**
                \t * @notice  same as `tryCatch` but with a gas limit
                \t * @param   to  address we're sending value to
                \t * @param   value  the amount
                \t * @param   data  callData
                \t * @param   gasLimit  how much gas is allowed
                \t */
                \tfunction tryCatchLimit(address to, uint256 value, bytes calldata data, uint256 gasLimit) external payable {
                \t\trequire(msg.sender == address(this), 'ONLY_ACCOUNT_CAN_CALL');
                \t\tuint256 gasBefore = gasleft();
                \t\t(bool success, bytes memory returnData) = to.call{ value: value, gas: gasLimit }(data);
                \t\trequire(gasleft() > gasBefore / 64, 'TRYCATCH_OOG');
                \t\tif (!success) emit LogErr(to, value, data, returnData);
                \t}
                \t/**
                \t * @notice  execute: this method is used to execute a single bundle of calls that are signed with a key
                \t * that is authorized to execute on this account (in `privileges`)
                \t * @dev     WARNING: if the signature of this is changed, we have to change AmbireAccountFactory
                \t * @param   calls  the transaction we're executing. They may not execute
                \t * if specific cases. One such is when setting a timelock
                \t * @param   signature  the signature for the transactions
                \t */
                \tfunction execute(Transaction[] calldata calls, bytes calldata signature) public payable {
                \t\taddress signerKey;
                \t\tuint8 sigMode = uint8(signature[signature.length - 1]);
                \t\tuint256 currentNonce = nonce;
                \t\t// we increment the nonce here (not using `nonce++` to save some gas)
                \t\tnonce = currentNonce + 1;
                \t\tif (sigMode == SIGMODE_EXTERNALLY_VALIDATED) {
                \t\t\tbool isValidSig;
                \t\t\tuint256 timestampValidAfter;
                \t\t\t(signerKey, isValidSig, timestampValidAfter) = validateExternalSig(calls, signature);
                \t\t\tif (!isValidSig) {
                \t\t\t\trequire(block.timestamp >= timestampValidAfter, 'SIGNATURE_VALIDATION_TIMELOCK');
                \t\t\t\trevert('SIGNATURE_VALIDATION_FAIL');
                \t\t\t}
                \t\t} else {
                \t\t\tsignerKey = SignatureValidator.recoverAddr(
                \t\t\t\tkeccak256(abi.encode(address(this), block.chainid, currentNonce, calls)),
                \t\t\t\tsignature,
                \t\t\t\ttrue
                \t\t\t);
                \t\t\trequire(privileges[signerKey] != bytes32(0), 'INSUFFICIENT_PRIVILEGE');
                \t\t}
                \t\texecuteBatch(calls);
                \t\t// The actual anti-bricking mechanism - do not allow a signerKey to drop their own privileges
                \t\trequire(privileges[signerKey] != bytes32(0), 'PRIVILEGE_NOT_DOWNGRADED');
                \t}
                \t/**
                \t * @notice  allows executing multiple bundles of calls (batch together multiple executes)
                \t * @param   toExec  an array of execute function parameters
                \t */
                \tfunction executeMultiple(ExecuteArgs[] calldata toExec) external payable {
                \t\tfor (uint256 i = 0; i != toExec.length; i++) execute(toExec[i].calls, toExec[i].signature);
                \t}
                \t/**
                \t * @notice  Allows executing calls if the caller itself is authorized
                \t * @dev     no need for nonce management here cause we're not dealing with sigs
                \t * @param   calls  the transaction we're executing
                \t */
                \tfunction executeBySender(Transaction[] calldata calls) external payable {
                \t\trequire(privileges[msg.sender] != bytes32(0), 'INSUFFICIENT_PRIVILEGE');
                \t\texecuteBatch(calls);
                \t\t// again, anti-bricking
                \t\trequire(privileges[msg.sender] != bytes32(0), 'PRIVILEGE_NOT_DOWNGRADED');
                \t}
                \t/**
                \t * @notice  allows the contract itself to execute a batch of calls
                \t * self-calling is useful in cases like wanting to do multiple things in a tryCatchLimit
                \t * @param   calls  the calls we're executing
                \t */
                \tfunction executeBySelf(Transaction[] calldata calls) external payable {
                \t\trequire(msg.sender == address(this), 'ONLY_ACCOUNT_CAN_CALL');
                \t\texecuteBatch(calls);
                \t}
                \t/**
                \t * @notice  allows the contract itself to execute a single calls
                \t * self-calling is useful when you want to workaround the executeBatch()
                \t * protection of not being able to call address(0)
                \t * @param   call  the call we're executing
                \t */
                \tfunction executeBySelfSingle(Transaction calldata call) external payable {
                \t\trequire(msg.sender == address(this), 'ONLY_ACCOUNT_CAN_CALL');
                \t\texecuteCall(call.to, call.value, call.data);
                \t}
                \t/**
                \t * @notice  Execute a batch of transactions
                \t * @param   calls  the transaction we're executing
                \t */
                \tfunction executeBatch(Transaction[] memory calls) internal {
                \t\tuint256 len = calls.length;
                \t\tfor (uint256 i = 0; i < len; i++) {
                \t\t\tTransaction memory call = calls[i];
                \t\t\tif (call.to != address(0)) executeCall(call.to, call.value, call.data);
                \t\t}
                \t}
                \t/**
                \t * @notice  Execute a signle transaction
                \t * @dev     we shouldn't use address.call(), cause: https://github.com/ethereum/solidity/issues/2884
                \t * @param   to  the address we're sending to
                \t * @param   value  the amount we're sending
                \t * @param   data  callData
                \t */
                \tfunction executeCall(address to, uint256 value, bytes memory data) internal {
                \t\tassembly {
                \t\t\tlet result := call(gas(), to, value, add(data, 0x20), mload(data), 0, 0)
                \t\t\tif eq(result, 0) {
                \t\t\t\tlet size := returndatasize()
                \t\t\t\tlet ptr := mload(0x40)
                \t\t\t\treturndatacopy(ptr, 0, size)
                \t\t\t\trevert(ptr, size)
                \t\t\t}
                \t\t}
                \t}
                \t/**
                \t * @notice  EIP-1271 implementation
                \t * @dev     see https://eips.ethereum.org/EIPS/eip-1271
                \t * @param   hash  the signed hash
                \t * @param   signature  the signature for the signed hash
                \t * @return  bytes4  is it a success or a failure
                \t */
                \tfunction isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4) {
                \t\t(address recovered, bool usedUnprotected) = SignatureValidator.recoverAddrAllowUnprotected(hash, signature, false);
                \t\tif (uint256(privileges[recovered]) > (usedUnprotected ? 1 : 0)) {
                \t\t\t// bytes4(keccak256("isValidSignature(bytes32,bytes)")
                \t\t\treturn 0x1626ba7e;
                \t\t} else {
                \t\t\treturn 0xffffffff;
                \t\t}
                \t}
                \t/**
                \t * @notice  EIP-1155 implementation
                \t * we pretty much only need to signal that we support the interface for 165, but for 1155 we also need the fallback function
                \t * @param   interfaceID  the interface we're signaling support for
                \t * @return  bool  do we support the interface or not
                \t */
                \tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {
                \t\tbool supported = interfaceID == 0x01ffc9a7 || // ERC-165 support (i.e. `bytes4(keccak256('supportsInterface(bytes4)'))`).
                \t\t\tinterfaceID == 0x150b7a02 || // ERC721TokenReceiver
                \t\t\tinterfaceID == 0x4e2312e0 || // ERC-1155 `ERC1155TokenReceiver` support (i.e. `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`).
                \t\t\tinterfaceID == 0x0a417632; // used for checking whether the account is v2 or not
                \t\tif (supported) return true;
                \t\taddress payable fallbackHandler = payable(address(uint160(uint256(privileges[FALLBACK_HANDLER_SLOT]))));
                \t\tif (fallbackHandler == address(0)) return false;
                \t\treturn AmbireAccount(fallbackHandler).supportsInterface(interfaceID);
                \t}
                \t//
                \t// EIP-4337 implementation
                \t//
                \t// return value in case of signature failure, with no time-range.
                \t// equivalent to packSigTimeRange(true,0,0);
                \tuint256 constant internal SIG_VALIDATION_FAILED = 1;
                \t// equivalent to packSigTimeRange(false,0,0);
                \tuint256 constant internal SIG_VALIDATION_SUCCESS = 0;
                \t/**
                \t * @notice  EIP-4337 implementation
                \t * @dev     We have an edge case for enabling ERC-4337 in the first if statement.
                \t * If the function call is to execute, we do not perform an userOp sig validation.
                \t * We require a one time hash nonce commitment from the paymaster for the given
                \t * req. We use this to give permissions to the entry point on the fly
                \t * and enable ERC-4337
                \t * @param   op  the PackedUserOperation we're executing
                \t * @param   userOpHash  the hash we've committed to
                \t * @param   missingAccountFunds  the funds the account needs to pay
                \t * @return  uint256  0 for success, 1 for signature failure, and a uint256
                \t * packed timestamp for a future valid signature:
                \t * address aggregator, uint48 validUntil, uint48 validAfter
                \t */
                \tfunction validateUserOp(PackedUserOperation calldata op, bytes32 userOpHash, uint256 missingAccountFunds)
                \texternal payable returns (uint256)
                \t{
                \t\t// enable running executeMultiple operation through the entryPoint if
                \t\t// a paymaster sponsors it with a commitment one-time nonce.
                \t\t// two use cases:
                \t\t// 1) enable 4337 on a network by giving privileges to the entryPoint
                \t\t// 2) key recovery. If the key is lost, we cannot sign the userOp,
                \t\t// so we have to go to `execute` to trigger the recovery logic
                \t\t// Why executeMultiple but not execute?
                \t\t// executeMultiple allows us to combine recovery + fee payment calls.
                \t\t// The fee payment call will be with a signature from the new key
                \t\tif (op.callData.length >= 4 && bytes4(op.callData[0:4]) == this.executeMultiple.selector) {
                \t\t\t// Require a paymaster, otherwise this mode can be used by anyone to get the user to spend their deposit
                \t\t\t// @estimation-no-revert
                \t\t\tif (op.signature.length != 0) return SIG_VALIDATION_FAILED;
                \t\t\trequire(
                \t\t\t\top.paymasterAndData.length >= UserOpHelper.PAYMASTER_DATA_OFFSET &&
                \t\t\t\tbytes20(op.paymasterAndData[:UserOpHelper.PAYMASTER_ADDR_OFFSET]) != bytes20(0),
                \t\t\t\t'validateUserOp: paymaster required in execute() mode'
                \t\t\t);
                \t\t\t// hashing in everything except sender (nonces are scoped by sender anyway), nonce, signature
                \t\t\tuint256 targetNonce = uint256(keccak256(
                \t\t\t\tabi.encode(op.initCode, op.callData, op.accountGasLimits, op.preVerificationGas, op.gasFees, op.paymasterAndData)
                \t\t\t)) << 64;
                \t\t\t// @estimation-no-revert
                \t\t\tif (op.nonce != targetNonce) return SIG_VALIDATION_FAILED;
                \t\t\treturn SIG_VALIDATION_SUCCESS;
                \t\t}
                \t\trequire(privileges[msg.sender] == ENTRY_POINT_MARKER, 'validateUserOp: not from entryPoint');
                \t\t// @estimation
                \t\t// paying should happen even if signature validation fails
                \t\tif (missingAccountFunds > 0) {
                \t\t\t// NOTE: MAY pay more than the minimum, to deposit for future transactions
                \t\t\t(bool success,) = msg.sender.call{value : missingAccountFunds}('');
                \t\t\t// ignore failure (its EntryPoint's job to verify, not account.)
                \t\t\t(success);
                \t\t}
                \t\t// this is replay-safe because userOpHash is retrieved like this: keccak256(abi.encode(userOp.hash(), address(this), block.chainid))
                \t\taddress signer = SignatureValidator.recoverAddr(userOpHash, op.signature, true);
                \t\tif (privileges[signer] == bytes32(0)) return SIG_VALIDATION_FAILED;
                \t\treturn SIG_VALIDATION_SUCCESS;
                \t}
                \tfunction validateExternalSig(Transaction[] memory calls, bytes calldata signature)
                \tinternal returns(address signerKey, bool isValidSig, uint256 timestampValidAfter) {
                \t\t(bytes memory sig, ) = SignatureValidator.splitSignature(signature);
                \t\t// the address of the validator we're using for this validation
                \t\taddress validatorAddr;
                \t\t// all the data needed by the validator to execute the validation.
                \t\t// In the case of DKIMRecoverySigValidator, this is AccInfo:
                \t\t// abi.encode {string emailFrom; string emailTo; string domainName;
                \t\t// bytes dkimPubKeyModulus; bytes dkimPubKeyExponent; address secondaryKey;
                \t\t// bool acceptUnknownSelectors; uint32 waitUntilAcceptAdded;
                \t\t// uint32 waitUntilAcceptRemoved; bool acceptEmptyDKIMSig;
                \t\t// bool acceptEmptySecondSig;uint32 onlyOneSigTimelock;}
                \t\t// The struct is declared in DKIMRecoverySigValidator
                \t\tbytes memory validatorData;
                \t\t// the signature data needed by the external validator.
                \t\t// In the case of DKIMRecoverySigValidator, this is abi.encode(
                \t\t// SignatureMeta memory sigMeta, bytes memory dkimSig, bytes memory secondSig
                \t\t// ).
                \t\tbytes memory innerSig;
                \t\t// the signerKey in this case is an arbitrary value that does
                \t\t// not have any specific purpose other than representing
                \t\t// the privileges key
                \t\t(signerKey, validatorAddr, validatorData, innerSig) = abi.decode(sig, (address, address, bytes, bytes));
                \t\trequire(
                \t\t\tprivileges[signerKey] == keccak256(abi.encode(validatorAddr, validatorData)),
                \t\t\t'EXTERNAL_VALIDATION_NOT_SET'
                \t\t);
                \t\t// The sig validator itself should throw when a signature isn't validated successfully
                \t\t// the return value just indicates whether we want to execute the current calls
                \t\t(isValidSig, timestampValidAfter) = ExternalSigValidator(validatorAddr).validateSig(validatorData, innerSig, calls);
                \t}
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                import './deployless/IAmbireAccount.sol';
                import './libs/Transaction.sol';
                /**
                 * @notice  A contract used for deploying AmbireAccount.sol
                 * @dev     We use create2 to get the AmbireAccount address. It's deterministic:
                 * if the same data is passed to it, the same address will pop out.
                 */
                contract AmbireFactory {
                \tevent LogDeployed(address addr, uint256 salt);
                \taddress public immutable allowedToDrain;
                \tconstructor(address allowed) {
                \t\tallowedToDrain = allowed;
                \t}
                \t/**
                \t * @notice  Allows anyone to deploy any contracft with a specific code/salt
                \t * @dev     This is safe because it's CREATE2 deployment
                \t * @param   code  the code to be deployed
                \t * @param   salt  the salt to shuffle the computed address
                \t * @return  address  the deployed address
                \t */
                \tfunction deploy(bytes calldata code, uint256 salt) external returns(address) {
                \t\treturn deploySafe(code, salt);
                \t}
                \t
                \t/**
                \t * @notice  Call this when you want to deploy the contract and execute calls
                \t * @dev     When the relayer needs to act upon an /identity/:addr/submit call, it'll either call execute on the AmbireAccount directly
                \t * if it's already deployed, or call `deployAndExecute` if the account is still counterfactual
                \t * we can't have deployAndExecuteBySender, because the sender will be the factory
                \t * @param   code  the code to be deployed
                \t * @param   salt  the salt to shuffle the computed address
                \t * @param   txns  the txns the are going to be executed
                \t * @param   signature  the signature for the txns
                \t * @return  address  the deployed address
                \t */
                \tfunction deployAndExecute(
                \t\tbytes calldata code,
                \t\tuint256 salt,
                \t\tTransaction[] calldata txns,
                \t\tbytes calldata signature
                \t) external returns (address){
                \t\taddress payable addr = payable(deploySafe(code, salt));
                \t\tIAmbireAccount(addr).execute(txns, signature);
                \t\treturn addr;
                \t}
                \t
                \t/**
                \t * @notice  Call this when you want to deploy the contract and call executeMultiple
                \t * @dev     when the relayer needs to act upon an /identity/:addr/submit call, 
                \t * it'll either call execute on the AmbireAccount directly. If it's already
                \t * deployed, or call `deployAndExecuteMultiple` if the account is still
                \t * counterfactual but there are multiple accountOps to send
                \t * @param   code  the code to be deployed
                \t * @param   salt  the salt to shuffle the computed address
                \t * @param   toExec  [txns, signature] execute parameters
                \t * @return  address  the deployed address
                \t */
                \tfunction deployAndExecuteMultiple(
                \t\tbytes calldata code,
                \t\tuint256 salt,
                \t\tIAmbireAccount.ExecuteArgs[] calldata toExec
                \t) external returns (address){
                \t\taddress payable addr = payable(deploySafe(code, salt));
                \t\tIAmbireAccount(addr).executeMultiple(toExec);
                \t\treturn addr;
                \t}
                \t/**
                \t * @notice  This method can be used to withdraw stuck tokens or airdrops
                \t * @dev     Only allowedToDrain can do the call
                \t * @param   to  receiver
                \t * @param   value  how much to be sent
                \t * @param   data  if a token has airdropped, code to send it
                \t * @param   gas  maximum gas willing to spend
                \t */
                \tfunction call(address to, uint256 value, bytes calldata data, uint256 gas) external {
                \t\trequire(msg.sender == allowedToDrain, 'ONLY_AUTHORIZED');
                \t\t(bool success, bytes memory err) = to.call{ gas: gas, value: value }(data);
                \t\trequire(success, string(err));
                \t}
                \t
                \t/**
                \t * @dev     This is done to mitigate possible frontruns where, for example,
                \t * where deploying the same code/salt via deploy() would make a pending
                \t * deployAndExecute fail. The way we mitigate that is by checking if the
                \t * contract is already deployed and if so, we continue execution
                \t * @param   code  the code to be deployed
                \t * @param   salt  the salt to shuffle the computed address
                \t * @return  address  the deployed address
                \t */
                \tfunction deploySafe(bytes memory code, uint256 salt) internal returns (address) {
                \t\taddress expectedAddr = address(
                \t\t\tuint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), salt, keccak256(code)))))
                \t\t);
                \t\tuint256 size;
                \t\tassembly {
                \t\t\tsize := extcodesize(expectedAddr)
                \t\t}
                \t\t// If there is code at that address, we can assume it's the one we were about to deploy,
                \t\t// because of how CREATE2 and keccak256 works
                \t\tif (size == 0) {
                \t\t\taddress addr;
                \t\t\tassembly {
                \t\t\t\taddr := create2(0, add(code, 0x20), mload(code), salt)
                \t\t\t}
                \t\t\trequire(addr != address(0), 'FAILED_DEPLOYING');
                \t\t\trequire(addr == expectedAddr, 'FAILED_MATCH');
                \t\t\temit LogDeployed(addr, salt);
                \t\t}
                \t\treturn expectedAddr;
                \t}
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                import './deployless/IAmbireAccount.sol';
                import './libs/erc4337/IPaymaster.sol';
                import './libs/SignatureValidator.sol';
                import './libs/erc4337/UserOpHelper.sol';
                contract AmbirePaymaster is IPaymaster {
                \taddress immutable public relayer;
                \tconstructor(address _relayer) {
                \t\trelayer = _relayer;
                \t}
                \t/**
                \t * @notice  This method can be used to withdraw stuck tokens or airdrops
                \t *
                \t * @param   to  The address we're calling
                \t * @param   value  The value in the call
                \t * @param\tdata\tthe call data
                \t * @param\tgas\tthe call gas
                \t */
                \tfunction call(address to, uint256 value, bytes calldata data, uint256 gas) external payable {
                \t\trequire(msg.sender == relayer, 'call: not relayer');
                \t\t(bool success, bytes memory err) = to.call{ gas: gas, value: value }(data);
                \t\trequire(success, string(err));
                \t}
                \t/**
                \t * @notice  Validate user operations the paymaster has signed
                \t * We do not need to send funds to the EntryPoint because we rely on pre-existing deposit.
                \t * Requests are chain specific to prevent signature reuse.
                \t * @dev     We have two use cases for the paymaster:
                \t * - normal erc-4337. Everything is per ERC-4337 standard, the nonce is sequential.
                \t * - an executeMultiple call. If the calldata is executeMultiple, we've hardcoded
                \t * a 0 nonce. That's what's called a one-time hash nonce and its key is actually
                \t * the commitment. Check EntryPoint -> NonceManager for more information.
                \t *
                \t * @param   userOp  the UserOperation we're executing
                \t * @return  context  context is returned in the postOp and called by the
                \t * EntryPoint. But we're not using postOp is context is always emtpy
                \t * @return  validationData  This consists of:
                \t * - an aggregator address: address(uint160(validationData)). This is used
                \t * when you want an outer contract to determine whether the signature is valid.
                \t * In our case, this is always 0 (address 0) for valid signatures and
                \t * 1 (address 1) for invalid. This is what the entry point expects and
                \t * in those two cases, an outer contract is obviously not called.
                \t * - a uint48 validUntil: uint48(validationData >> 160)
                \t * A Paymaster signature can be signed at time "x" but delayed intentionally
                \t * until time "y" when a fee payment's price has dropped significantly or
                \t * some other issue. validUntil sets a time validity for the signature
                     * - a uint48 validAfter: uint48(validationData >> (48 + 160))
                \t * If the signature should be valid only after a period of time,
                \t * we tweak the validAfter property.
                \t * For more information, check EntryPoint -> _getValidationData()
                \t */
                \tfunction validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32, uint256)
                \t\texternal
                \t\tview
                \t\treturns (bytes memory context, uint256 validationData)
                \t{
                \t\t(uint48 validUntil, uint48 validAfter, bytes memory signature) = abi.decode(
                \t\t\tuserOp.paymasterAndData[UserOpHelper.PAYMASTER_DATA_OFFSET:],
                \t\t\t(uint48, uint48, bytes)
                \t\t);
                \t\tbytes memory callData = userOp.callData;
                \t\tbytes32 hash = keccak256(abi.encode(
                \t\t\tblock.chainid,
                \t\t\taddress(this),
                \t\t\t// entry point
                \t\t\tmsg.sender,
                \t\t\tvalidUntil,
                \t\t\tvalidAfter,
                \t\t\t// everything except paymasterAndData and signature
                \t\t\tuserOp.sender,
                \t\t\t// for the nonce we have an exception case: one-time nonces depend on paymasterAndData, which is generated by the relayer
                \t\t\t// we can't have this as part of the sig cuz we create a cyclical dep
                \t\t\t// the nonce can only be used once, so one cannot replay the gas payment
                \t\t\tcallData.length >= 4 && bytes4(userOp.callData[0:4]) == IAmbireAccount.executeMultiple.selector ? 0 : userOp.nonce,
                \t\t\tuserOp.initCode,
                \t\t\tcallData,
                \t\t\tuserOp.accountGasLimits,
                \t\t\tuserOp.preVerificationGas,
                \t\t\tuserOp.gasFees
                \t\t));
                \t\t(address recovered, ) = SignatureValidator.recoverAddrAllowUnprotected(hash, signature, true);
                \t\tbool isValidSig = recovered == relayer;
                \t\t// see _packValidationData: https://github.com/eth-infinitism/account-abstraction/blob/f2b09e60a92d5b3177c68d9f382912ccac19e8db/contracts/core/Helpers.sol#L73-L80
                \t\treturn ("", uint160(isValidSig ? 0 : 1) | (uint256(validUntil) << 160) | (uint256(validAfter) << 208));
                \t}
                \t/**
                \t * @notice  No-op, won't be used because we don't return a context
                \t * @param   mode  .
                \t * @param   context  .
                \t * @param   actualGasCost  .
                \t */
                \tfunction postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) external {
                \t\t// No-op, won't be used because we don't return a context
                \t}
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                import './libs/Transaction.sol';
                /**
                 * @title   ExternalSigValidator
                 * @notice  A way to add custom recovery to AmbireAccount.
                 * address accountAddr is the Ambire account address
                 * bytes calldata data is all the data needed by the ExternalSigValidator.
                 * It could be anything and it's validator specific.
                 * bytes calldata sig is the signature we're validating. Notice its not
                 * bytes32 so there could be cases where its not only the signature. It's
                 * validator specific
                 * uint256 nonce - the Ambire account nonce
                 * Transaction[] calldata calls - the txns that are going to be executed
                 * if the validation is successful
                 * @dev     Not all passed properties necessarily need to be used.
                 */
                abstract contract ExternalSigValidator {
                \tfunction validateSig(
                \t\tbytes calldata data,
                \t\tbytes calldata sig,
                \t\tTransaction[] calldata calls
                \t) external virtual returns (bool isValidSignature, uint256 timestampValidAfter);
                }// SPDX-License-Identifier: agpl-3.0
                pragma solidity ^0.8.7;
                import '../libs/Transaction.sol';
                interface IAmbireAccount {
                \tfunction privileges(address addr) external returns (bytes32);
                \tfunction nonce() external returns (uint);
                \tstruct RecoveryInfo {
                \t\taddress[] keys;
                \t\tuint timelock;
                \t}
                \tstruct ExecuteArgs {
                \t\tTransaction[] calls;
                \t\tbytes signature;
                \t}
                \tfunction setAddrPrivilege(address addr, bytes32 priv) external payable;
                \tfunction tryCatch(address to, uint value, bytes calldata data) external payable;
                \tfunction tryCatchLimit(address to, uint value, bytes calldata data, uint gasLimit) external payable;
                \tfunction execute(Transaction[] calldata txns, bytes calldata signature) external payable;
                \tfunction executeBySender(Transaction[] calldata txns) external payable;
                \tfunction executeBySelf(Transaction[] calldata txns) external payable;
                \tfunction executeMultiple(ExecuteArgs[] calldata toExec) external payable;
                \t// EIP 1271 implementation
                \t// see https://eips.ethereum.org/EIPS/eip-1271
                \tfunction isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4);
                \tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                library Bytes {
                \tfunction trimToSize(bytes memory b, uint256 newLen) internal pure {
                \t\trequire(b.length > newLen, 'BytesLib: only shrinking');
                \t\tassembly {
                \t\t\tmstore(b, newLen)
                \t\t}
                \t}
                \t/***********************************|
                \t|        Read Bytes Functions       |
                \t|__________________________________*/
                \t/**
                \t * @dev Reads a bytes32 value from a position in a byte array.
                \t * @param b Byte array containing a bytes32 value.
                \t * @param index Index in byte array of bytes32 value.
                \t * @return result bytes32 value from byte array.
                \t */
                \tfunction readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) {
                \t\t// Arrays are prefixed by a 256 bit length parameter
                \t\tindex += 32;
                \t\trequire(b.length >= index, 'BytesLib: length');
                \t\t// Read the bytes32 from array memory
                \t\tassembly {
                \t\t\tresult := mload(add(b, index))
                \t\t}
                \t\treturn result;
                \t}
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                import './Bytes.sol';
                interface IERC1271Wallet {
                \tfunction isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue);
                }
                library SignatureValidator {
                \tusing Bytes for bytes;
                \tenum SignatureMode {
                \t\t// the first mode Unprotected is used in combination with EIP-1271 signature verification to do
                \t\t// EIP-712 verifications, as well as "Ethereum signed message:" message verifications
                \t\t// The caveat with this is that we need to ensure that the signer key used for it isn't reused, or the message body
                \t\t// itself contains context about the wallet (such as it's address)
                \t\t// We do this, rather than applying the prefix on-chain, because if we do you won't be able to see the message
                \t\t// when signing on a hardware wallet (you'll only see the hash) - since `isValidSignature` can only receive the hash -
                \t\t// if the prefix is applied on-chain you can never match it - it's hash(prefix+hash(msg)) vs hash(prefix+msg)
                \t\t// As for transactions (`execute()`), those can be signed with any of the modes
                \t\t// Otherwise, if it's reused, we MUST use `Standard` mode which always wraps the final digest hash, but unfortnately this means
                \t\t// you can't preview the full message when signing on a HW wallet
                \t\tUnprotected,
                \t\tStandard,
                \t\tSmartWallet,
                \t\tSpoof,
                \t\tSchnorr,
                \t\tMultisig,
                \t\t// WARNING: Signature modes should not be more than 26 as the "v"
                \t\t// value for standard ecrecover is 27/28
                \t\t// WARNING: must always be last
                \t\tLastUnused
                \t}
                \t// bytes4(keccak256("isValidSignature(bytes32,bytes)"))
                \tbytes4 internal constant ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e;
                \t// secp256k1 group order
                \tuint256 internal constant Q = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
                \tfunction splitSignature(bytes memory sig) internal pure returns (bytes memory, uint8) {
                \t\tuint8 modeRaw;
                \t\tunchecked {
                \t\t\tmodeRaw = uint8(sig[sig.length - 1]);
                \t\t}
                \t\tsig.trimToSize(sig.length - 1);
                \t\treturn (sig, modeRaw);
                \t}
                \tfunction recoverAddr(bytes32 hash, bytes memory sig, bool allowSpoofing) internal view returns (address) {
                \t\t(address recovered, bool usedUnprotected) = recoverAddrAllowUnprotected(hash, sig, allowSpoofing);
                \t\trequire(!usedUnprotected, 'SV_USED_UNBOUND');
                \t\treturn recovered;
                \t}
                \tfunction recoverAddrAllowUnprotected(bytes32 hash, bytes memory sig, bool allowSpoofing) internal view returns (address, bool) {
                \t\trequire(sig.length != 0, 'SV_SIGLEN');
                \t\tuint8 modeRaw;
                \t\tunchecked {
                \t\t\tmodeRaw = uint8(sig[sig.length - 1]);
                \t\t}
                \t\t// Ensure we're in bounds for mode; Solidity does this as well but it will just silently blow up rather than showing a decent error
                \t\tif (modeRaw >= uint8(SignatureMode.LastUnused)) {
                \t\t\tif (sig.length == 65) modeRaw = uint8(SignatureMode.Unprotected);
                \t\t\telse revert('SV_SIGMODE');
                \t\t}
                \t\tSignatureMode mode = SignatureMode(modeRaw);
                \t\t// the address of the key we are gonna be returning
                \t\taddress signerKey;
                \t\t// wrap in the EIP712 wrapping if it's not unbound
                \t\t// multisig gets an exception because each inner sig will have to apply this logic
                \t\t// @TODO should spoofing be removed from this?
                \t\tbool isUnprotected = mode == SignatureMode.Unprotected || mode == SignatureMode.Multisig;
                \t\tif (!isUnprotected) {
                \t\t\tbytes32 DOMAIN_SEPARATOR = keccak256(abi.encode(
                \t\t\t\tkeccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)'),
                \t\t\t\tkeccak256(bytes('Ambire')),
                \t\t\t\tkeccak256(bytes('1')),
                \t\t\t\tblock.chainid,
                \t\t\t\taddress(this),
                \t\t\t\tbytes32(0)
                \t\t\t));
                \t\t\thash = keccak256(abi.encodePacked(
                \t\t\t\t'\\x19\\x01',
                \t\t\t\tDOMAIN_SEPARATOR,
                \t\t\t\tkeccak256(abi.encode(
                \t\t\t\t\tkeccak256(bytes('AmbireOperation(address account,bytes32 hash)')),
                \t\t\t\t\taddress(this),
                \t\t\t\t\thash
                \t\t\t\t))
                \t\t\t));
                \t\t}
                \t\t// {r}{s}{v}{mode}
                \t\tif (mode == SignatureMode.Unprotected || mode == SignatureMode.Standard) {
                \t\t\trequire(sig.length == 65 || sig.length == 66, 'SV_LEN');
                \t\t\tbytes32 r = sig.readBytes32(0);
                \t\t\tbytes32 s = sig.readBytes32(32);
                \t\t\tuint8 v = uint8(sig[64]);
                \t\t\tsignerKey = ecrecover(hash, v, r, s);
                \t\t// {sig}{verifier}{mode}
                \t\t} else if (mode == SignatureMode.Schnorr) {
                \t\t\t// Based on https://hackmd.io/@nZ-twauPRISEa6G9zg3XRw/SyjJzSLt9
                \t\t\t// You can use this library to produce signatures: https://github.com/borislav-itskov/schnorrkel.js
                \t\t\t// px := public key x-coord
                \t\t\t// e := schnorr signature challenge
                \t\t\t// s := schnorr signature
                \t\t\t// parity := public key y-coord parity (27 or 28)
                \t\t\t// last uint8 is for the Ambire sig mode - it's ignored
                \t\t\tsig.trimToSize(sig.length - 1);
                \t\t\t(bytes32 px, bytes32 e, bytes32 s, uint8 parity) = abi.decode(sig, (bytes32, bytes32, bytes32, uint8));
                \t\t\t// ecrecover = (m, v, r, s);
                \t\t\tbytes32 sp = bytes32(Q - mulmod(uint256(s), uint256(px), Q));
                \t\t\tbytes32 ep = bytes32(Q - mulmod(uint256(e), uint256(px), Q));
                \t\t\trequire(sp != bytes32(Q));
                \t\t\t// the ecrecover precompile implementation checks that the `r` and `s`
                \t\t\t// inputs are non-zero (in this case, `px` and `ep`), thus we don't need to
                \t\t\t// check if they're zero.
                \t\t\taddress R = ecrecover(sp, parity, px, ep);
                \t\t\trequire(R != address(0), 'SV_ZERO_SIG');
                \t\t\trequire(e == keccak256(abi.encodePacked(R, uint8(parity), px, hash)), 'SV_SCHNORR_FAILED');
                \t\t\tsignerKey = address(uint160(uint256(keccak256(abi.encodePacked('SCHNORR', px)))));
                \t\t} else if (mode == SignatureMode.Multisig) {
                \t\t\tsig.trimToSize(sig.length - 1);
                \t\t\tbytes[] memory signatures = abi.decode(sig, (bytes[]));
                \t\t\t// since we're in a multisig, we care if any of the inner sigs are unbound
                \t\t\tisUnprotected = false;
                \t\t\tfor (uint256 i = 0; i != signatures.length; i++) {
                \t\t\t\t(address inner, bool isInnerUnprotected) = recoverAddrAllowUnprotected(hash, signatures[i], false);
                \t\t\t\tif (isInnerUnprotected) isUnprotected = true;
                \t\t\t\tsignerKey = address(
                \t\t\t\t\tuint160(uint256(keccak256(abi.encodePacked(signerKey, inner))))
                \t\t\t\t);
                \t\t\t}
                \t\t} else if (mode == SignatureMode.SmartWallet) {
                \t\t\t// 32 bytes for the addr, 1 byte for the type = 33
                \t\t\trequire(sig.length > 33, 'SV_LEN_WALLET');
                \t\t\tuint256 newLen;
                \t\t\tunchecked {
                \t\t\t\tnewLen = sig.length - 33;
                \t\t\t}
                \t\t\tIERC1271Wallet wallet = IERC1271Wallet(address(uint160(uint256(sig.readBytes32(newLen)))));
                \t\t\tsig.trimToSize(newLen);
                \t\t\trequire(ERC1271_MAGICVALUE_BYTES32 == wallet.isValidSignature(hash, sig), 'SV_WALLET_INVALID');
                \t\t\tsignerKey = address(wallet);
                \t\t// {address}{mode}; the spoof mode is used when simulating calls
                \t\t} else if (mode == SignatureMode.Spoof && allowSpoofing) {
                \t\t\t// This is safe cause it's specifically intended for spoofing sigs in simulation conditions, where tx.origin can be controlled
                \t\t\t// We did not choose 0x00..00 because in future network upgrades tx.origin may be nerfed or there may be edge cases in which
                \t\t\t// it is zero, such as native account abstraction
                \t\t\t// slither-disable-next-line tx-origin
                \t\t\trequire(tx.origin == address(1) || tx.origin == address(6969), 'SV_SPOOF_ORIGIN');
                \t\t\trequire(sig.length == 33, 'SV_SPOOF_LEN');
                \t\t\tsig.trimToSize(32);
                \t\t\t// To simulate the gas usage; check is just to silence unused warning
                \t\t\trequire(ecrecover(0, 0, 0, 0) != address(6969));
                \t\t\tsignerKey = abi.decode(sig, (address));
                \t\t} else {
                \t\t\trevert('SV_TYPE');
                \t\t}
                \t\trequire(signerKey != address(0), 'SV_ZERO_SIG');
                \t\treturn (signerKey, isUnprotected);
                \t}
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                // Transaction structure
                // we handle replay protection separately by requiring (address(this), chainID, nonce) as part of the sig
                // @dev a better name for this would be `Call`, but we are keeping `Transaction` for backwards compatibility
                struct Transaction {
                    address to;
                    uint256 value;
                    bytes data;
                }
                // SPDX-License-Identifier: GPL-3.0
                pragma solidity ^0.8.12;
                import "./PackedUserOperation.sol";
                /**
                 * the interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.
                 * a paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
                 */
                interface IPaymaster {
                    enum PostOpMode {
                        opSucceeded, // user op succeeded
                        opReverted, // user op reverted. still has to pay for gas.
                        postOpReverted //user op succeeded, but caused postOp to revert. Now it's a 2nd call, after user's op was deliberately reverted.
                    }
                    /**
                     * payment validation: check if paymaster agrees to pay.
                     * Must verify sender is the entryPoint.
                     * Revert to reject this request.
                     * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted)
                     * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.
                     * @param userOp the user operation
                     * @param userOpHash hash of the user's request data.
                     * @param maxCost the maximum cost of this transaction (based on maximum gas and gas price from userOp)
                     * @return context value to send to a postOp
                     *      zero length to signify postOp is not required.
                     * @return validationData signature and time-range of this operation, encoded the same as the return value of validateUserOperation
                     *      <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
                     *         otherwise, an address of an "authorizer" contract.
                     *      <6-byte> validUntil - last timestamp this operation is valid. 0 for "indefinite"
                     *      <6-byte> validAfter - first timestamp this operation is valid
                     *      Note that the validation code cannot use block.timestamp (or block.number) directly.
                     */
                    function validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost)
                    external returns (bytes memory context, uint256 validationData);
                    /**
                     * post-operation handler.
                     * Must verify sender is the entryPoint
                     * @param mode enum with the following options:
                     *      opSucceeded - user operation succeeded.
                     *      opReverted  - user op reverted. still has to pay for gas.
                     *      postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.
                     *                       Now this is the 2nd call, after user's op was deliberately reverted.
                     * @param context - the context value returned by validatePaymasterUserOp
                     * @param actualGasCost - actual gas used so far (without this postOp call).
                     */
                    function postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) external;
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                /**
                 * User Operation struct
                 * @param sender                - The sender account of this request.
                 * @param nonce                 - Unique value the sender uses to verify it is not a replay.
                 * @param initCode              - If set, the account contract will be created by this constructor/
                 * @param callData              - The method call to execute on this account.
                 * @param accountGasLimits      - Packed gas limits for validateUserOp and gas limit passed to the callData method call.
                 * @param preVerificationGas    - Gas not calculated by the handleOps method, but added to the gas paid.
                 *                                Covers batch overhead.
                 * @param gasFees               - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.
                 * @param paymasterAndData      - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data
                 *                                The paymaster will pay for the transaction instead of the sender.
                 * @param signature             - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.
                 */
                struct PackedUserOperation {
                  address sender;
                  uint256 nonce;
                  bytes initCode;
                  bytes callData;
                  // callGasLimit + verificationGasLimit
                  bytes32 accountGasLimits;
                  uint256 preVerificationGas;
                  // maxFeePerGas + maxPriorityFeePerGas
                  bytes32 gasFees;
                  bytes paymasterAndData;
                  bytes signature;
                }
                // SPDX-License-Identifier: agpl-3.0
                pragma solidity 0.8.19;
                library UserOpHelper {
                \tuint256 public constant PAYMASTER_ADDR_OFFSET = 20;
                  // 52 = 20 address + 16 paymasterVerificationGasLimit + 16 paymasterPostOpGasLimit
                \tuint256 public constant PAYMASTER_DATA_OFFSET = 52;
                }
                

                File 11 of 12: FiatTokenV2_2
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { EIP712Domain } from "./EIP712Domain.sol"; // solhint-disable-line no-unused-import
                import { Blacklistable } from "../v1/Blacklistable.sol"; // solhint-disable-line no-unused-import
                import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; // solhint-disable-line no-unused-import
                import { FiatTokenV2 } from "./FiatTokenV2.sol"; // solhint-disable-line no-unused-import
                import { FiatTokenV2_1 } from "./FiatTokenV2_1.sol";
                import { EIP712 } from "../util/EIP712.sol";
                // solhint-disable func-name-mixedcase
                /**
                 * @title FiatToken V2.2
                 * @notice ERC20 Token backed by fiat reserves, version 2.2
                 */
                contract FiatTokenV2_2 is FiatTokenV2_1 {
                    /**
                     * @notice Initialize v2.2
                     * @param accountsToBlacklist   A list of accounts to migrate from the old blacklist
                     * @param newSymbol             New token symbol
                     * data structure to the new blacklist data structure.
                     */
                    function initializeV2_2(
                        address[] calldata accountsToBlacklist,
                        string calldata newSymbol
                    ) external {
                        // solhint-disable-next-line reason-string
                        require(_initializedVersion == 2);
                        // Update fiat token symbol
                        symbol = newSymbol;
                        // Add previously blacklisted accounts to the new blacklist data structure
                        // and remove them from the old blacklist data structure.
                        for (uint256 i = 0; i < accountsToBlacklist.length; i++) {
                            require(
                                _deprecatedBlacklisted[accountsToBlacklist[i]],
                                "FiatTokenV2_2: Blacklisting previously unblacklisted account!"
                            );
                            _blacklist(accountsToBlacklist[i]);
                            delete _deprecatedBlacklisted[accountsToBlacklist[i]];
                        }
                        _blacklist(address(this));
                        delete _deprecatedBlacklisted[address(this)];
                        _initializedVersion = 3;
                    }
                    /**
                     * @dev Internal function to get the current chain id.
                     * @return The current chain id.
                     */
                    function _chainId() internal virtual view returns (uint256) {
                        uint256 chainId;
                        assembly {
                            chainId := chainid()
                        }
                        return chainId;
                    }
                    /**
                     * @inheritdoc EIP712Domain
                     */
                    function _domainSeparator() internal override view returns (bytes32) {
                        return EIP712.makeDomainSeparator(name, "2", _chainId());
                    }
                    /**
                     * @notice Update allowance with a signed permit
                     * @dev EOA wallet signatures should be packed in the order of r, s, v.
                     * @param owner       Token owner's address (Authorizer)
                     * @param spender     Spender's address
                     * @param value       Amount of allowance
                     * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                     * @param signature   Signature bytes signed by an EOA wallet or a contract wallet
                     */
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        bytes memory signature
                    ) external whenNotPaused {
                        _permit(owner, spender, value, deadline, signature);
                    }
                    /**
                     * @notice Execute a transfer with a signed authorization
                     * @dev EOA wallet signatures should be packed in the order of r, s, v.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                     */
                    function transferWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        bytes memory signature
                    ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                        _transferWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            signature
                        );
                    }
                    /**
                     * @notice Receive a transfer with a signed authorization from the payer
                     * @dev This has an additional check to ensure that the payee's address
                     * matches the caller of this function to prevent front-running attacks.
                     * EOA wallet signatures should be packed in the order of r, s, v.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                     */
                    function receiveWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        bytes memory signature
                    ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                        _receiveWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            signature
                        );
                    }
                    /**
                     * @notice Attempt to cancel an authorization
                     * @dev Works only if the authorization is not yet used.
                     * EOA wallet signatures should be packed in the order of r, s, v.
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                     */
                    function cancelAuthorization(
                        address authorizer,
                        bytes32 nonce,
                        bytes memory signature
                    ) external whenNotPaused {
                        _cancelAuthorization(authorizer, nonce, signature);
                    }
                    /**
                     * @dev Helper method that sets the blacklist state of an account on balanceAndBlacklistStates.
                     * If _shouldBlacklist is true, we apply a (1 << 255) bitmask with an OR operation on the
                     * account's balanceAndBlacklistState. This flips the high bit for the account to 1,
                     * indicating that the account is blacklisted.
                     *
                     * If _shouldBlacklist if false, we reset the account's balanceAndBlacklistStates to their
                     * balances. This clears the high bit for the account, indicating that the account is unblacklisted.
                     * @param _account         The address of the account.
                     * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                     */
                    function _setBlacklistState(address _account, bool _shouldBlacklist)
                        internal
                        override
                    {
                        balanceAndBlacklistStates[_account] = _shouldBlacklist
                            ? balanceAndBlacklistStates[_account] | (1 << 255)
                            : _balanceOf(_account);
                    }
                    /**
                     * @dev Helper method that sets the balance of an account on balanceAndBlacklistStates.
                     * Since balances are stored in the last 255 bits of the balanceAndBlacklistStates value,
                     * we need to ensure that the updated balance does not exceed (2^255 - 1).
                     * Since blacklisted accounts' balances cannot be updated, the method will also
                     * revert if the account is blacklisted
                     * @param _account The address of the account.
                     * @param _balance The new fiat token balance of the account (max: (2^255 - 1)).
                     */
                    function _setBalance(address _account, uint256 _balance) internal override {
                        require(
                            _balance <= ((1 << 255) - 1),
                            "FiatTokenV2_2: Balance exceeds (2^255 - 1)"
                        );
                        require(
                            !_isBlacklisted(_account),
                            "FiatTokenV2_2: Account is blacklisted"
                        );
                        balanceAndBlacklistStates[_account] = _balance;
                    }
                    /**
                     * @inheritdoc Blacklistable
                     */
                    function _isBlacklisted(address _account)
                        internal
                        override
                        view
                        returns (bool)
                    {
                        return balanceAndBlacklistStates[_account] >> 255 == 1;
                    }
                    /**
                     * @dev Helper method to obtain the balance of an account. Since balances
                     * are stored in the last 255 bits of the balanceAndBlacklistStates value,
                     * we apply a ((1 << 255) - 1) bit bitmask with an AND operation on the
                     * balanceAndBlacklistState to obtain the balance.
                     * @param _account  The address of the account.
                     * @return          The fiat token balance of the account.
                     */
                    function _balanceOf(address _account)
                        internal
                        override
                        view
                        returns (uint256)
                    {
                        return balanceAndBlacklistStates[_account] & ((1 << 255) - 1);
                    }
                    /**
                     * @inheritdoc FiatTokenV1
                     */
                    function approve(address spender, uint256 value)
                        external
                        override
                        whenNotPaused
                        returns (bool)
                    {
                        _approve(msg.sender, spender, value);
                        return true;
                    }
                    /**
                     * @inheritdoc FiatTokenV2
                     */
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external override whenNotPaused {
                        _permit(owner, spender, value, deadline, v, r, s);
                    }
                    /**
                     * @inheritdoc FiatTokenV2
                     */
                    function increaseAllowance(address spender, uint256 increment)
                        external
                        override
                        whenNotPaused
                        returns (bool)
                    {
                        _increaseAllowance(msg.sender, spender, increment);
                        return true;
                    }
                    /**
                     * @inheritdoc FiatTokenV2
                     */
                    function decreaseAllowance(address spender, uint256 decrement)
                        external
                        override
                        whenNotPaused
                        returns (bool)
                    {
                        _decreaseAllowance(msg.sender, spender, decrement);
                        return true;
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.2 <0.8.0;
                /**
                 * @dev Collection of functions related to the address type
                 */
                library Address {
                    /**
                     * @dev Returns true if `account` is a contract.
                     *
                     * [IMPORTANT]
                     * ====
                     * It is unsafe to assume that an address for which this function returns
                     * false is an externally-owned account (EOA) and not a contract.
                     *
                     * Among others, `isContract` will return false for the following
                     * types of addresses:
                     *
                     *  - an externally-owned account
                     *  - a contract in construction
                     *  - an address where a contract will be created
                     *  - an address where a contract lived, but was destroyed
                     * ====
                     */
                    function isContract(address account) internal view returns (bool) {
                        // This method relies on extcodesize, which returns 0 for contracts in
                        // construction, since the code is only stored at the end of the
                        // constructor execution.
                        uint256 size;
                        // solhint-disable-next-line no-inline-assembly
                        assembly { size := extcodesize(account) }
                        return size > 0;
                    }
                    /**
                     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                     * `recipient`, forwarding all available gas and reverting on errors.
                     *
                     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                     * of certain opcodes, possibly making contracts go over the 2300 gas limit
                     * imposed by `transfer`, making them unable to receive funds via
                     * `transfer`. {sendValue} removes this limitation.
                     *
                     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                     *
                     * IMPORTANT: because control is transferred to `recipient`, care must be
                     * taken to not create reentrancy vulnerabilities. Consider using
                     * {ReentrancyGuard} or the
                     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                     */
                    function sendValue(address payable recipient, uint256 amount) internal {
                        require(address(this).balance >= amount, "Address: insufficient balance");
                        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                        (bool success, ) = recipient.call{ value: amount }("");
                        require(success, "Address: unable to send value, recipient may have reverted");
                    }
                    /**
                     * @dev Performs a Solidity function call using a low level `call`. A
                     * plain`call` is an unsafe replacement for a function call: use this
                     * function instead.
                     *
                     * If `target` reverts with a revert reason, it is bubbled up by this
                     * function (like regular Solidity function calls).
                     *
                     * Returns the raw returned data. To convert to the expected return value,
                     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                     *
                     * Requirements:
                     *
                     * - `target` must be a contract.
                     * - calling `target` with `data` must not revert.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                      return functionCall(target, data, "Address: low-level call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                     * `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, 0, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but also transferring `value` wei to `target`.
                     *
                     * Requirements:
                     *
                     * - the calling contract must have an ETH balance of at least `value`.
                     * - the called Solidity function must be `payable`.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                     * with `errorMessage` as a fallback revert reason when `target` reverts.
                     *
                     * _Available since v3.1._
                     */
                    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                        require(address(this).balance >= value, "Address: insufficient balance for call");
                        require(isContract(target), "Address: call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.call{ value: value }(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                        return functionStaticCall(target, data, "Address: low-level static call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a static call.
                     *
                     * _Available since v3.3._
                     */
                    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                        require(isContract(target), "Address: static call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.staticcall(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                    }
                    /**
                     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                     * but performing a delegate call.
                     *
                     * _Available since v3.4._
                     */
                    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                        require(isContract(target), "Address: delegate call to non-contract");
                        // solhint-disable-next-line avoid-low-level-calls
                        (bool success, bytes memory returndata) = target.delegatecall(data);
                        return _verifyCallResult(success, returndata, errorMessage);
                    }
                    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                        if (success) {
                            return returndata;
                        } else {
                            // Look for revert reason and bubble it up if present
                            if (returndata.length > 0) {
                                // The easiest way to bubble the revert reason is using memory via assembly
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    let returndata_size := mload(returndata)
                                    revert(add(32, returndata), returndata_size)
                                }
                            } else {
                                revert(errorMessage);
                            }
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <0.8.0;
                import "./IERC20.sol";
                import "../../math/SafeMath.sol";
                import "../../utils/Address.sol";
                /**
                 * @title SafeERC20
                 * @dev Wrappers around ERC20 operations that throw on failure (when the token
                 * contract returns false). Tokens that return no value (and instead revert or
                 * throw on failure) are also supported, non-reverting calls are assumed to be
                 * successful.
                 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                 */
                library SafeERC20 {
                    using SafeMath for uint256;
                    using Address for address;
                    function safeTransfer(IERC20 token, address to, uint256 value) internal {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                    }
                    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                    }
                    /**
                     * @dev Deprecated. This function has issues similar to the ones found in
                     * {IERC20-approve}, and its usage is discouraged.
                     *
                     * Whenever possible, use {safeIncreaseAllowance} and
                     * {safeDecreaseAllowance} instead.
                     */
                    function safeApprove(IERC20 token, address spender, uint256 value) internal {
                        // safeApprove should only be called when setting an initial allowance,
                        // or when resetting it to zero. To increase and decrease it, use
                        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                        // solhint-disable-next-line max-line-length
                        require((value == 0) || (token.allowance(address(this), spender) == 0),
                            "SafeERC20: approve from non-zero to non-zero allowance"
                        );
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                    }
                    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        uint256 newAllowance = token.allowance(address(this), spender).add(value);
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                    }
                    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                        uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                    }
                    /**
                     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                     * on the return value: the return value is optional (but if data is returned, it must not be false).
                     * @param token The token targeted by the call.
                     * @param data The call data (encoded using abi.encode or one of its variants).
                     */
                    function _callOptionalReturn(IERC20 token, bytes memory data) private {
                        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                        // the target address contains contract code and also asserts for success in the low-level call.
                        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                        if (returndata.length > 0) { // Return data is optional
                            // solhint-disable-next-line max-line-length
                            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                        }
                    }
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <0.8.0;
                /**
                 * @dev Interface of the ERC20 standard as defined in the EIP.
                 */
                interface IERC20 {
                    /**
                     * @dev Returns the amount of tokens in existence.
                     */
                    function totalSupply() external view returns (uint256);
                    /**
                     * @dev Returns the amount of tokens owned by `account`.
                     */
                    function balanceOf(address account) external view returns (uint256);
                    /**
                     * @dev Moves `amount` tokens from the caller's account to `recipient`.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transfer(address recipient, uint256 amount) external returns (bool);
                    /**
                     * @dev Returns the remaining number of tokens that `spender` will be
                     * allowed to spend on behalf of `owner` through {transferFrom}. This is
                     * zero by default.
                     *
                     * This value changes when {approve} or {transferFrom} are called.
                     */
                    function allowance(address owner, address spender) external view returns (uint256);
                    /**
                     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * IMPORTANT: Beware that changing an allowance with this method brings the risk
                     * that someone may use both the old and the new allowance by unfortunate
                     * transaction ordering. One possible solution to mitigate this race
                     * condition is to first reduce the spender's allowance to 0 and set the
                     * desired value afterwards:
                     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                     *
                     * Emits an {Approval} event.
                     */
                    function approve(address spender, uint256 amount) external returns (bool);
                    /**
                     * @dev Moves `amount` tokens from `sender` to `recipient` using the
                     * allowance mechanism. `amount` is then deducted from the caller's
                     * allowance.
                     *
                     * Returns a boolean value indicating whether the operation succeeded.
                     *
                     * Emits a {Transfer} event.
                     */
                    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                    /**
                     * @dev Emitted when `value` tokens are moved from one account (`from`) to
                     * another (`to`).
                     *
                     * Note that `value` may be zero.
                     */
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    /**
                     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                     * a call to {approve}. `value` is the new allowance.
                     */
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                }
                // SPDX-License-Identifier: MIT
                pragma solidity >=0.6.0 <0.8.0;
                /**
                 * @dev Wrappers over Solidity's arithmetic operations with added overflow
                 * checks.
                 *
                 * Arithmetic operations in Solidity wrap on overflow. This can easily result
                 * in bugs, because programmers usually assume that an overflow raises an
                 * error, which is the standard behavior in high level programming languages.
                 * `SafeMath` restores this intuition by reverting the transaction when an
                 * operation overflows.
                 *
                 * Using this library instead of the unchecked operations eliminates an entire
                 * class of bugs, so it's recommended to use it always.
                 */
                library SafeMath {
                    /**
                     * @dev Returns the addition of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        uint256 c = a + b;
                        if (c < a) return (false, 0);
                        return (true, c);
                    }
                    /**
                     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b > a) return (false, 0);
                        return (true, a - b);
                    }
                    /**
                     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                        if (a == 0) return (true, 0);
                        uint256 c = a * b;
                        if (c / a != b) return (false, 0);
                        return (true, c);
                    }
                    /**
                     * @dev Returns the division of two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b == 0) return (false, 0);
                        return (true, a / b);
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                     *
                     * _Available since v3.4._
                     */
                    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                        if (b == 0) return (false, 0);
                        return (true, a % b);
                    }
                    /**
                     * @dev Returns the addition of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `+` operator.
                     *
                     * Requirements:
                     *
                     * - Addition cannot overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a, "SafeMath: addition overflow");
                        return c;
                    }
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting on
                     * overflow (when the result is negative).
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b <= a, "SafeMath: subtraction overflow");
                        return a - b;
                    }
                    /**
                     * @dev Returns the multiplication of two unsigned integers, reverting on
                     * overflow.
                     *
                     * Counterpart to Solidity's `*` operator.
                     *
                     * Requirements:
                     *
                     * - Multiplication cannot overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        if (a == 0) return 0;
                        uint256 c = a * b;
                        require(c / a == b, "SafeMath: multiplication overflow");
                        return c;
                    }
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting on
                     * division by zero. The result is rounded towards zero.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b > 0, "SafeMath: division by zero");
                        return a / b;
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting when dividing by zero.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b > 0, "SafeMath: modulo by zero");
                        return a % b;
                    }
                    /**
                     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                     * overflow (when the result is negative).
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {trySub}.
                     *
                     * Counterpart to Solidity's `-` operator.
                     *
                     * Requirements:
                     *
                     * - Subtraction cannot overflow.
                     */
                    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b <= a, errorMessage);
                        return a - b;
                    }
                    /**
                     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                     * division by zero. The result is rounded towards zero.
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {tryDiv}.
                     *
                     * Counterpart to Solidity's `/` operator. Note: this function uses a
                     * `revert` opcode (which leaves remaining gas untouched) while Solidity
                     * uses an invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b > 0, errorMessage);
                        return a / b;
                    }
                    /**
                     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                     * reverting with custom message when dividing by zero.
                     *
                     * CAUTION: This function is deprecated because it requires allocating memory for the error
                     * message unnecessarily. For custom revert reasons use {tryMod}.
                     *
                     * Counterpart to Solidity's `%` operator. This function uses a `revert`
                     * opcode (which leaves remaining gas untouched) while Solidity uses an
                     * invalid opcode to revert (consuming all remaining gas).
                     *
                     * Requirements:
                     *
                     * - The divisor cannot be zero.
                     */
                    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                        require(b > 0, errorMessage);
                        return a % b;
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { FiatTokenV2 } from "./FiatTokenV2.sol";
                // solhint-disable func-name-mixedcase
                /**
                 * @title FiatToken V2.1
                 * @notice ERC20 Token backed by fiat reserves, version 2.1
                 */
                contract FiatTokenV2_1 is FiatTokenV2 {
                    /**
                     * @notice Initialize v2.1
                     * @param lostAndFound  The address to which the locked funds are sent
                     */
                    function initializeV2_1(address lostAndFound) external {
                        // solhint-disable-next-line reason-string
                        require(_initializedVersion == 1);
                        uint256 lockedAmount = _balanceOf(address(this));
                        if (lockedAmount > 0) {
                            _transfer(address(this), lostAndFound, lockedAmount);
                        }
                        _blacklist(address(this));
                        _initializedVersion = 2;
                    }
                    /**
                     * @notice Version string for the EIP712 domain separator
                     * @return Version string
                     */
                    function version() external pure returns (string memory) {
                        return "2";
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol";
                import { EIP712 } from "../util/EIP712.sol";
                import { EIP3009 } from "./EIP3009.sol";
                import { EIP2612 } from "./EIP2612.sol";
                /**
                 * @title FiatToken V2
                 * @notice ERC20 Token backed by fiat reserves, version 2
                 */
                contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
                    uint8 internal _initializedVersion;
                    /**
                     * @notice Initialize v2
                     * @param newName   New token name
                     */
                    function initializeV2(string calldata newName) external {
                        // solhint-disable-next-line reason-string
                        require(initialized && _initializedVersion == 0);
                        name = newName;
                        _DEPRECATED_CACHED_DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(
                            newName,
                            "2"
                        );
                        _initializedVersion = 1;
                    }
                    /**
                     * @notice Increase the allowance by a given increment
                     * @param spender   Spender's address
                     * @param increment Amount of increase in allowance
                     * @return True if successful
                     */
                    function increaseAllowance(address spender, uint256 increment)
                        external
                        virtual
                        whenNotPaused
                        notBlacklisted(msg.sender)
                        notBlacklisted(spender)
                        returns (bool)
                    {
                        _increaseAllowance(msg.sender, spender, increment);
                        return true;
                    }
                    /**
                     * @notice Decrease the allowance by a given decrement
                     * @param spender   Spender's address
                     * @param decrement Amount of decrease in allowance
                     * @return True if successful
                     */
                    function decreaseAllowance(address spender, uint256 decrement)
                        external
                        virtual
                        whenNotPaused
                        notBlacklisted(msg.sender)
                        notBlacklisted(spender)
                        returns (bool)
                    {
                        _decreaseAllowance(msg.sender, spender, decrement);
                        return true;
                    }
                    /**
                     * @notice Execute a transfer with a signed authorization
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function transferWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                        _transferWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            v,
                            r,
                            s
                        );
                    }
                    /**
                     * @notice Receive a transfer with a signed authorization from the payer
                     * @dev This has an additional check to ensure that the payee's address
                     * matches the caller of this function to prevent front-running attacks.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function receiveWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                        _receiveWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            v,
                            r,
                            s
                        );
                    }
                    /**
                     * @notice Attempt to cancel an authorization
                     * @dev Works only if the authorization is not yet used.
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function cancelAuthorization(
                        address authorizer,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) external whenNotPaused {
                        _cancelAuthorization(authorizer, nonce, v, r, s);
                    }
                    /**
                     * @notice Update allowance with a signed permit
                     * @param owner       Token owner's address (Authorizer)
                     * @param spender     Spender's address
                     * @param value       Amount of allowance
                     * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                     * @param v           v of the signature
                     * @param r           r of the signature
                     * @param s           s of the signature
                     */
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    )
                        external
                        virtual
                        whenNotPaused
                        notBlacklisted(owner)
                        notBlacklisted(spender)
                    {
                        _permit(owner, spender, value, deadline, v, r, s);
                    }
                    /**
                     * @dev Internal function to increase the allowance by a given increment
                     * @param owner     Token owner's address
                     * @param spender   Spender's address
                     * @param increment Amount of increase
                     */
                    function _increaseAllowance(
                        address owner,
                        address spender,
                        uint256 increment
                    ) internal override {
                        _approve(owner, spender, allowed[owner][spender].add(increment));
                    }
                    /**
                     * @dev Internal function to decrease the allowance by a given decrement
                     * @param owner     Token owner's address
                     * @param spender   Spender's address
                     * @param decrement Amount of decrease
                     */
                    function _decreaseAllowance(
                        address owner,
                        address spender,
                        uint256 decrement
                    ) internal override {
                        _approve(
                            owner,
                            spender,
                            allowed[owner][spender].sub(
                                decrement,
                                "ERC20: decreased allowance below zero"
                            )
                        );
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                // solhint-disable func-name-mixedcase
                /**
                 * @title EIP712 Domain
                 */
                contract EIP712Domain {
                    // was originally DOMAIN_SEPARATOR
                    // but that has been moved to a method so we can override it in V2_2+
                    bytes32 internal _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                    /**
                     * @notice Get the EIP712 Domain Separator.
                     * @return The bytes32 EIP712 domain separator.
                     */
                    function DOMAIN_SEPARATOR() external view returns (bytes32) {
                        return _domainSeparator();
                    }
                    /**
                     * @dev Internal method to get the EIP712 Domain Separator.
                     * @return The bytes32 EIP712 domain separator.
                     */
                    function _domainSeparator() internal virtual view returns (bytes32) {
                        return _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                import { EIP712Domain } from "./EIP712Domain.sol";
                import { SignatureChecker } from "../util/SignatureChecker.sol";
                import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                /**
                 * @title EIP-3009
                 * @notice Provide internal implementation for gas-abstracted transfers
                 * @dev Contracts that inherit from this must wrap these with publicly
                 * accessible functions, optionally adding modifiers where necessary
                 */
                abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
                    // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                    bytes32
                        public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
                    // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                    bytes32
                        public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
                    // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
                    bytes32
                        public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
                    /**
                     * @dev authorizer address => nonce => bool (true if nonce is used)
                     */
                    mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
                    event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
                    event AuthorizationCanceled(
                        address indexed authorizer,
                        bytes32 indexed nonce
                    );
                    /**
                     * @notice Returns the state of an authorization
                     * @dev Nonces are randomly generated 32-byte data unique to the
                     * authorizer's address
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @return True if the nonce is used
                     */
                    function authorizationState(address authorizer, bytes32 nonce)
                        external
                        view
                        returns (bool)
                    {
                        return _authorizationStates[authorizer][nonce];
                    }
                    /**
                     * @notice Execute a transfer with a signed authorization
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function _transferWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        _transferWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            abi.encodePacked(r, s, v)
                        );
                    }
                    /**
                     * @notice Execute a transfer with a signed authorization
                     * @dev EOA wallet signatures should be packed in the order of r, s, v.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                     */
                    function _transferWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        bytes memory signature
                    ) internal {
                        _requireValidAuthorization(from, nonce, validAfter, validBefore);
                        _requireValidSignature(
                            from,
                            keccak256(
                                abi.encode(
                                    TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                                    from,
                                    to,
                                    value,
                                    validAfter,
                                    validBefore,
                                    nonce
                                )
                            ),
                            signature
                        );
                        _markAuthorizationAsUsed(from, nonce);
                        _transfer(from, to, value);
                    }
                    /**
                     * @notice Receive a transfer with a signed authorization from the payer
                     * @dev This has an additional check to ensure that the payee's address
                     * matches the caller of this function to prevent front-running attacks.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function _receiveWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        _receiveWithAuthorization(
                            from,
                            to,
                            value,
                            validAfter,
                            validBefore,
                            nonce,
                            abi.encodePacked(r, s, v)
                        );
                    }
                    /**
                     * @notice Receive a transfer with a signed authorization from the payer
                     * @dev This has an additional check to ensure that the payee's address
                     * matches the caller of this function to prevent front-running attacks.
                     * EOA wallet signatures should be packed in the order of r, s, v.
                     * @param from          Payer's address (Authorizer)
                     * @param to            Payee's address
                     * @param value         Amount to be transferred
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     * @param nonce         Unique nonce
                     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                     */
                    function _receiveWithAuthorization(
                        address from,
                        address to,
                        uint256 value,
                        uint256 validAfter,
                        uint256 validBefore,
                        bytes32 nonce,
                        bytes memory signature
                    ) internal {
                        require(to == msg.sender, "FiatTokenV2: caller must be the payee");
                        _requireValidAuthorization(from, nonce, validAfter, validBefore);
                        _requireValidSignature(
                            from,
                            keccak256(
                                abi.encode(
                                    RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                                    from,
                                    to,
                                    value,
                                    validAfter,
                                    validBefore,
                                    nonce
                                )
                            ),
                            signature
                        );
                        _markAuthorizationAsUsed(from, nonce);
                        _transfer(from, to, value);
                    }
                    /**
                     * @notice Attempt to cancel an authorization
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @param v             v of the signature
                     * @param r             r of the signature
                     * @param s             s of the signature
                     */
                    function _cancelAuthorization(
                        address authorizer,
                        bytes32 nonce,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        _cancelAuthorization(authorizer, nonce, abi.encodePacked(r, s, v));
                    }
                    /**
                     * @notice Attempt to cancel an authorization
                     * @dev EOA wallet signatures should be packed in the order of r, s, v.
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                     */
                    function _cancelAuthorization(
                        address authorizer,
                        bytes32 nonce,
                        bytes memory signature
                    ) internal {
                        _requireUnusedAuthorization(authorizer, nonce);
                        _requireValidSignature(
                            authorizer,
                            keccak256(
                                abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce)
                            ),
                            signature
                        );
                        _authorizationStates[authorizer][nonce] = true;
                        emit AuthorizationCanceled(authorizer, nonce);
                    }
                    /**
                     * @notice Validates that signature against input data struct
                     * @param signer        Signer's address
                     * @param dataHash      Hash of encoded data struct
                     * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                     */
                    function _requireValidSignature(
                        address signer,
                        bytes32 dataHash,
                        bytes memory signature
                    ) private view {
                        require(
                            SignatureChecker.isValidSignatureNow(
                                signer,
                                MessageHashUtils.toTypedDataHash(_domainSeparator(), dataHash),
                                signature
                            ),
                            "FiatTokenV2: invalid signature"
                        );
                    }
                    /**
                     * @notice Check that an authorization is unused
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     */
                    function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
                        private
                        view
                    {
                        require(
                            !_authorizationStates[authorizer][nonce],
                            "FiatTokenV2: authorization is used or canceled"
                        );
                    }
                    /**
                     * @notice Check that authorization is valid
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     * @param validAfter    The time after which this is valid (unix time)
                     * @param validBefore   The time before which this is valid (unix time)
                     */
                    function _requireValidAuthorization(
                        address authorizer,
                        bytes32 nonce,
                        uint256 validAfter,
                        uint256 validBefore
                    ) private view {
                        require(
                            now > validAfter,
                            "FiatTokenV2: authorization is not yet valid"
                        );
                        require(now < validBefore, "FiatTokenV2: authorization is expired");
                        _requireUnusedAuthorization(authorizer, nonce);
                    }
                    /**
                     * @notice Mark an authorization as used
                     * @param authorizer    Authorizer's address
                     * @param nonce         Nonce of the authorization
                     */
                    function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
                        private
                    {
                        _authorizationStates[authorizer][nonce] = true;
                        emit AuthorizationUsed(authorizer, nonce);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                import { EIP712Domain } from "./EIP712Domain.sol";
                import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                import { SignatureChecker } from "../util/SignatureChecker.sol";
                /**
                 * @title EIP-2612
                 * @notice Provide internal implementation for gas-abstracted approvals
                 */
                abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
                    // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                    bytes32
                        public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                    mapping(address => uint256) private _permitNonces;
                    /**
                     * @notice Nonces for permit
                     * @param owner Token owner's address (Authorizer)
                     * @return Next nonce
                     */
                    function nonces(address owner) external view returns (uint256) {
                        return _permitNonces[owner];
                    }
                    /**
                     * @notice Verify a signed approval permit and execute if valid
                     * @param owner     Token owner's address (Authorizer)
                     * @param spender   Spender's address
                     * @param value     Amount of allowance
                     * @param deadline  The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                     * @param v         v of the signature
                     * @param r         r of the signature
                     * @param s         s of the signature
                     */
                    function _permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal {
                        _permit(owner, spender, value, deadline, abi.encodePacked(r, s, v));
                    }
                    /**
                     * @notice Verify a signed approval permit and execute if valid
                     * @dev EOA wallet signatures should be packed in the order of r, s, v.
                     * @param owner      Token owner's address (Authorizer)
                     * @param spender    Spender's address
                     * @param value      Amount of allowance
                     * @param deadline   The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                     * @param signature  Signature byte array signed by an EOA wallet or a contract wallet
                     */
                    function _permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        bytes memory signature
                    ) internal {
                        require(
                            deadline == type(uint256).max || deadline >= now,
                            "FiatTokenV2: permit is expired"
                        );
                        bytes32 typedDataHash = MessageHashUtils.toTypedDataHash(
                            _domainSeparator(),
                            keccak256(
                                abi.encode(
                                    PERMIT_TYPEHASH,
                                    owner,
                                    spender,
                                    value,
                                    _permitNonces[owner]++,
                                    deadline
                                )
                            )
                        );
                        require(
                            SignatureChecker.isValidSignatureNow(
                                owner,
                                typedDataHash,
                                signature
                            ),
                            "EIP2612: invalid signature"
                        );
                        _approve(owner, spender, value);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol";
                abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
                    function _increaseAllowance(
                        address owner,
                        address spender,
                        uint256 increment
                    ) internal virtual;
                    function _decreaseAllowance(
                        address owner,
                        address spender,
                        uint256 decrement
                    ) internal virtual;
                }
                /**
                 * SPDX-License-Identifier: MIT
                 *
                 * Copyright (c) 2016 Smart Contract Solutions, Inc.
                 * Copyright (c) 2018-2020 CENTRE SECZ
                 *
                 * Permission is hereby granted, free of charge, to any person obtaining a copy
                 * of this software and associated documentation files (the "Software"), to deal
                 * in the Software without restriction, including without limitation the rights
                 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                 * copies of the Software, and to permit persons to whom the Software is
                 * furnished to do so, subject to the following conditions:
                 *
                 * The above copyright notice and this permission notice shall be included in
                 * copies or substantial portions of the Software.
                 *
                 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                 * SOFTWARE.
                 */
                pragma solidity 0.6.12;
                import { Ownable } from "./Ownable.sol";
                /**
                 * @notice Base contract which allows children to implement an emergency stop
                 * mechanism
                 * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
                 * Modifications:
                 * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
                 * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
                 * 3. Removed whenPaused (6/14/2018)
                 * 4. Switches ownable library to use ZeppelinOS (7/12/18)
                 * 5. Remove constructor (7/13/18)
                 * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
                 * 7. Make public functions external (5/27/20)
                 */
                contract Pausable is Ownable {
                    event Pause();
                    event Unpause();
                    event PauserChanged(address indexed newAddress);
                    address public pauser;
                    bool public paused = false;
                    /**
                     * @dev Modifier to make a function callable only when the contract is not paused.
                     */
                    modifier whenNotPaused() {
                        require(!paused, "Pausable: paused");
                        _;
                    }
                    /**
                     * @dev throws if called by any account other than the pauser
                     */
                    modifier onlyPauser() {
                        require(msg.sender == pauser, "Pausable: caller is not the pauser");
                        _;
                    }
                    /**
                     * @dev called by the owner to pause, triggers stopped state
                     */
                    function pause() external onlyPauser {
                        paused = true;
                        emit Pause();
                    }
                    /**
                     * @dev called by the owner to unpause, returns to normal state
                     */
                    function unpause() external onlyPauser {
                        paused = false;
                        emit Unpause();
                    }
                    /**
                     * @notice Updates the pauser address.
                     * @param _newPauser The address of the new pauser.
                     */
                    function updatePauser(address _newPauser) external onlyOwner {
                        require(
                            _newPauser != address(0),
                            "Pausable: new pauser is the zero address"
                        );
                        pauser = _newPauser;
                        emit PauserChanged(pauser);
                    }
                }
                /**
                 * SPDX-License-Identifier: MIT
                 *
                 * Copyright (c) 2018 zOS Global Limited.
                 * Copyright (c) 2018-2020 CENTRE SECZ
                 *
                 * Permission is hereby granted, free of charge, to any person obtaining a copy
                 * of this software and associated documentation files (the "Software"), to deal
                 * in the Software without restriction, including without limitation the rights
                 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                 * copies of the Software, and to permit persons to whom the Software is
                 * furnished to do so, subject to the following conditions:
                 *
                 * The above copyright notice and this permission notice shall be included in
                 * copies or substantial portions of the Software.
                 *
                 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                 * SOFTWARE.
                 */
                pragma solidity 0.6.12;
                /**
                 * @notice The Ownable contract has an owner address, and provides basic
                 * authorization control functions
                 * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
                 * Modifications:
                 * 1. Consolidate OwnableStorage into this contract (7/13/18)
                 * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
                 * 3. Make public functions external (5/27/20)
                 */
                contract Ownable {
                    // Owner of the contract
                    address private _owner;
                    /**
                     * @dev Event to show ownership has been transferred
                     * @param previousOwner representing the address of the previous owner
                     * @param newOwner representing the address of the new owner
                     */
                    event OwnershipTransferred(address previousOwner, address newOwner);
                    /**
                     * @dev The constructor sets the original owner of the contract to the sender account.
                     */
                    constructor() public {
                        setOwner(msg.sender);
                    }
                    /**
                     * @dev Tells the address of the owner
                     * @return the address of the owner
                     */
                    function owner() external view returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Sets a new owner address
                     */
                    function setOwner(address newOwner) internal {
                        _owner = newOwner;
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        require(msg.sender == _owner, "Ownable: caller is not the owner");
                        _;
                    }
                    /**
                     * @dev Allows the current owner to transfer control of the contract to a newOwner.
                     * @param newOwner The address to transfer ownership to.
                     */
                    function transferOwnership(address newOwner) external onlyOwner {
                        require(
                            newOwner != address(0),
                            "Ownable: new owner is the zero address"
                        );
                        emit OwnershipTransferred(_owner, newOwner);
                        setOwner(newOwner);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
                import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol";
                import { Ownable } from "./Ownable.sol";
                import { Pausable } from "./Pausable.sol";
                import { Blacklistable } from "./Blacklistable.sol";
                /**
                 * @title FiatToken
                 * @dev ERC20 Token backed by fiat reserves
                 */
                contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
                    using SafeMath for uint256;
                    string public name;
                    string public symbol;
                    uint8 public decimals;
                    string public currency;
                    address public masterMinter;
                    bool internal initialized;
                    /// @dev A mapping that stores the balance and blacklist states for a given address.
                    /// The first bit defines whether the address is blacklisted (1 if blacklisted, 0 otherwise).
                    /// The last 255 bits define the balance for the address.
                    mapping(address => uint256) internal balanceAndBlacklistStates;
                    mapping(address => mapping(address => uint256)) internal allowed;
                    uint256 internal totalSupply_ = 0;
                    mapping(address => bool) internal minters;
                    mapping(address => uint256) internal minterAllowed;
                    event Mint(address indexed minter, address indexed to, uint256 amount);
                    event Burn(address indexed burner, uint256 amount);
                    event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
                    event MinterRemoved(address indexed oldMinter);
                    event MasterMinterChanged(address indexed newMasterMinter);
                    /**
                     * @notice Initializes the fiat token contract.
                     * @param tokenName       The name of the fiat token.
                     * @param tokenSymbol     The symbol of the fiat token.
                     * @param tokenCurrency   The fiat currency that the token represents.
                     * @param tokenDecimals   The number of decimals that the token uses.
                     * @param newMasterMinter The masterMinter address for the fiat token.
                     * @param newPauser       The pauser address for the fiat token.
                     * @param newBlacklister  The blacklister address for the fiat token.
                     * @param newOwner        The owner of the fiat token.
                     */
                    function initialize(
                        string memory tokenName,
                        string memory tokenSymbol,
                        string memory tokenCurrency,
                        uint8 tokenDecimals,
                        address newMasterMinter,
                        address newPauser,
                        address newBlacklister,
                        address newOwner
                    ) public {
                        require(!initialized, "FiatToken: contract is already initialized");
                        require(
                            newMasterMinter != address(0),
                            "FiatToken: new masterMinter is the zero address"
                        );
                        require(
                            newPauser != address(0),
                            "FiatToken: new pauser is the zero address"
                        );
                        require(
                            newBlacklister != address(0),
                            "FiatToken: new blacklister is the zero address"
                        );
                        require(
                            newOwner != address(0),
                            "FiatToken: new owner is the zero address"
                        );
                        name = tokenName;
                        symbol = tokenSymbol;
                        currency = tokenCurrency;
                        decimals = tokenDecimals;
                        masterMinter = newMasterMinter;
                        pauser = newPauser;
                        blacklister = newBlacklister;
                        setOwner(newOwner);
                        initialized = true;
                    }
                    /**
                     * @dev Throws if called by any account other than a minter.
                     */
                    modifier onlyMinters() {
                        require(minters[msg.sender], "FiatToken: caller is not a minter");
                        _;
                    }
                    /**
                     * @notice Mints fiat tokens to an address.
                     * @param _to The address that will receive the minted tokens.
                     * @param _amount The amount of tokens to mint. Must be less than or equal
                     * to the minterAllowance of the caller.
                     * @return True if the operation was successful.
                     */
                    function mint(address _to, uint256 _amount)
                        external
                        whenNotPaused
                        onlyMinters
                        notBlacklisted(msg.sender)
                        notBlacklisted(_to)
                        returns (bool)
                    {
                        require(_to != address(0), "FiatToken: mint to the zero address");
                        require(_amount > 0, "FiatToken: mint amount not greater than 0");
                        uint256 mintingAllowedAmount = minterAllowed[msg.sender];
                        require(
                            _amount <= mintingAllowedAmount,
                            "FiatToken: mint amount exceeds minterAllowance"
                        );
                        totalSupply_ = totalSupply_.add(_amount);
                        _setBalance(_to, _balanceOf(_to).add(_amount));
                        minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
                        emit Mint(msg.sender, _to, _amount);
                        emit Transfer(address(0), _to, _amount);
                        return true;
                    }
                    /**
                     * @dev Throws if called by any account other than the masterMinter
                     */
                    modifier onlyMasterMinter() {
                        require(
                            msg.sender == masterMinter,
                            "FiatToken: caller is not the masterMinter"
                        );
                        _;
                    }
                    /**
                     * @notice Gets the minter allowance for an account.
                     * @param minter The address to check.
                     * @return The remaining minter allowance for the account.
                     */
                    function minterAllowance(address minter) external view returns (uint256) {
                        return minterAllowed[minter];
                    }
                    /**
                     * @notice Checks if an account is a minter.
                     * @param account The address to check.
                     * @return True if the account is a minter, false if the account is not a minter.
                     */
                    function isMinter(address account) external view returns (bool) {
                        return minters[account];
                    }
                    /**
                     * @notice Gets the remaining amount of fiat tokens a spender is allowed to transfer on
                     * behalf of the token owner.
                     * @param owner   The token owner's address.
                     * @param spender The spender's address.
                     * @return The remaining allowance.
                     */
                    function allowance(address owner, address spender)
                        external
                        override
                        view
                        returns (uint256)
                    {
                        return allowed[owner][spender];
                    }
                    /**
                     * @notice Gets the totalSupply of the fiat token.
                     * @return The totalSupply of the fiat token.
                     */
                    function totalSupply() external override view returns (uint256) {
                        return totalSupply_;
                    }
                    /**
                     * @notice Gets the fiat token balance of an account.
                     * @param account  The address to check.
                     * @return balance The fiat token balance of the account.
                     */
                    function balanceOf(address account)
                        external
                        override
                        view
                        returns (uint256)
                    {
                        return _balanceOf(account);
                    }
                    /**
                     * @notice Sets a fiat token allowance for a spender to spend on behalf of the caller.
                     * @param spender The spender's address.
                     * @param value   The allowance amount.
                     * @return True if the operation was successful.
                     */
                    function approve(address spender, uint256 value)
                        external
                        virtual
                        override
                        whenNotPaused
                        notBlacklisted(msg.sender)
                        notBlacklisted(spender)
                        returns (bool)
                    {
                        _approve(msg.sender, spender, value);
                        return true;
                    }
                    /**
                     * @dev Internal function to set allowance.
                     * @param owner     Token owner's address.
                     * @param spender   Spender's address.
                     * @param value     Allowance amount.
                     */
                    function _approve(
                        address owner,
                        address spender,
                        uint256 value
                    ) internal override {
                        require(owner != address(0), "ERC20: approve from the zero address");
                        require(spender != address(0), "ERC20: approve to the zero address");
                        allowed[owner][spender] = value;
                        emit Approval(owner, spender, value);
                    }
                    /**
                     * @notice Transfers tokens from an address to another by spending the caller's allowance.
                     * @dev The caller must have some fiat token allowance on the payer's tokens.
                     * @param from  Payer's address.
                     * @param to    Payee's address.
                     * @param value Transfer amount.
                     * @return True if the operation was successful.
                     */
                    function transferFrom(
                        address from,
                        address to,
                        uint256 value
                    )
                        external
                        override
                        whenNotPaused
                        notBlacklisted(msg.sender)
                        notBlacklisted(from)
                        notBlacklisted(to)
                        returns (bool)
                    {
                        require(
                            value <= allowed[from][msg.sender],
                            "ERC20: transfer amount exceeds allowance"
                        );
                        _transfer(from, to, value);
                        allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
                        return true;
                    }
                    /**
                     * @notice Transfers tokens from the caller.
                     * @param to    Payee's address.
                     * @param value Transfer amount.
                     * @return True if the operation was successful.
                     */
                    function transfer(address to, uint256 value)
                        external
                        override
                        whenNotPaused
                        notBlacklisted(msg.sender)
                        notBlacklisted(to)
                        returns (bool)
                    {
                        _transfer(msg.sender, to, value);
                        return true;
                    }
                    /**
                     * @dev Internal function to process transfers.
                     * @param from  Payer's address.
                     * @param to    Payee's address.
                     * @param value Transfer amount.
                     */
                    function _transfer(
                        address from,
                        address to,
                        uint256 value
                    ) internal override {
                        require(from != address(0), "ERC20: transfer from the zero address");
                        require(to != address(0), "ERC20: transfer to the zero address");
                        require(
                            value <= _balanceOf(from),
                            "ERC20: transfer amount exceeds balance"
                        );
                        _setBalance(from, _balanceOf(from).sub(value));
                        _setBalance(to, _balanceOf(to).add(value));
                        emit Transfer(from, to, value);
                    }
                    /**
                     * @notice Adds or updates a new minter with a mint allowance.
                     * @param minter The address of the minter.
                     * @param minterAllowedAmount The minting amount allowed for the minter.
                     * @return True if the operation was successful.
                     */
                    function configureMinter(address minter, uint256 minterAllowedAmount)
                        external
                        whenNotPaused
                        onlyMasterMinter
                        returns (bool)
                    {
                        minters[minter] = true;
                        minterAllowed[minter] = minterAllowedAmount;
                        emit MinterConfigured(minter, minterAllowedAmount);
                        return true;
                    }
                    /**
                     * @notice Removes a minter.
                     * @param minter The address of the minter to remove.
                     * @return True if the operation was successful.
                     */
                    function removeMinter(address minter)
                        external
                        onlyMasterMinter
                        returns (bool)
                    {
                        minters[minter] = false;
                        minterAllowed[minter] = 0;
                        emit MinterRemoved(minter);
                        return true;
                    }
                    /**
                     * @notice Allows a minter to burn some of its own tokens.
                     * @dev The caller must be a minter, must not be blacklisted, and the amount to burn
                     * should be less than or equal to the account's balance.
                     * @param _amount the amount of tokens to be burned.
                     */
                    function burn(uint256 _amount)
                        external
                        whenNotPaused
                        onlyMinters
                        notBlacklisted(msg.sender)
                    {
                        uint256 balance = _balanceOf(msg.sender);
                        require(_amount > 0, "FiatToken: burn amount not greater than 0");
                        require(balance >= _amount, "FiatToken: burn amount exceeds balance");
                        totalSupply_ = totalSupply_.sub(_amount);
                        _setBalance(msg.sender, balance.sub(_amount));
                        emit Burn(msg.sender, _amount);
                        emit Transfer(msg.sender, address(0), _amount);
                    }
                    /**
                     * @notice Updates the master minter address.
                     * @param _newMasterMinter The address of the new master minter.
                     */
                    function updateMasterMinter(address _newMasterMinter) external onlyOwner {
                        require(
                            _newMasterMinter != address(0),
                            "FiatToken: new masterMinter is the zero address"
                        );
                        masterMinter = _newMasterMinter;
                        emit MasterMinterChanged(masterMinter);
                    }
                    /**
                     * @inheritdoc Blacklistable
                     */
                    function _blacklist(address _account) internal override {
                        _setBlacklistState(_account, true);
                    }
                    /**
                     * @inheritdoc Blacklistable
                     */
                    function _unBlacklist(address _account) internal override {
                        _setBlacklistState(_account, false);
                    }
                    /**
                     * @dev Helper method that sets the blacklist state of an account.
                     * @param _account         The address of the account.
                     * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                     */
                    function _setBlacklistState(address _account, bool _shouldBlacklist)
                        internal
                        virtual
                    {
                        _deprecatedBlacklisted[_account] = _shouldBlacklist;
                    }
                    /**
                     * @dev Helper method that sets the balance of an account.
                     * @param _account The address of the account.
                     * @param _balance The new fiat token balance of the account.
                     */
                    function _setBalance(address _account, uint256 _balance) internal virtual {
                        balanceAndBlacklistStates[_account] = _balance;
                    }
                    /**
                     * @inheritdoc Blacklistable
                     */
                    function _isBlacklisted(address _account)
                        internal
                        virtual
                        override
                        view
                        returns (bool)
                    {
                        return _deprecatedBlacklisted[_account];
                    }
                    /**
                     * @dev Helper method to obtain the balance of an account.
                     * @param _account  The address of the account.
                     * @return          The fiat token balance of the account.
                     */
                    function _balanceOf(address _account)
                        internal
                        virtual
                        view
                        returns (uint256)
                    {
                        return balanceAndBlacklistStates[_account];
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { Ownable } from "./Ownable.sol";
                /**
                 * @title Blacklistable Token
                 * @dev Allows accounts to be blacklisted by a "blacklister" role
                 */
                abstract contract Blacklistable is Ownable {
                    address public blacklister;
                    mapping(address => bool) internal _deprecatedBlacklisted;
                    event Blacklisted(address indexed _account);
                    event UnBlacklisted(address indexed _account);
                    event BlacklisterChanged(address indexed newBlacklister);
                    /**
                     * @dev Throws if called by any account other than the blacklister.
                     */
                    modifier onlyBlacklister() {
                        require(
                            msg.sender == blacklister,
                            "Blacklistable: caller is not the blacklister"
                        );
                        _;
                    }
                    /**
                     * @dev Throws if argument account is blacklisted.
                     * @param _account The address to check.
                     */
                    modifier notBlacklisted(address _account) {
                        require(
                            !_isBlacklisted(_account),
                            "Blacklistable: account is blacklisted"
                        );
                        _;
                    }
                    /**
                     * @notice Checks if account is blacklisted.
                     * @param _account The address to check.
                     * @return True if the account is blacklisted, false if the account is not blacklisted.
                     */
                    function isBlacklisted(address _account) external view returns (bool) {
                        return _isBlacklisted(_account);
                    }
                    /**
                     * @notice Adds account to blacklist.
                     * @param _account The address to blacklist.
                     */
                    function blacklist(address _account) external onlyBlacklister {
                        _blacklist(_account);
                        emit Blacklisted(_account);
                    }
                    /**
                     * @notice Removes account from blacklist.
                     * @param _account The address to remove from the blacklist.
                     */
                    function unBlacklist(address _account) external onlyBlacklister {
                        _unBlacklist(_account);
                        emit UnBlacklisted(_account);
                    }
                    /**
                     * @notice Updates the blacklister address.
                     * @param _newBlacklister The address of the new blacklister.
                     */
                    function updateBlacklister(address _newBlacklister) external onlyOwner {
                        require(
                            _newBlacklister != address(0),
                            "Blacklistable: new blacklister is the zero address"
                        );
                        blacklister = _newBlacklister;
                        emit BlacklisterChanged(blacklister);
                    }
                    /**
                     * @dev Checks if account is blacklisted.
                     * @param _account The address to check.
                     * @return true if the account is blacklisted, false otherwise.
                     */
                    function _isBlacklisted(address _account)
                        internal
                        virtual
                        view
                        returns (bool);
                    /**
                     * @dev Helper method that blacklists an account.
                     * @param _account The address to blacklist.
                     */
                    function _blacklist(address _account) internal virtual;
                    /**
                     * @dev Helper method that unblacklists an account.
                     * @param _account The address to unblacklist.
                     */
                    function _unBlacklist(address _account) internal virtual;
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                abstract contract AbstractFiatTokenV1 is IERC20 {
                    function _approve(
                        address owner,
                        address spender,
                        uint256 value
                    ) internal virtual;
                    function _transfer(
                        address from,
                        address to,
                        uint256 value
                    ) internal virtual;
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { Ownable } from "../v1/Ownable.sol";
                import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
                contract Rescuable is Ownable {
                    using SafeERC20 for IERC20;
                    address private _rescuer;
                    event RescuerChanged(address indexed newRescuer);
                    /**
                     * @notice Returns current rescuer
                     * @return Rescuer's address
                     */
                    function rescuer() external view returns (address) {
                        return _rescuer;
                    }
                    /**
                     * @notice Revert if called by any account other than the rescuer.
                     */
                    modifier onlyRescuer() {
                        require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
                        _;
                    }
                    /**
                     * @notice Rescue ERC20 tokens locked up in this contract.
                     * @param tokenContract ERC20 token contract address
                     * @param to        Recipient address
                     * @param amount    Amount to withdraw
                     */
                    function rescueERC20(
                        IERC20 tokenContract,
                        address to,
                        uint256 amount
                    ) external onlyRescuer {
                        tokenContract.safeTransfer(to, amount);
                    }
                    /**
                     * @notice Updates the rescuer address.
                     * @param newRescuer The address of the new rescuer.
                     */
                    function updateRescuer(address newRescuer) external onlyOwner {
                        require(
                            newRescuer != address(0),
                            "Rescuable: new rescuer is the zero address"
                        );
                        _rescuer = newRescuer;
                        emit RescuerChanged(newRescuer);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { FiatTokenV1 } from "../v1/FiatTokenV1.sol";
                import { Rescuable } from "./Rescuable.sol";
                /**
                 * @title FiatTokenV1_1
                 * @dev ERC20 Token backed by fiat reserves
                 */
                contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                import { ECRecover } from "./ECRecover.sol";
                import { IERC1271 } from "../interface/IERC1271.sol";
                /**
                 * @dev Signature verification helper that can be used instead of `ECRecover.recover` to seamlessly support both ECDSA
                 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets.
                 *
                 * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/SignatureChecker.sol
                 */
                library SignatureChecker {
                    /**
                     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
                     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECRecover.recover`.
                     * @param signer        Address of the claimed signer
                     * @param digest        Keccak-256 hash digest of the signed message
                     * @param signature     Signature byte array associated with hash
                     */
                    function isValidSignatureNow(
                        address signer,
                        bytes32 digest,
                        bytes memory signature
                    ) external view returns (bool) {
                        if (!isContract(signer)) {
                            return ECRecover.recover(digest, signature) == signer;
                        }
                        return isValidERC1271SignatureNow(signer, digest, signature);
                    }
                    /**
                     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
                     * against the signer smart contract using ERC1271.
                     * @param signer        Address of the claimed signer
                     * @param digest        Keccak-256 hash digest of the signed message
                     * @param signature     Signature byte array associated with hash
                     *
                     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
                     * change through time. It could return true at block N and false at block N+1 (or the opposite).
                     */
                    function isValidERC1271SignatureNow(
                        address signer,
                        bytes32 digest,
                        bytes memory signature
                    ) internal view returns (bool) {
                        (bool success, bytes memory result) = signer.staticcall(
                            abi.encodeWithSelector(
                                IERC1271.isValidSignature.selector,
                                digest,
                                signature
                            )
                        );
                        return (success &&
                            result.length >= 32 &&
                            abi.decode(result, (bytes32)) ==
                            bytes32(IERC1271.isValidSignature.selector));
                    }
                    /**
                     * @dev Checks if the input address is a smart contract.
                     */
                    function isContract(address addr) internal view returns (bool) {
                        uint256 size;
                        assembly {
                            size := extcodesize(addr)
                        }
                        return size > 0;
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                /**
                 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
                 *
                 * The library provides methods for generating a hash of a message that conforms to the
                 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
                 * specifications.
                 */
                library MessageHashUtils {
                    /**
                     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
                     * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/MessageHashUtils.sol
                     *
                     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
                     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the
                     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
                     *
                     * @param domainSeparator    Domain separator
                     * @param structHash         Hashed EIP-712 data struct
                     * @return digest            The keccak256 digest of an EIP-712 typed data
                     */
                    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
                        internal
                        pure
                        returns (bytes32 digest)
                    {
                        assembly {
                            let ptr := mload(0x40)
                            mstore(ptr, "\\x19\\x01")
                            mstore(add(ptr, 0x02), domainSeparator)
                            mstore(add(ptr, 0x22), structHash)
                            digest := keccak256(ptr, 0x42)
                        }
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                /**
                 * @title EIP712
                 * @notice A library that provides EIP712 helper functions
                 */
                library EIP712 {
                    /**
                     * @notice Make EIP712 domain separator
                     * @param name      Contract name
                     * @param version   Contract version
                     * @param chainId   Blockchain ID
                     * @return Domain separator
                     */
                    function makeDomainSeparator(
                        string memory name,
                        string memory version,
                        uint256 chainId
                    ) internal view returns (bytes32) {
                        return
                            keccak256(
                                abi.encode(
                                    // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
                                    0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                    keccak256(bytes(name)),
                                    keccak256(bytes(version)),
                                    chainId,
                                    address(this)
                                )
                            );
                    }
                    /**
                     * @notice Make EIP712 domain separator
                     * @param name      Contract name
                     * @param version   Contract version
                     * @return Domain separator
                     */
                    function makeDomainSeparator(string memory name, string memory version)
                        internal
                        view
                        returns (bytes32)
                    {
                        uint256 chainId;
                        assembly {
                            chainId := chainid()
                        }
                        return makeDomainSeparator(name, version, chainId);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                /**
                 * @title ECRecover
                 * @notice A library that provides a safe ECDSA recovery function
                 */
                library ECRecover {
                    /**
                     * @notice Recover signer's address from a signed message
                     * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
                     * Modifications: Accept v, r, and s as separate arguments
                     * @param digest    Keccak-256 hash digest of the signed message
                     * @param v         v of the signature
                     * @param r         r of the signature
                     * @param s         s of the signature
                     * @return Signer address
                     */
                    function recover(
                        bytes32 digest,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) internal pure returns (address) {
                        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                        // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                        //
                        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                        // these malleable signatures as well.
                        if (
                            uint256(s) >
                            0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                        ) {
                            revert("ECRecover: invalid signature 's' value");
                        }
                        if (v != 27 && v != 28) {
                            revert("ECRecover: invalid signature 'v' value");
                        }
                        // If the signature is valid (and not malleable), return the signer address
                        address signer = ecrecover(digest, v, r, s);
                        require(signer != address(0), "ECRecover: invalid signature");
                        return signer;
                    }
                    /**
                     * @notice Recover signer's address from a signed message
                     * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0053ee040a7ff1dbc39691c9e67a69f564930a88/contracts/utils/cryptography/ECDSA.sol
                     * @param digest    Keccak-256 hash digest of the signed message
                     * @param signature Signature byte array associated with hash
                     * @return Signer address
                     */
                    function recover(bytes32 digest, bytes memory signature)
                        internal
                        pure
                        returns (address)
                    {
                        require(signature.length == 65, "ECRecover: invalid signature length");
                        bytes32 r;
                        bytes32 s;
                        uint8 v;
                        // ecrecover takes the signature parameters, and the only way to get them
                        // currently is to use assembly.
                        /// @solidity memory-safe-assembly
                        assembly {
                            r := mload(add(signature, 0x20))
                            s := mload(add(signature, 0x40))
                            v := byte(0, mload(add(signature, 0x60)))
                        }
                        return recover(digest, v, r, s);
                    }
                }
                /**
                 * SPDX-License-Identifier: Apache-2.0
                 *
                 * Copyright (c) 2023, Circle Internet Financial, LLC.
                 *
                 * Licensed under the Apache License, Version 2.0 (the "License");
                 * you may not use this file except in compliance with the License.
                 * You may obtain a copy of the License at
                 *
                 * http://www.apache.org/licenses/LICENSE-2.0
                 *
                 * Unless required by applicable law or agreed to in writing, software
                 * distributed under the License is distributed on an "AS IS" BASIS,
                 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                 * See the License for the specific language governing permissions and
                 * limitations under the License.
                 */
                pragma solidity 0.6.12;
                /**
                 * @dev Interface of the ERC1271 standard signature validation method for
                 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                 */
                interface IERC1271 {
                    /**
                     * @dev Should return whether the signature provided is valid for the provided data
                     * @param hash          Hash of the data to be signed
                     * @param signature     Signature byte array associated with the provided data hash
                     * @return magicValue   bytes4 magic value 0x1626ba7e when function passes
                     */
                    function isValidSignature(bytes32 hash, bytes memory signature)
                        external
                        view
                        returns (bytes4 magicValue);
                }
                

                File 12 of 12: UFragments
                pragma solidity 0.7.6;
                import "./_external/SafeMath.sol";
                import "./_external/Ownable.sol";
                import "./_external/ERC20Detailed.sol";
                import "./lib/SafeMathInt.sol";
                /**
                 * @title uFragments ERC20 token
                 * @dev This is part of an implementation of the uFragments Ideal Money protocol.
                 *      uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and
                 *      combining tokens proportionally across all wallets.
                 *
                 *      uFragment balances are internally represented with a hidden denomination, 'gons'.
                 *      We support splitting the currency in expansion and combining the currency on contraction by
                 *      changing the exchange rate between the hidden 'gons' and the public 'fragments'.
                 */
                contract UFragments is ERC20Detailed, Ownable {
                    // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
                    // Anytime there is division, there is a risk of numerical instability from rounding errors. In
                    // order to minimize this risk, we adhere to the following guidelines:
                    // 1) The conversion rate adopted is the number of gons that equals 1 fragment.
                    //    The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
                    //    always the denominator. (i.e. If you want to convert gons to fragments instead of
                    //    multiplying by the inverse rate, you should divide by the normal rate)
                    // 2) Gon balances converted into Fragments are always rounded down (truncated).
                    //
                    // We make the following guarantees:
                    // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
                    //   be decreased by precisely x Fragments, and B's external balance will be precisely
                    //   increased by x Fragments.
                    //
                    // We do not guarantee that the sum of all balances equals the result of calling totalSupply().
                    // This is because, for any conversion function 'f()' that has non-zero rounding error,
                    // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
                    using SafeMath for uint256;
                    using SafeMathInt for int256;
                    event LogRebase(uint256 indexed epoch, uint256 totalSupply);
                    event LogMonetaryPolicyUpdated(address monetaryPolicy);
                    // Used for authentication
                    address public monetaryPolicy;
                    modifier onlyMonetaryPolicy() {
                        require(msg.sender == monetaryPolicy);
                        _;
                    }
                    bool private rebasePausedDeprecated;
                    bool private tokenPausedDeprecated;
                    modifier validRecipient(address to) {
                        require(to != address(0x0));
                        require(to != address(this));
                        _;
                    }
                    uint256 private constant DECIMALS = 9;
                    uint256 private constant MAX_UINT256 = type(uint256).max;
                    uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 50 * 10**6 * 10**DECIMALS;
                    // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
                    // Use the highest value that fits in a uint256 for max granularity.
                    uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
                    // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
                    uint256 private constant MAX_SUPPLY = type(uint128).max; // (2^128) - 1
                    uint256 private _totalSupply;
                    uint256 private _gonsPerFragment;
                    mapping(address => uint256) private _gonBalances;
                    // This is denominated in Fragments, because the gons-fragments conversion might change before
                    // it's fully paid.
                    mapping(address => mapping(address => uint256)) private _allowedFragments;
                    // EIP-2612: permit – 712-signed approvals
                    // https://eips.ethereum.org/EIPS/eip-2612
                    string public constant EIP712_REVISION = "1";
                    bytes32 public constant EIP712_DOMAIN =
                        keccak256(
                            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                        );
                    bytes32 public constant PERMIT_TYPEHASH =
                        keccak256(
                            "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                        );
                    // EIP-2612: keeps track of number of permits per address
                    mapping(address => uint256) private _nonces;
                    /**
                     * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
                     */
                    function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner {
                        monetaryPolicy = monetaryPolicy_;
                        emit LogMonetaryPolicyUpdated(monetaryPolicy_);
                    }
                    /**
                     * @dev Notifies Fragments contract about a new rebase cycle.
                     * @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
                     * @return The total number of fragments after the supply adjustment.
                     */
                    function rebase(uint256 epoch, int256 supplyDelta)
                        external
                        onlyMonetaryPolicy
                        returns (uint256)
                    {
                        if (supplyDelta == 0) {
                            emit LogRebase(epoch, _totalSupply);
                            return _totalSupply;
                        }
                        if (supplyDelta < 0) {
                            _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
                        } else {
                            _totalSupply = _totalSupply.add(uint256(supplyDelta));
                        }
                        if (_totalSupply > MAX_SUPPLY) {
                            _totalSupply = MAX_SUPPLY;
                        }
                        _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
                        // From this point forward, _gonsPerFragment is taken as the source of truth.
                        // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
                        // conversion rate.
                        // This means our applied supplyDelta can deviate from the requested supplyDelta,
                        // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
                        //
                        // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
                        // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
                        // ever increased, it must be re-included.
                        // _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
                        emit LogRebase(epoch, _totalSupply);
                        return _totalSupply;
                    }
                    function initialize(address owner_) public override initializer {
                        ERC20Detailed.initialize("Ampleforth", "AMPL", uint8(DECIMALS));
                        Ownable.initialize(owner_);
                        rebasePausedDeprecated = false;
                        tokenPausedDeprecated = false;
                        _totalSupply = INITIAL_FRAGMENTS_SUPPLY;
                        _gonBalances[owner_] = TOTAL_GONS;
                        _gonsPerFragment = TOTAL_GONS.div(_totalSupply);
                        emit Transfer(address(0x0), owner_, _totalSupply);
                    }
                    /**
                     * @return The total number of fragments.
                     */
                    function totalSupply() external view override returns (uint256) {
                        return _totalSupply;
                    }
                    /**
                     * @param who The address to query.
                     * @return The balance of the specified address.
                     */
                    function balanceOf(address who) external view override returns (uint256) {
                        return _gonBalances[who].div(_gonsPerFragment);
                    }
                    /**
                     * @param who The address to query.
                     * @return The gon balance of the specified address.
                     */
                    function scaledBalanceOf(address who) external view returns (uint256) {
                        return _gonBalances[who];
                    }
                    /**
                     * @return the total number of gons.
                     */
                    function scaledTotalSupply() external pure returns (uint256) {
                        return TOTAL_GONS;
                    }
                    /**
                     * @return The number of successful permits by the specified address.
                     */
                    function nonces(address who) public view returns (uint256) {
                        return _nonces[who];
                    }
                    /**
                     * @return The computed DOMAIN_SEPARATOR to be used off-chain services
                     *         which implement EIP-712.
                     *         https://eips.ethereum.org/EIPS/eip-2612
                     */
                    function DOMAIN_SEPARATOR() public view returns (bytes32) {
                        uint256 chainId;
                        assembly {
                            chainId := chainid()
                        }
                        return
                            keccak256(
                                abi.encode(
                                    EIP712_DOMAIN,
                                    keccak256(bytes(name())),
                                    keccak256(bytes(EIP712_REVISION)),
                                    chainId,
                                    address(this)
                                )
                            );
                    }
                    /**
                     * @dev Transfer tokens to a specified address.
                     * @param to The address to transfer to.
                     * @param value The amount to be transferred.
                     * @return True on success, false otherwise.
                     */
                    function transfer(address to, uint256 value)
                        external
                        override
                        validRecipient(to)
                        returns (bool)
                    {
                        uint256 gonValue = value.mul(_gonsPerFragment);
                        _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
                        _gonBalances[to] = _gonBalances[to].add(gonValue);
                        emit Transfer(msg.sender, to, value);
                        return true;
                    }
                    /**
                     * @dev Transfer all of the sender's wallet balance to a specified address.
                     * @param to The address to transfer to.
                     * @return True on success, false otherwise.
                     */
                    function transferAll(address to) external validRecipient(to) returns (bool) {
                        uint256 gonValue = _gonBalances[msg.sender];
                        uint256 value = gonValue.div(_gonsPerFragment);
                        delete _gonBalances[msg.sender];
                        _gonBalances[to] = _gonBalances[to].add(gonValue);
                        emit Transfer(msg.sender, to, value);
                        return true;
                    }
                    /**
                     * @dev Function to check the amount of tokens that an owner has allowed to a spender.
                     * @param owner_ The address which owns the funds.
                     * @param spender The address which will spend the funds.
                     * @return The number of tokens still available for the spender.
                     */
                    function allowance(address owner_, address spender) external view override returns (uint256) {
                        return _allowedFragments[owner_][spender];
                    }
                    /**
                     * @dev Transfer tokens from one address to another.
                     * @param from The address you want to send tokens from.
                     * @param to The address you want to transfer to.
                     * @param value The amount of tokens to be transferred.
                     */
                    function transferFrom(
                        address from,
                        address to,
                        uint256 value
                    ) external override validRecipient(to) returns (bool) {
                        _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
                        uint256 gonValue = value.mul(_gonsPerFragment);
                        _gonBalances[from] = _gonBalances[from].sub(gonValue);
                        _gonBalances[to] = _gonBalances[to].add(gonValue);
                        emit Transfer(from, to, value);
                        return true;
                    }
                    /**
                     * @dev Transfer all balance tokens from one address to another.
                     * @param from The address you want to send tokens from.
                     * @param to The address you want to transfer to.
                     */
                    function transferAllFrom(address from, address to) external validRecipient(to) returns (bool) {
                        uint256 gonValue = _gonBalances[from];
                        uint256 value = gonValue.div(_gonsPerFragment);
                        _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
                        delete _gonBalances[from];
                        _gonBalances[to] = _gonBalances[to].add(gonValue);
                        emit Transfer(from, to, value);
                        return true;
                    }
                    /**
                     * @dev Approve the passed address to spend the specified amount of tokens on behalf of
                     * msg.sender. This method is included for ERC20 compatibility.
                     * increaseAllowance and decreaseAllowance should be used instead.
                     * Changing an allowance with this method brings the risk that someone may transfer both
                     * the old and the new allowance - if they are both greater than zero - if a transfer
                     * transaction is mined before the later approve() call is mined.
                     *
                     * @param spender The address which will spend the funds.
                     * @param value The amount of tokens to be spent.
                     */
                    function approve(address spender, uint256 value) external override returns (bool) {
                        _allowedFragments[msg.sender][spender] = value;
                        emit Approval(msg.sender, spender, value);
                        return true;
                    }
                    /**
                     * @dev Increase the amount of tokens that an owner has allowed to a spender.
                     * This method should be used instead of approve() to avoid the double approval vulnerability
                     * described above.
                     * @param spender The address which will spend the funds.
                     * @param addedValue The amount of tokens to increase the allowance by.
                     */
                    function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
                        _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(
                            addedValue
                        );
                        emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                        return true;
                    }
                    /**
                     * @dev Decrease the amount of tokens that an owner has allowed to a spender.
                     *
                     * @param spender The address which will spend the funds.
                     * @param subtractedValue The amount of tokens to decrease the allowance by.
                     */
                    function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
                        uint256 oldValue = _allowedFragments[msg.sender][spender];
                        _allowedFragments[msg.sender][spender] = (subtractedValue >= oldValue)
                            ? 0
                            : oldValue.sub(subtractedValue);
                        emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
                        return true;
                    }
                    /**
                     * @dev Allows for approvals to be made via secp256k1 signatures.
                     * @param owner The owner of the funds
                     * @param spender The spender
                     * @param value The amount
                     * @param deadline The deadline timestamp, type(uint256).max for max deadline
                     * @param v Signature param
                     * @param s Signature param
                     * @param r Signature param
                     */
                    function permit(
                        address owner,
                        address spender,
                        uint256 value,
                        uint256 deadline,
                        uint8 v,
                        bytes32 r,
                        bytes32 s
                    ) public {
                        require(block.timestamp <= deadline);
                        uint256 ownerNonce = _nonces[owner];
                        bytes32 permitDataDigest =
                            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, ownerNonce, deadline));
                        bytes32 digest =
                            keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR(), permitDataDigest));
                        require(owner == ecrecover(digest, v, r, s));
                        _nonces[owner] = ownerNonce.add(1);
                        _allowedFragments[owner][spender] = value;
                        emit Approval(owner, spender, value);
                    }
                }
                pragma solidity 0.7.6;
                /**
                 * @title SafeMath
                 * @dev Math operations with safety checks that revert on error
                 */
                library SafeMath {
                    /**
                     * @dev Multiplies two numbers, reverts on overflow.
                     */
                    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                        // benefit is lost if 'b' is also tested.
                        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
                        if (a == 0) {
                            return 0;
                        }
                        uint256 c = a * b;
                        require(c / a == b);
                        return c;
                    }
                    /**
                     * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
                     */
                    function div(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b > 0); // Solidity only automatically asserts when dividing by 0
                        uint256 c = a / b;
                        // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                        return c;
                    }
                    /**
                     * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                     */
                    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b <= a);
                        uint256 c = a - b;
                        return c;
                    }
                    /**
                     * @dev Adds two numbers, reverts on overflow.
                     */
                    function add(uint256 a, uint256 b) internal pure returns (uint256) {
                        uint256 c = a + b;
                        require(c >= a);
                        return c;
                    }
                    /**
                     * @dev Divides two numbers and returns the remainder (unsigned integer modulo),
                     * reverts when dividing by zero.
                     */
                    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                        require(b != 0);
                        return a % b;
                    }
                }
                pragma solidity 0.7.6;
                import "./Initializable.sol";
                /**
                 * @title Ownable
                 * @dev The Ownable contract has an owner address, and provides basic authorization control
                 * functions, this simplifies the implementation of "user permissions".
                 */
                contract Ownable is Initializable {
                    address private _owner;
                    event OwnershipRenounced(address indexed previousOwner);
                    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    /**
                     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                     * account.
                     */
                    function initialize(address sender) public virtual initializer {
                        _owner = sender;
                    }
                    /**
                     * @return the address of the owner.
                     */
                    function owner() public view returns (address) {
                        return _owner;
                    }
                    /**
                     * @dev Throws if called by any account other than the owner.
                     */
                    modifier onlyOwner() {
                        require(isOwner());
                        _;
                    }
                    /**
                     * @return true if `msg.sender` is the owner of the contract.
                     */
                    function isOwner() public view returns (bool) {
                        return msg.sender == _owner;
                    }
                    /**
                     * @dev Allows the current owner to relinquish control of the contract.
                     * @notice Renouncing to ownership will leave the contract without an owner.
                     * It will not be possible to call the functions with the `onlyOwner`
                     * modifier anymore.
                     */
                    function renounceOwnership() public onlyOwner {
                        emit OwnershipRenounced(_owner);
                        _owner = address(0);
                    }
                    /**
                     * @dev Allows the current owner to transfer control of the contract to a newOwner.
                     * @param newOwner The address to transfer ownership to.
                     */
                    function transferOwnership(address newOwner) public onlyOwner {
                        _transferOwnership(newOwner);
                    }
                    /**
                     * @dev Transfers control of the contract to a newOwner.
                     * @param newOwner The address to transfer ownership to.
                     */
                    function _transferOwnership(address newOwner) internal {
                        require(newOwner != address(0));
                        emit OwnershipTransferred(_owner, newOwner);
                        _owner = newOwner;
                    }
                    uint256[50] private ______gap;
                }
                pragma solidity 0.7.6;
                import "./Initializable.sol";
                import "./IERC20.sol";
                /**
                 * @title ERC20Detailed token
                 * @dev The decimals are only for visualization purposes.
                 * All the operations are done using the smallest and indivisible token unit,
                 * just as on Ethereum all the operations are done in wei.
                 */
                abstract contract ERC20Detailed is Initializable, IERC20 {
                    string private _name;
                    string private _symbol;
                    uint8 private _decimals;
                    function initialize(
                        string memory name,
                        string memory symbol,
                        uint8 decimals
                    ) public virtual initializer {
                        _name = name;
                        _symbol = symbol;
                        _decimals = decimals;
                    }
                    /**
                     * @return the name of the token.
                     */
                    function name() public view returns (string memory) {
                        return _name;
                    }
                    /**
                     * @return the symbol of the token.
                     */
                    function symbol() public view returns (string memory) {
                        return _symbol;
                    }
                    /**
                     * @return the number of decimals of the token.
                     */
                    function decimals() public view returns (uint8) {
                        return _decimals;
                    }
                    uint256[50] private ______gap;
                }
                /*
                MIT License
                Copyright (c) 2018 requestnetwork
                Copyright (c) 2018 Fragments, Inc.
                Permission is hereby granted, free of charge, to any person obtaining a copy
                of this software and associated documentation files (the "Software"), to deal
                in the Software without restriction, including without limitation the rights
                to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                copies of the Software, and to permit persons to whom the Software is
                furnished to do so, subject to the following conditions:
                The above copyright notice and this permission notice shall be included in all
                copies or substantial portions of the Software.
                THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                SOFTWARE.
                */
                pragma solidity 0.7.6;
                /**
                 * @title SafeMathInt
                 * @dev Math operations for int256 with overflow safety checks.
                 */
                library SafeMathInt {
                    int256 private constant MIN_INT256 = int256(1) << 255;
                    int256 private constant MAX_INT256 = ~(int256(1) << 255);
                    /**
                     * @dev Multiplies two int256 variables and fails on overflow.
                     */
                    function mul(int256 a, int256 b) internal pure returns (int256) {
                        int256 c = a * b;
                        // Detect overflow when multiplying MIN_INT256 with -1
                        require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
                        require((b == 0) || (c / b == a));
                        return c;
                    }
                    /**
                     * @dev Division of two int256 variables and fails on overflow.
                     */
                    function div(int256 a, int256 b) internal pure returns (int256) {
                        // Prevent overflow when dividing MIN_INT256 by -1
                        require(b != -1 || a != MIN_INT256);
                        // Solidity already throws when dividing by 0.
                        return a / b;
                    }
                    /**
                     * @dev Subtracts two int256 variables and fails on overflow.
                     */
                    function sub(int256 a, int256 b) internal pure returns (int256) {
                        int256 c = a - b;
                        require((b >= 0 && c <= a) || (b < 0 && c > a));
                        return c;
                    }
                    /**
                     * @dev Adds two int256 variables and fails on overflow.
                     */
                    function add(int256 a, int256 b) internal pure returns (int256) {
                        int256 c = a + b;
                        require((b >= 0 && c >= a) || (b < 0 && c < a));
                        return c;
                    }
                    /**
                     * @dev Converts to absolute value, and fails on overflow.
                     */
                    function abs(int256 a) internal pure returns (int256) {
                        require(a != MIN_INT256);
                        return a < 0 ? -a : a;
                    }
                }
                pragma solidity 0.7.6;
                /**
                 * @title Initializable
                 *
                 * @dev Helper contract to support initializer functions. To use it, replace
                 * the constructor with a function that has the `initializer` modifier.
                 * WARNING: Unlike constructors, initializer functions must be manually
                 * invoked. This applies both to deploying an Initializable contract, as well
                 * as extending an Initializable contract via inheritance.
                 * WARNING: When used with inheritance, manual care must be taken to not invoke
                 * a parent initializer twice, or ensure that all initializers are idempotent,
                 * because this is not dealt with automatically as with constructors.
                 */
                contract Initializable {
                    /**
                     * @dev Indicates that the contract has been initialized.
                     */
                    bool private initialized;
                    /**
                     * @dev Indicates that the contract is in the process of being initialized.
                     */
                    bool private initializing;
                    /**
                     * @dev Modifier to use in the initializer function of a contract.
                     */
                    modifier initializer() {
                        require(
                            initializing || isConstructor() || !initialized,
                            "Contract instance has already been initialized"
                        );
                        bool wasInitializing = initializing;
                        initializing = true;
                        initialized = true;
                        _;
                        initializing = wasInitializing;
                    }
                    /// @dev Returns true if and only if the function is running in the constructor
                    function isConstructor() private view returns (bool) {
                        // extcodesize checks the size of the code stored in an address, and
                        // address returns the current address. Since the code is still not
                        // deployed when running a constructor, any checks on its code size will
                        // yield zero, making it an effective way to detect if a contract is
                        // under construction or not.
                        // MINOR CHANGE HERE:
                        // previous code
                        // uint256 cs;
                        // assembly { cs := extcodesize(address) }
                        // return cs == 0;
                        // current code
                        address _self = address(this);
                        uint256 cs;
                        assembly {
                            cs := extcodesize(_self)
                        }
                        return cs == 0;
                    }
                    // Reserved storage space to allow for layout changes in the future.
                    uint256[50] private ______gap;
                }
                pragma solidity 0.7.6;
                /**
                 * @title ERC20 interface
                 * @dev see https://github.com/ethereum/EIPs/issues/20
                 */
                interface IERC20 {
                    function totalSupply() external view returns (uint256);
                    function balanceOf(address who) external view returns (uint256);
                    function allowance(address owner, address spender) external view returns (uint256);
                    function transfer(address to, uint256 value) external returns (bool);
                    function approve(address spender, uint256 value) external returns (bool);
                    function transferFrom(
                        address from,
                        address to,
                        uint256 value
                    ) external returns (bool);
                    event Transfer(address indexed from, address indexed to, uint256 value);
                    event Approval(address indexed owner, address indexed spender, uint256 value);
                }