Transaction Hash:
Block:
19275684 at Feb-21-2024 11:17:59 AM +UTC
Transaction Fee:
0.01279189741729126 ETH
$29.50
Gas Used:
402,460 Gas / 31.784270281 Gwei
Emitted Events:
42 |
WETH9.Deposit( dst=MetaRouter, wad=1153657049182576727 )
|
43 |
WETH9.Transfer( src=MetaRouter, dst=TransparentUpgradeableProxy, wad=1153657049182576727 )
|
44 |
TransparentUpgradeableProxy.0x532dbb6d061eee97ab4370060f60ede10b3dc361cc1214c07ae5e34dd86e6aaf( 0x532dbb6d061eee97ab4370060f60ede10b3dc361cc1214c07ae5e34dd86e6aaf, 0000000000000000000000005523985926aa12ba58dc5ad00ddca99678d7227e, 00000000000000000000000000000000000000000000000000000000000000a0, 000000000000000000000000b8f275fbf7a959f4bce59999a2ef122a099e81a8, 0000000000000000000000005523985926aa12ba58dc5ad00ddca99678d7227e, 000000000000000000000000000000000000000000000000000000000000dbe0, 0000000000000000000000000000000000000000000000000000000000000a04, c29a91bc00000000000000000000000000000000000000000000000000000000, 0000002000000000000000000000000000000000000000000000000000016bcc, 41e9000000000000000000000000000000000000000000000000000010029cf9, 5127205752a3ac966c473f4764837a6eb9bcbe5540cd69e4e0036b46aa9dd488, 26fe7ebb8a1056ad37db298e220b00078c8fe56c9b366a104c3de2abbbd85cfc, 7c204f38000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead908, 3c756cc200000000000000000000000000000000000000000000000000000000, 000000010000000000000000000000003334f5d5b3f9843df783c79fe87cba03, c59289ae00000000000000000000000000000000000000000000000000000000, 000001a0000000000000000000000000cb28fbe3e9c0fea62e0e63ff3f232cec, fe555ad400000000000000000000000000000000000000000000000000000000, 00000200000000000000000000000000b8f275fbf7a959f4bce59999a2ef122a, 099e81a800000000000000000000000000000000000000000000000000000000, 0000052000000000000000000000000000000000000000000000000000000000, 0000006400000000000000000000000000000000000000000000000000000000, 000000020000000000000000000000001ce4e75e2bd6bbbacde1e10d68132281, 38337e86000000000000000000000000424190072b7db5352bb91cc70dabd82f, 547ae00300000000000000000000000000000000000000000000000000000000, 000002e41e859a05000000000000000000000000000000000000000000000000, 10029cf951272057000000000000000000000000000000000000000000000000, 00000000000000c0000000000000000000000000000000000000000000000000, 0000000000000200000000000000000000000000000000000000000000000000, 0000000000000240000000000000000000000000000000000000000000000000, 00000000000002a00000000000000000000000002cbabd7329b84e2c0a317702, 410e7c73d0e0246d000000000000000000000000000000000000000000000000, 0000000000000001000000000000000000000000000000000000000000000000, 0000000000000020000000000000000000000000000000000000000000000000, 00000000000000c48f6bdeaa0000000000000000000000000000000000000000, 0000000000000000000000090000000000000000000000000000000000000000, 0000000000000000000000060000000000000000000000000000000000000000, 000000001001312d0f3e20570000000000000000000000000000000000000000, 000000000feb04dca8b94f30000000000000000000000000cb28fbe3e9c0fea6, 2e0e63ff3f232cecfe555ad40000000000000000000000000000000000000000, 000000000000000065df16160000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000001000000000000000000000000bcc2637dfa64999f75abb53a, 7265b5b4932e40eb000000000000000000000000000000000000000000000000, 00000000000000020000000000000000000000001ce4e75e2bd6bbbacde1e10d, 6813228138337e86000000000000000000000000424190072b7db5352bb91cc7, 0dabd82f547ae003000000000000000000000000000000000000000000000000, 0000000000000001000000000000000000000000000000000000000000000000, 0000000000000064000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000484e66bb550000000000000000000000000000000000000000000000000, 0000000000000020000000000000000000000000000000000000000000000000, 0000b5e620f48000000000000000000000000000000000000000000000000000, 0fff7f18f19ca711000000000000000000000000000000000000000000000000, 00000000000000000000000000000000000000002cbabd7329b84e2c0a317702, 410e7c73d0e0246d0000000000000000000000001111111254eeb25477b68fb8, 5ed929f73a960582000000000000000000000000424190072b7db5352bb91cc7, 0dabd82f547ae003000000000000000000000000000000000000000000000000, 00000000000001c0000000000000000000000000000000000000000000000000, 00000000000000c40000000000000000000000003334f5d5b3f9843df783c79f, e87cba03c59289ae0000000000000000000000005aa5f7f84ed0e5db0a4a85c3, 947ea16b53352fd4000000000000000000000000b8f275fbf7a959f4bce59999, a2ef122a099e81a8000000000000000000000000e043b6e90303ee5e2f70c90d, cb9358bdf176a4f0000000000000000000000000000000000000000000000000, 0000000000000038766961000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000026812aa3caf000000000000000000000000e37e799d5077682f, a0a244d46e5649f71457bd090000000000000000000000002170ed0880ac9a75, 5fd29b2688956bd959f933f8000000000000000000000000eeeeeeeeeeeeeeee, eeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000e37e799d5077682f, a0a244d46e5649f71457bd090000000000000000000000003334f5d5b3f9843d, f783c79fe87cba03c59289ae0000000000000000000000000000000000000000, 000000000ffec932d0a827110000000000000000000000000000000000000000, 000000007bd4a5254648c46c0000000000000000000000000000000000000000, 0000000000000000000000040000000000000000000000000000000000000000, 0000000000000000000001400000000000000000000000000000000000000000, 0000000000000000000001600000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000d90000000000000000000000000000000000000000, bb0000a500006900001a0020d6bdbf782170ed0880ac9a755fd29b2688956bd9, 59f933f802a00000000000000000000000000000000000000000000000000000, 000000000001ee63c1e501d0e226f674bbf064f54ab47f42473ff80db98cba21, 70ed0880ac9a755fd29b2688956bd959f933f84101bb4cdb9cbd36b01bd1cbae, bf2de08d9173bc095c00042e1a7d4d0000000000000000000000000000000000, 000000000000000000000000000000c0611111111254eeb25477b68fb85ed929, f73a96058200000000000000ea698b4700000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
45 |
TransparentUpgradeableProxy.0x31325fe0a1a2e6a5b1e41572156ba5b4e94f0fae7e7f63ec21e9b5ce1e4b3eab( 0x31325fe0a1a2e6a5b1e41572156ba5b4e94f0fae7e7f63ec21e9b5ce1e4b3eab, 0x000000000000000000000000e043b6e90303ee5e2f70c90dcb9358bdf176a4f0, 0x000000000000000000000000000000000000000000000000000000000000dbe0, 0x000000000000000000000000e043b6e90303ee5e2f70c90dcb9358bdf176a4f0, 52a3ac966c473f4764837a6eb9bcbe5540cd69e4e0036b46aa9dd48826fe7ebb, 0000000000000000000000003334f5d5b3f9843df783c79fe87cba03c59289ae, 00000000000000000000000000000000000000000000000010029cf951272057, 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 )
|
46 |
TransparentUpgradeableProxy.0x5a297b2c9a9f94a0f4e5a796c74ad38e219d1185fccf5f79c18726a830c2b6f5( 0x5a297b2c9a9f94a0f4e5a796c74ad38e219d1185fccf5f79c18726a830c2b6f5, 0x7669610000000000000000000000000000000000000000000000000000000000, 52a3ac966c473f4764837a6eb9bcbe5540cd69e4e0036b46aa9dd48826fe7ebb )
|
47 |
TransparentUpgradeableProxy.0x6a48ca94b4d4a8dbcf9b2eaf462748b7a696e5d1b15e1eb15ec9a0249b6e3fed( 0x6a48ca94b4d4a8dbcf9b2eaf462748b7a696e5d1b15e1eb15ec9a0249b6e3fed, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000001003d4e2c6cd0000, 000000000000000000000000000000000000000000000000000137e975a5dfa9, 0000000000000000000000000000000000000000000000000000000065d5e078, bf097fc7357777520c86ea6ad84b764ba4421e269c285bf0c9c0dd7b3970924c, 00000000000000000000000000000000000000000000000000000000000000e0, 0000000000000000000000000000000000000000000000000000000000000160, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000060, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000007b8efa83216e9a7fd17f071839b5386c7bdb2fea, 0000000000000000000000000000000000000000000000000000000000000040, 0000000000000000000000000000000000000000000000000000000000000d40, 000000000000000000000000777777773fdd8b28bb03377d10fcea75ad9768da, 000000000000000000000000f621fb08bbe51af70e7e0f4ea63496894166ff7f, 0000000000000000000000000000000000000000000000000000000000000060, 0000000000000000000000000000000000000000000000000000000000000ca4, a11b119800000000000000000000000000000000000000000000000000000000, 0000002000000000000000000000000000000000000000000000000000000000, 0000012000000000000000000000000000000000000000000000000000000000, 0000016000000000000000000000000000000000000000000000000000000000, 00000180000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead908, 3c756cc2000000000000000000000000cb28fbe3e9c0fea62e0e63ff3f232cec, fe555ad400000000000000000000000000000000000000000000000010029cf9, 5127205700000000000000000000000000000000000000000000000000000000, 00000001000000000000000000000000b8f275fbf7a959f4bce59999a2ef122a, 099e81a800000000000000000000000000000000000000000000000000000000, 000001e000000000000000000000000000000000000000000000000000000000, 00000004d0e30db0000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000200000000000000000000000000000000000000000000000000000000, 00000000000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead908, 3c756cc200000000000000000000000000000000000000000000000000000000, 00000a64ce654c17000000000000000000000000000000000000000000000000, 0000000000000020000000000000000000000000000000000000000000000000, 00016bcc41e90000000000000000000000000000000000000000000000000000, 10029cf951272057000000000000000000000000c02aaa39b223fe8d0a0e5c4f, 27ead9083c756cc20000000000000000000000003334f5d5b3f9843df783c79f, e87cba03c59289ae000000000000000000000000b8f275fbf7a959f4bce59999, a2ef122a099e81a80000000000000000000000005523985926aa12ba58dc5ad0, 0ddca99678d7227e000000000000000000000000e043b6e90303ee5e2f70c90d, cb9358bdf176a4f0000000000000000000000000000000000000000000000000, 000000000000dbe0000000000000000000000000000000000000000000000000, 0000000000000200000000000000000000000000cb28fbe3e9c0fea62e0e63ff, 3f232cecfe555ad4000000000000000000000000000000000000000000000000, 0000000000000260000000000000000000000000b8f275fbf7a959f4bce59999, a2ef122a099e81a8000000000000000000000000000000000000000000000000, 0000000000000580000000000000000000000000000000000000000000000000, 0000000000000064000000000000000000000000e043b6e90303ee5e2f70c90d, cb9358bdf176a4f0766961000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000000000000020000000000000000000000001ce4e75e2bd6bbbacde1e10d, 6813228138337e86000000000000000000000000424190072b7db5352bb91cc7, 0dabd82f547ae003000000000000000000000000000000000000000000000000, 00000000000002e41e859a050000000000000000000000000000000000000000, 0000000010029cf9512720570000000000000000000000000000000000000000, 0000000000000000000000c00000000000000000000000000000000000000000, 0000000000000000000002000000000000000000000000000000000000000000, 0000000000000000000002400000000000000000000000000000000000000000, 0000000000000000000002a00000000000000000000000002cbabd7329b84e2c, 0a317702410e7c73d0e0246d0000000000000000000000000000000000000000, 0000000000000000000000010000000000000000000000000000000000000000, 0000000000000000000000200000000000000000000000000000000000000000, 0000000000000000000000c48f6bdeaa00000000000000000000000000000000, 0000000000000000000000000000000900000000000000000000000000000000, 0000000000000000000000000000000600000000000000000000000000000000, 00000000000000001001312d0f3e205700000000000000000000000000000000, 00000000000000000feb04dca8b94f30000000000000000000000000cb28fbe3, e9c0fea62e0e63ff3f232cecfe555ad400000000000000000000000000000000, 00000000000000000000000065df161600000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000001000000000000000000000000bcc2637dfa64999f, 75abb53a7265b5b4932e40eb0000000000000000000000000000000000000000, 0000000000000000000000020000000000000000000000001ce4e75e2bd6bbba, cde1e10d6813228138337e86000000000000000000000000424190072b7db535, 2bb91cc70dabd82f547ae0030000000000000000000000000000000000000000, 0000000000000000000000010000000000000000000000000000000000000000, 0000000000000000000000640000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000484e66bb5500000000000000000000000000000000000000000, 0000000000000000000000200000000000000000000000000000000000000000, 000000000000b5e620f480000000000000000000000000000000000000000000, 000000000fff7f18f19ca7110000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000002cbabd7329b84e2c, 0a317702410e7c73d0e0246d0000000000000000000000001111111254eeb254, 77b68fb85ed929f73a960582000000000000000000000000424190072b7db535, 2bb91cc70dabd82f547ae0030000000000000000000000000000000000000000, 0000000000000000000001c00000000000000000000000000000000000000000, 0000000000000000000000c40000000000000000000000003334f5d5b3f9843d, f783c79fe87cba03c59289ae0000000000000000000000005aa5f7f84ed0e5db, 0a4a85c3947ea16b53352fd4000000000000000000000000b8f275fbf7a959f4, bce59999a2ef122a099e81a8000000000000000000000000e043b6e90303ee5e, 2f70c90dcb9358bdf176a4f00000000000000000000000000000000000000000, 0000000000000000000000387669610000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 00000000000000000000026812aa3caf000000000000000000000000e37e799d, 5077682fa0a244d46e5649f71457bd090000000000000000000000002170ed08, 80ac9a755fd29b2688956bd959f933f8000000000000000000000000eeeeeeee, eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000e37e799d, 5077682fa0a244d46e5649f71457bd090000000000000000000000003334f5d5, b3f9843df783c79fe87cba03c59289ae00000000000000000000000000000000, 00000000000000000ffec932d0a8271100000000000000000000000000000000, 00000000000000007bd4a5254648c46c00000000000000000000000000000000, 0000000000000000000000000000000400000000000000000000000000000000, 0000000000000000000000000000014000000000000000000000000000000000, 0000000000000000000000000000016000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 000000000000000000000000000000d900000000000000000000000000000000, 00000000bb0000a500006900001a0020d6bdbf782170ed0880ac9a755fd29b26, 88956bd959f933f802a000000000000000000000000000000000000000000000, 00000000000000000001ee63c1e501d0e226f674bbf064f54ab47f42473ff80d, b98cba2170ed0880ac9a755fd29b2688956bd959f933f84101bb4cdb9cbd36b0, 1bd1cbaebf2de08d9173bc095c00042e1a7d4d00000000000000000000000000, 00000000000000000000000000000000000000c0611111111254eeb25477b68f, b85ed929f73a96058200000000000000ea698b47000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x77777777...5AD9768DA | (Via Protocol: Router) | 0.038933715096158851 Eth | 0.039276665913582124 Eth | 0.000342950817423273 | |
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 6.8581313558678876 Eth | 6.86008905871739064 Eth | 0.00195770284950304 | |
0xb8f275fB...A099e81A8 | (Symbiosis Finance: Portal) | ||||
0xC02aaA39...83C756Cc2 | 3,144,180.625278408960287769 Eth | 3,144,181.778935458142864496 Eth | 1.153657049182576727 | ||
0xe043B6E9...df176A4F0 |
1.18313115 Eth
Nonce: 0
|
0.01633925258270874 Eth
Nonce: 1
| 1.16679189741729126 |
Execution Trace
ETH 1.154
TransparentUpgradeableProxy.47c59922( )
ETH 1.154
ViaRouter.execute( viaData=[{name:assetIn, type:address, order:1, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:amountIn, type:uint256, order:2, indexed:false, value:1154000000000000000, valueString:1154000000000000000}, {name:fee, type:uint256, order:3, indexed:false, value:342950817423273, valueString:342950817423273}, {name:deadline, type:uint256, order:4, indexed:false, value:1708515448, valueString:1708515448}, {name:id, type:bytes32, order:5, indexed:false, value:BF097FC7357777520C86EA6AD84B764BA4421E269C285BF0C9C0DD7B3970924C, valueString:BF097FC7357777520C86EA6AD84B764BA4421E269C285BF0C9C0DD7B3970924C}], swapData=[{name:target, type:address, order:1, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:assetOut, type:address, order:2, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:callData, type:bytes, order:3, indexed:false, value:0x, valueString:0x}], bridgeData=[{name:target, type:address, order:1, indexed:false, value:0x7b8EfA83216E9a7FD17f071839B5386c7BdB2fea, valueString:0x7b8EfA83216E9a7FD17f071839B5386c7BdB2fea}, {name:callData, type:bytes, order:2, indexed:false, value:0x000000000000000000000000777777773FDD8B28BB03377D10FCEA75AD9768DA000000000000000000000000F621FB08BBE51AF70E7E0F4EA63496894166FF7F00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000CA4A11B11980000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000180000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD400000000000000000000000000000000000000000000000010029CF9512720570000000000000000000000000000000000000000000000000000000000000001000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000001E00000000000000000000000000000000000000000000000000000000000000004D0E30DB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000000000000000000000000000000000000000000A64CE654C17000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000016BCC41E9000000000000000000000000000000000000000000000000000010029CF951272057000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A80000000000000000000000005523985926AA12BA58DC5AD00DDCA99678D7227E000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0000000000000000000000000000000000000000000000000000000000000DBE00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000000000260000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000005800000000000000000000000000000000000000000000000000000000000000064000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0766961000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000002E41E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000484E66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B47000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, valueString:0x000000000000000000000000777777773FDD8B28BB03377D10FCEA75AD9768DA000000000000000000000000F621FB08BBE51AF70E7E0F4EA63496894166FF7F00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000CA4A11B11980000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000180000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD400000000000000000000000000000000000000000000000010029CF9512720570000000000000000000000000000000000000000000000000000000000000001000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000001E00000000000000000000000000000000000000000000000000000000000000004D0E30DB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000000000000000000000000000000000000000000A64CE654C17000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000016BCC41E9000000000000000000000000000000000000000000000000000010029CF951272057000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A80000000000000000000000005523985926AA12BA58DC5AD00DDCA99678D7227E000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0000000000000000000000000000000000000000000000000000000000000DBE00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000000000260000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000005800000000000000000000000000000000000000000000000000000000000000064000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0766961000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000002E41E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000484E66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B47000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}], validatorSig=0x7DBD201D5FEE16AE857A0AD4004595940B23E1107919E0079BEF05B1223771CC0177F336ECA0B015D7CA6487D52741CD534796C221B891893065BA8263661B4A1C )
-
Null: 0x000...001.90570d1f( )
ETH 1.154
UniversalAdapter.call( assetIn=0x0000000000000000000000000000000000000000, amountIn=1153657049182576727, extraNativeValue=0, args=0x000000000000000000000000777777773FDD8B28BB03377D10FCEA75AD9768DA000000000000000000000000F621FB08BBE51AF70E7E0F4EA63496894166FF7F00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000CA4A11B11980000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000180000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD400000000000000000000000000000000000000000000000010029CF9512720570000000000000000000000000000000000000000000000000000000000000001000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000001E00000000000000000000000000000000000000000000000000000000000000004D0E30DB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000000000000000000000000000000000000000000A64CE654C17000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000016BCC41E9000000000000000000000000000000000000000000000000000010029CF951272057000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A80000000000000000000000005523985926AA12BA58DC5AD00DDCA99678D7227E000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0000000000000000000000000000000000000000000000000000000000000DBE00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000000000260000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000005800000000000000000000000000000000000000000000000000000000000000064000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0766961000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000002E41E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000484E66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B47000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 )
ETH 1.153657049182576727
MetaRouter.metaRoute( _metarouteTransaction=[{name:firstSwapCalldata, type:bytes, order:1, indexed:false, value:0xD0E30DB0, valueString:0xD0E30DB0}, {name:secondSwapCalldata, type:bytes, order:2, indexed:false, value:0x, valueString:0x}, {name:approvedTokens, type:address[], order:3, indexed:false, value:[0x0000000000000000000000000000000000000000, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], valueString:[0x0000000000000000000000000000000000000000, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2]}, {name:firstDexRouter, type:address, order:4, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:secondDexRouter, type:address, order:5, indexed:false, value:0xcB28fbE3E9C0FEA62E0E63ff3f232CECfE555aD4, valueString:0xcB28fbE3E9C0FEA62E0E63ff3f232CECfE555aD4}, {name:amount, type:uint256, order:6, indexed:false, value:1153657049182576727, valueString:1153657049182576727}, {name:nativeIn, type:bool, order:7, indexed:false, value:true, valueString:True}, {name:relayRecipient, type:address, order:8, indexed:false, value:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8, valueString:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8}, {name:otherSideCalldata, type:bytes, order:9, indexed:false, value:0xCE654C17000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000016BCC41E9000000000000000000000000000000000000000000000000000010029CF951272057000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A80000000000000000000000005523985926AA12BA58DC5AD00DDCA99678D7227E000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0000000000000000000000000000000000000000000000000000000000000DBE00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000000000260000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000005800000000000000000000000000000000000000000000000000000000000000064000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0766961000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000002E41E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000484E66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B4700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, valueString:0xCE654C17000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000016BCC41E9000000000000000000000000000000000000000000000000000010029CF951272057000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC20000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A80000000000000000000000005523985926AA12BA58DC5AD00DDCA99678D7227E000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0000000000000000000000000000000000000000000000000000000000000DBE00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000000000260000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A800000000000000000000000000000000000000000000000000000000000005800000000000000000000000000000000000000000000000000000000000000064000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F0766961000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000002E41E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000484E66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B4700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000}] )
- ETH 1.153657049182576727
WETH9.CALL( )
-
WETH9.balanceOf( 0xf621Fb08BBE51aF70e7E0F4EA63496894166Ff7F ) => ( 1153657049182576727 )
-
WETH9.allowance( 0xf621Fb08BBE51aF70e7E0F4EA63496894166Ff7F, 0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8 ) => ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 )
TransparentUpgradeableProxy.ce654c17( )
Portal.metaSynthesize( _metaSynthesizeTransaction=[{name:stableBridgingFee, type:uint256, order:1, indexed:false, value:400000000000000, valueString:400000000000000}, {name:amount, type:uint256, order:2, indexed:false, value:1153657049182576727, valueString:1153657049182576727}, {name:rtoken, type:address, order:3, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:chain2address, type:address, order:4, indexed:false, value:0x3334f5D5b3f9843df783C79FE87cbA03C59289ae, valueString:0x3334f5D5b3f9843df783C79FE87cbA03C59289ae}, {name:receiveSide, type:address, order:5, indexed:false, value:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8, valueString:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8}, {name:oppositeBridge, type:address, order:6, indexed:false, value:0x5523985926Aa12BA58DC5Ad00DDca99678D7227E, valueString:0x5523985926Aa12BA58DC5Ad00DDca99678D7227E}, {name:syntCaller, type:address, order:7, indexed:false, value:0xe043B6E90303Ee5E2F70C90DcB9358Bdf176A4F0, valueString:0xe043B6E90303Ee5E2F70C90DcB9358Bdf176A4F0}, {name:chainID, type:uint256, order:8, indexed:false, value:56288, valueString:56288}, {name:swapTokens, type:address[], order:9, indexed:false, value:[0x1CE4E75E2Bd6bbbACDE1E10D6813228138337E86, 0x424190072b7Db5352bB91cC70DabD82F547AE003], valueString:[0x1CE4E75E2Bd6bbbACDE1E10D6813228138337E86, 0x424190072b7Db5352bB91cC70DabD82F547AE003]}, {name:secondDexRouter, type:address, order:10, indexed:false, value:0xcB28fbE3E9C0FEA62E0E63ff3f232CECfE555aD4, valueString:0xcB28fbE3E9C0FEA62E0E63ff3f232CECfE555aD4}, {name:secondSwapCalldata, type:bytes, order:11, indexed:false, value:0x1E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064, valueString:0x1E859A0500000000000000000000000000000000000000000000000010029CF95127205700000000000000000000000000000000000000000000000000000000000000C00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002A00000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000C48F6BDEAA000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000001001312D0F3E20570000000000000000000000000000000000000000000000000FEB04DCA8B94F30000000000000000000000000CB28FBE3E9C0FEA62E0E63FF3F232CECFE555AD40000000000000000000000000000000000000000000000000000000065DF1616000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000BCC2637DFA64999F75ABB53A7265B5B4932E40EB00000000000000000000000000000000000000000000000000000000000000020000000000000000000000001CE4E75E2BD6BBBACDE1E10D6813228138337E86000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000064}, {name:finalReceiveSide, type:address, order:12, indexed:false, value:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8, valueString:0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8}, {name:finalCalldata, type:bytes, order:13, indexed:false, value:0xE66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B47000000000000000000000000000000000000000000000000, valueString:0xE66BB55000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000B5E620F480000000000000000000000000000000000000000000000000000FFF7F18F19CA71100000000000000000000000000000000000000000000000000000000000000000000000000000000000000002CBABD7329B84E2C0A317702410E7C73D0E0246D0000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000424190072B7DB5352BB91CC70DABD82F547AE00300000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000000C40000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000005AA5F7F84ED0E5DB0A4A85C3947EA16B53352FD4000000000000000000000000B8F275FBF7A959F4BCE59999A2EF122A099E81A8000000000000000000000000E043B6E90303EE5E2F70C90DCB9358BDF176A4F000000000000000000000000000000000000000000000000000000000000000387669610000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000026812AA3CAF000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000002170ED0880AC9A755FD29B2688956BD959F933F8000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE000000000000000000000000E37E799D5077682FA0A244D46E5649F71457BD090000000000000000000000003334F5D5B3F9843DF783C79FE87CBA03C59289AE0000000000000000000000000000000000000000000000000FFEC932D0A827110000000000000000000000000000000000000000000000007BD4A5254648C46C000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000160000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D90000000000000000000000000000000000000000BB0000A500006900001A0020D6BDBF782170ED0880AC9A755FD29B2688956BD959F933F802A00000000000000000000000000000000000000000000000000000000000000001EE63C1E501D0E226F674BBF064F54AB47F42473FF80DB98CBA2170ED0880AC9A755FD29B2688956BD959F933F84101BB4CDB9CBD36B01BD1CBAEBF2DE08D9173BC095C00042E1A7D4D0000000000000000000000000000000000000000000000000000000000000000C0611111111254EEB25477B68FB85ED929F73A96058200000000000000EA698B47000000000000000000000000000000000000000000000000}, {name:finalOffset, type:uint256, order:14, indexed:false, value:100, valueString:100}, {name:revertableAddress, type:address, order:15, indexed:false, value:0xe043B6E90303Ee5E2F70C90DcB9358Bdf176A4F0, valueString:0xe043B6E90303Ee5E2F70C90DcB9358Bdf176A4F0}, {name:clientID, type:bytes32, order:16, indexed:false, value:7669610000000000000000000000000000000000000000000000000000000000, valueString:7669610000000000000000000000000000000000000000000000000000000000}] ) => ( 52A3AC966C473F4764837A6EB9BCBE5540CD69E4E0036B46AA9DD48826FE7EBB )
-
WETH9.transferFrom( src=0xf621Fb08BBE51aF70e7E0F4EA63496894166Ff7F, dst=0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8, wad=1153657049182576727 ) => ( True )
-
TransparentUpgradeableProxy.6cebc9c2( )
-
- ETH 1.153657049182576727
-
File 1 of 8: TransparentUpgradeableProxy
File 2 of 8: WETH9
File 3 of 8: MetaRouter
File 4 of 8: TransparentUpgradeableProxy
File 5 of 8: TransparentUpgradeableProxy
File 6 of 8: ViaRouter
File 7 of 8: UniversalAdapter
File 8 of 8: Portal
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializing the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { 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 This is a virtual function that should be overridden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overridden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } }
File 2 of 8: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub // 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.18; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } 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) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */
File 3 of 8: MetaRouter
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: GPL-3.0 // uni -> stable -> uni scheme pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./MetaRouteStructs.sol"; import "./MetaRouterGateway.sol"; import "../../utils/RevertMessageParser.sol"; /** * @title MetaRouterV3 * @notice Users must give approve on their tokens to `MetaRoutetGateway` contract, * not to `MetaRouter` contract. */ contract MetaRouter is Context { MetaRouterGateway public immutable metaRouterGateway; event TransitTokenSent( address to, uint256 amount, address token ); constructor() { metaRouterGateway = new MetaRouterGateway(address(this)); } /** * @notice Method that starts the Meta Routing * @dev external + internal swap for burn scheme, only external for synth scheme * @dev calls the next method on the other side * @param _metarouteTransaction metaRoute offchain transaction data */ function metaRoute( MetaRouteStructs.MetaRouteTransaction calldata _metarouteTransaction ) external payable { uint256 approvedTokensLength = _metarouteTransaction.approvedTokens.length; if (!_metarouteTransaction.nativeIn) { metaRouterGateway.claimTokens( _metarouteTransaction.approvedTokens[0], _msgSender(), _metarouteTransaction.amount ); } uint256 secondSwapAmountIn = _metarouteTransaction.amount; if (_metarouteTransaction.firstSwapCalldata.length != 0) { if (!_metarouteTransaction.nativeIn) { _lazyApprove( _metarouteTransaction.approvedTokens[0], _metarouteTransaction.firstDexRouter, _metarouteTransaction.amount ); } require( _metarouteTransaction.firstDexRouter != address(metaRouterGateway), "MetaRouter: invalid first router" ); { uint256 size; address toCheck = _metarouteTransaction.firstDexRouter; assembly { size := extcodesize(toCheck) } require(size != 0, "MetaRouter: call for a non-contract account"); } (bool firstSwapSuccess, bytes memory swapData) = _metarouteTransaction.firstDexRouter.call{value: msg.value}( _metarouteTransaction.firstSwapCalldata ); if (!firstSwapSuccess) { revert(RevertMessageParser.getRevertMessage(swapData, "MetaRouter: first swap failed")); } secondSwapAmountIn = IERC20(_metarouteTransaction.approvedTokens[1]).balanceOf(address(this)); } uint256 finalSwapAmountIn = secondSwapAmountIn; if (_metarouteTransaction.secondSwapCalldata.length != 0) { bytes memory secondSwapCalldata = _metarouteTransaction.secondSwapCalldata; assembly { mstore(add(secondSwapCalldata, 36), secondSwapAmountIn) } _lazyApprove( _metarouteTransaction.approvedTokens[approvedTokensLength - 2], _metarouteTransaction.secondDexRouter, secondSwapAmountIn ); require( _metarouteTransaction.secondDexRouter != address(metaRouterGateway), "MetaRouter: invalid second router" ); { uint256 size; address toCheck = _metarouteTransaction.secondDexRouter; assembly { size := extcodesize(toCheck) } require(size != 0, "MetaRouter: call for a non-contract account"); } (bool secondSwapSuccess, bytes memory swapData) = _metarouteTransaction.secondDexRouter.call(secondSwapCalldata); if (!secondSwapSuccess) { revert(RevertMessageParser.getRevertMessage(swapData, "MetaRouter: second swap failed")); } finalSwapAmountIn = IERC20( _metarouteTransaction.approvedTokens[approvedTokensLength - 1] ).balanceOf(address(this)); } _lazyApprove( _metarouteTransaction.approvedTokens[approvedTokensLength - 1], _metarouteTransaction.relayRecipient, finalSwapAmountIn ); bytes memory otherSideCalldata = _metarouteTransaction.otherSideCalldata; assembly { mstore(add(otherSideCalldata, 100), finalSwapAmountIn) } require( _metarouteTransaction.relayRecipient != address(metaRouterGateway), "MetaRouter: invalid recipient" ); { uint256 size; address toCheck = _metarouteTransaction.relayRecipient; assembly { size := extcodesize(toCheck) } require(size != 0, "MetaRouter: call for a non-contract account"); } (bool otherSideCallSuccess, bytes memory data) = _metarouteTransaction.relayRecipient.call(otherSideCalldata); if (!otherSideCallSuccess) { revert(RevertMessageParser.getRevertMessage(data, "MetaRouter: other side call failed")); } } /** * @notice Implements an external call on some contract * @dev called by Portal in metaUnsynthesize() method * @param _token address of token * @param _amount amount of _token * @param _receiveSide contract on which call will take place * @param _calldata encoded method to call * @param _offset shift to patch the amount to calldata */ function externalCall( address _token, uint256 _amount, address _receiveSide, bytes calldata _calldata, uint256 _offset, address _to ) external { (bool success,) = _externalCall(_token, _amount, _receiveSide, _calldata, _offset); if (!success) { TransferHelper.safeTransfer( _token, _to, _amount ); emit TransitTokenSent(_to, _amount, _token); } } function returnSwap( address _token, uint256 _amount, address _router, bytes calldata _swapCalldata, address _burnToken, address _synthesis, bytes calldata _burnCalldata ) external { (bool success, bytes memory data) = _externalCall(_token, _amount, _router, _swapCalldata, 36); if (!success) { revert(RevertMessageParser.getRevertMessage(data, "MetaRouterV2: internal swap failed")); } uint256 internalSwapAmountOut = IERC20(_burnToken).balanceOf(address(this)); bytes memory burnCalldata = _burnCalldata; assembly { mstore(add(burnCalldata, 100), internalSwapAmountOut) } require( _synthesis != address(metaRouterGateway), "MetaRouterV2: invalid recipient" ); { uint256 size; address toCheck = _synthesis; assembly { size := extcodesize(toCheck) } require(size != 0, "MetaRouter: call for a non-contract account"); } (bool otherSideCallSuccess, bytes memory burnData) = _synthesis.call(burnCalldata); if (!otherSideCallSuccess) { revert(RevertMessageParser.getRevertMessage(burnData, "MetaRouterV2: revertSynthesizeRequest call failed")); } } /** * @notice Implements an internal swap on stable router and final method call * @dev called by Synthesis in metaMint() method * @param _metaMintTransaction metaMint offchain transaction data */ function metaMintSwap( MetaRouteStructs.MetaMintTransaction calldata _metaMintTransaction ) external { address finalCallToken = _metaMintTransaction.swapTokens[0]; if (_metaMintTransaction.secondSwapCalldata.length != 0) { // internal swap (bool internalSwapSuccess, bytes memory internalSwapData) = _externalCall( _metaMintTransaction.swapTokens[0], _metaMintTransaction.amount, _metaMintTransaction.secondDexRouter, _metaMintTransaction.secondSwapCalldata, 36 ); if (!internalSwapSuccess) { revert(RevertMessageParser.getRevertMessage(internalSwapData, "MetaRouter: internal swap failed")); } finalCallToken = _metaMintTransaction.swapTokens[1]; } if (_metaMintTransaction.finalCalldata.length != 0) { // patch crossChainID bytes32 crossChainID = _metaMintTransaction.crossChainID; bytes memory calldata_ = _metaMintTransaction.finalCalldata; assembly { mstore(add(calldata_, 132), crossChainID) } uint256 finalAmountIn = IERC20(finalCallToken).balanceOf(address(this)); // external call (bool finalSuccess, bytes memory finalData) = _externalCall( finalCallToken, finalAmountIn, _metaMintTransaction.finalReceiveSide, calldata_, _metaMintTransaction.finalOffset ); if (!finalSuccess) { revert(RevertMessageParser.getRevertMessage(finalData, "MetaRouter: final call failed")); } } uint256 amountOut = IERC20(_metaMintTransaction.swapTokens[_metaMintTransaction.swapTokens.length - 1]).balanceOf(address(this)); if (amountOut != 0) { TransferHelper.safeTransfer( _metaMintTransaction.swapTokens[_metaMintTransaction.swapTokens.length - 1], _metaMintTransaction.to, amountOut ); } } /** * @notice Implements call of some operation with token * @dev Internal function used in metaMintSwap() and externalCall() * @param _token token address * @param _amount amount of _token * @param _receiveSide address of contract on which method will be called * @param _calldata encoded method call * @param _offset shift to patch the _amount to calldata */ function _externalCall( address _token, uint256 _amount, address _receiveSide, bytes memory _calldata, uint256 _offset ) internal returns (bool success, bytes memory data) { require(_receiveSide != address(metaRouterGateway), "MetaRouter: invalid receiveSide"); _lazyApprove(_token, _receiveSide, _amount); assembly { mstore(add(_calldata, _offset), _amount) } { uint256 size; address toCheck = _receiveSide; assembly { size := extcodesize(toCheck) } require(size != 0, "MetaRouter: call for a non-contract account"); } (success, data) = _receiveSide.call(_calldata); } /** * @notice Implements approve * @dev Internal function used to approve the token spending * @param _token token address * @param _to address to approve * @param _amount amount for which approve will be given */ function _lazyApprove(address _token, address _to, uint256 _amount) internal { if (IERC20(_token).allowance(address(this), _to) < _amount) { TransferHelper.safeApprove(_token, _to, type(uint256).max); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * @title MetaRouterGateway * @notice During the `metaRoute` transaction `MetaRouter` (only) claims user's tokens * from `MetaRoutetGateway` contract and then operates with them. */ contract MetaRouterGateway { address public immutable metaRouter; modifier onlyMetarouter() { require(metaRouter == msg.sender, "Symb: caller is not the metarouter"); _; } constructor(address _metaRouter) { metaRouter = _metaRouter; } function claimTokens( address _token, address _from, uint256 _amount ) external onlyMetarouter { TransferHelper.safeTransferFrom(_token, _from, metaRouter, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library MetaRouteStructs { struct MetaBurnTransaction { uint256 stableBridgingFee; uint256 amount; bytes32 crossChainID; address syntCaller; address finalReceiveSide; address sToken; bytes finalCallData; uint256 finalOffset; address chain2address; address receiveSide; address oppositeBridge; address revertableAddress; uint256 chainID; bytes32 clientID; } struct MetaMintTransaction { uint256 stableBridgingFee; uint256 amount; bytes32 crossChainID; bytes32 externalID; address tokenReal; uint256 chainID; address to; address[] swapTokens; address secondDexRouter; bytes secondSwapCalldata; address finalReceiveSide; bytes finalCalldata; uint256 finalOffset; } struct MetaRouteTransaction { bytes firstSwapCalldata; bytes secondSwapCalldata; address[] approvedTokens; address firstDexRouter; address secondDexRouter; uint256 amount; bool nativeIn; address relayRecipient; bytes otherSideCalldata; } struct MetaSynthesizeTransaction { uint256 stableBridgingFee; uint256 amount; address rtoken; address chain2address; address receiveSide; address oppositeBridge; address syntCaller; uint256 chainID; address[] swapTokens; address secondDexRouter; bytes secondSwapCalldata; address finalReceiveSide; bytes finalCalldata; uint256 finalOffset; address revertableAddress; bytes32 clientID; } struct MetaRevertTransaction { uint256 stableBridgingFee; bytes32 internalID; address receiveSide; address managerChainBridge; address sourceChainBridge; uint256 managerChainId; uint256 sourceChainId; address router; bytes swapCalldata; address sourceChainSynthesis; address burnToken; bytes burnCalldata; bytes32 clientID; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library RevertMessageParser { function getRevertMessage(bytes memory _data, string memory _defaultMessage) internal pure returns (string memory) { // If the _data length is less than 68, then the transaction failed silently (without a revert message) if (_data.length < 68) return _defaultMessage; assembly { // Slice the sighash _data := add(_data, 0x04) } return abi.decode(_data, (string)); } }
File 4 of 8: TransparentUpgradeableProxy
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins. contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly 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 This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol"; abstract contract Proxiable is UUPSUpgradeable { function _authorizeUpgrade(address newImplementation) internal override { _beforeUpgrade(newImplementation); } function _beforeUpgrade(address newImplementation) internal virtual; } contract ChildOfProxiable is Proxiable { function _beforeUpgrade(address newImplementation) internal virtual override {} }
File 5 of 8: TransparentUpgradeableProxy
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins. contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly 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 This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol"; abstract contract Proxiable is UUPSUpgradeable { function _authorizeUpgrade(address newImplementation) internal override { _beforeUpgrade(newImplementation); } function _beforeUpgrade(address newImplementation) internal virtual; } contract ChildOfProxiable is Proxiable { function _beforeUpgrade(address newImplementation) internal virtual override {} }
File 6 of 8: ViaRouter
// SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/IAcross.sol"; contract AcrossAdapter is AdapterBase { struct AcrossArgs { address recipient; uint256 destinationChainId; uint64 relayerFeePct; uint32 quoteTimestamp; } /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { AcrossArgs memory acrossArgs = abi.decode(args, (AcrossArgs)); IAcross(target).deposit{value: (tokenIn == address(0)) ? amountIn : 0}( acrossArgs.recipient, tokenIn, amountIn, acrossArgs.destinationChainId, acrossArgs.relayerFeePct, acrossArgs.quoteTimestamp ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "../interfaces/IAdapter.sol"; import "../libraries/Transfers.sol"; import "../libraries/Errors.sol"; abstract contract AdapterBase is IAdapter { /// @notice Target contract for this adapter address public immutable target; /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) { require(target_ != address(0), Errors.ZERO_ADDRESS); target = target_; } /// @notice Approves incoming token to target and executes call /// @param tokenIn Incoming token /// @param amountIn Incoming amount /// @param args Encoded additional arguments for current adapter function call( address tokenIn, uint256 amountIn, uint256, bytes memory args ) external payable virtual override { Transfers.approve(tokenIn, target, amountIn); _executeCall(tokenIn, amountIn, args); } /// @notice Executes target call with given params /// @param tokenIn Incoming token /// @param amountIn Incoming amount /// @param args Encoded additional arguments for current adapter function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IAcross { function deposit( address recipient, address originToken, uint256 amount, uint256 destinationChainId, uint64 relayerFeePct, uint32 quoteTimestamp ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IAdapter { /// @notice Executes call with given params /// @param assetIn Incoming asset /// @param amountIn Incoming amount /// @param nativeExtraValue Extra value of native token that can be used by call /// @param args Encoded additional arguments for current adapter function call( address assetIn, uint256 amountIn, uint256 nativeExtraValue, bytes memory args ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Errors.sol"; library Transfers { using SafeERC20 for IERC20; using Address for address payable; /// @notice Transfers (or checks sent value) given asset from sender to running contract /// @param asset Asset to transfer (address(0) to check native sent value) /// @param amount Amount to transfer /// @return extraValue Extra amount of native token passed function transferIn(address asset, uint256 amount) internal returns (uint256 extraValue) { if (isNative(asset)) { require(msg.value >= amount, Errors.INVALID_MESSAGE_VALUE); return msg.value - amount; } else { uint256 balanceBefore = IERC20(asset).balanceOf(address(this)); IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); require( IERC20(asset).balanceOf(address(this)) - balanceBefore == amount, Errors.INVALID_RECEIVED_AMOUNT ); return msg.value; } } /// @notice Transfers given token from running contract to given address /// @param asset Asset to transfer (address(0) to transfer native token) /// @param to Address to transfer to /// @param amount Amount to transfer function transferOut( address asset, address to, uint256 amount ) internal { if (isNative(asset)) { payable(to).sendValue(amount); } else { IERC20(asset).safeTransfer(to, amount); } } /// @notice Approves given token to given spender (with checks for address(0) as native) /// @param asset Token to approve /// @param spender Spender address /// @param amount Amount to approve function approve( address asset, address spender, uint256 amount ) internal { if (isNative(asset)) { return; } uint256 allowance = IERC20(asset).allowance(address(this), spender); if (allowance > 0) { // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 IERC20(asset).safeApprove(spender, 0); } IERC20(asset).safeIncreaseAllowance(spender, amount); } /// @notice Gets balance of given token /// @param asset Token to get balance of (address(0) for native token) function getBalance(address asset) internal view returns (uint256) { if (isNative(asset)) { return address(this).balance; } else { return IERC20(asset).balanceOf(address(this)); } } function isNative(address asset) internal pure returns (bool) { return asset == address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; library Errors { // ViaRouter string internal constant INSUFFICIENT_COLLECTED_FEES = "ICF"; string internal constant EMPTY_EXECUTION = "EE"; string internal constant DEADLINE_HAS_PASSED = "DHP"; string internal constant DOUBLE_EXECUTION = "DE"; string internal constant NOT_SIGNED_BY_VALIDATOR = "NSV"; string internal constant NOT_AN_ADAPTER = "NAA"; string internal constant INVALID_SPLIT = "ISP"; string internal constant ID_MISMATCH = "IMM"; // Transfers string internal constant INVALID_MESSAGE_VALUE = "IMV"; string internal constant INVALID_RECEIVED_AMOUNT = "IRA"; // Adapters string internal constant INVALID_INCOMING_TOKEN = "IIT"; // Gasless Relay string internal constant NONCE_ALREADY_USED = "NAU"; string internal constant INVALID_ROUTER_SELECTOR = "IRS"; string internal constant INVALID_PERMIT_SELECTOR = "IPS"; string internal constant INVALID_NONCE = "IN"; // Generic string internal constant ZERO_ADDRESS = "ZA"; string internal constant INVALID_TARGET = "IVT"; string internal constant LENGHTS_MISMATCH = "LMM"; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./AdapterBase.sol"; import "../libraries/Errors.sol"; import "../interfaces/external/IXSwapper.sol"; contract XYAdapter is AdapterBase { /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct XArgs { IXSwapper.SwapDescription swapDesc; bytes aggregatorData; IXSwapper.ToChainDescription toChainDesc; } /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { XArgs memory xArgs = abi.decode(args, (XArgs)); require( xArgs.swapDesc.fromToken == tokenIn, Errors.INVALID_INCOMING_TOKEN ); xArgs.swapDesc.amount = amountIn; IXSwapper(target).swap( xArgs.swapDesc, xArgs.aggregatorData, xArgs.toChainDesc ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IXSwapper { struct SwapDescription { address fromToken; address toToken; address receiver; uint256 amount; uint256 minReturnAmount; } // Info of an expecting swap on target chain of a swap request struct ToChainDescription { uint32 toChainId; address toChainToken; uint256 expectedToChainTokenAmount; uint32 slippage; } /// @notice This functions is called by user to initiate a swap. User swaps his/her token for YPool token on this chain and provide info for the swap on target chain. A swap request will be created for each swap. /// @dev swapDesc is the swap info for swapping on DEX on this chain, not the swap request /// @param swapDesc Description of the swap on DEX, see IAggregator.SwapDescription /// @param aggregatorData Raw data consists of instructions to swap user's token for YPool token /// @param toChainDesc Description of the swap on target chain, see ToChainDescription function swap( SwapDescription memory swapDesc, bytes memory aggregatorData, ToChainDescription calldata toChainDesc ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./libraries/Errors.sol"; import "./libraries/Transfers.sol"; import "./interfaces/IViaRouter.sol"; import "./interfaces/external/IAllowanceTransfer.sol"; contract GaslessRelay is Ownable, EIP712 { using SafeERC20 for IERC20; using Address for address; using SafeCast for uint256; // CONSTANTS /// @notice EIP712 typehash used for transfers bytes32 public constant TRANSFER_CALL_TYPEHASH = keccak256( "TransferCall(address token,address to,uint256 amount,uint256 fee,uint256 nonce)" ); /// @notice EIP712 typehash used for executions bytes32 public constant EXECUTION_CALL_TYPEHASH = keccak256( "ExecutionCall(address token,uint256 amount,address quoter,bytes quoteData,uint256 fee,bytes executionData,uint256 value)" ); /// @notice EIP712 typehash used for batch calls bytes32 public constant BATCH_CALL_TYPEHASH = keccak256( "BatchCall(TransferCall[] transferCalls,ExecutionCall[] executionCalls)ExecutionCall(address token,uint256 amount,address quoter,bytes quoteData,uint256 fee,bytes executionData,uint256 value)TransferCall(address token,address to,uint256 amount,uint256 fee,uint256 nonce)" ); // STORAGE /// @notice Address of ViaRouter contract address public immutable router; /// @notice Address of Permit2 contract address public immutable permit2; /// @notice Mapping of transfer nonces for accounts to them being used mapping(address => mapping(uint256 => bool)) public nonceUsed; /// @notice Mapping of addresses to their allowed permit selector mapping(address => bytes4) public permitSelectors; /// @notice Structure describing transfer call /// @param token Token to transfer /// @param to Address to transfer to /// @param amount Amount to transfer /// @param fee Fee to collect (on top of amount) /// @param nonce Transfer's nonce (to avoid double-spending) struct TransferCall { address token; address to; uint256 amount; uint256 fee; uint256 nonce; } /// @notice Structure describing execution call /// @param token Token to transfer /// @param amount Amount to transfer /// @param quoter Address of the contract used to quote incoming amount /// @param quoteData Calldata used for quote /// @param fee Fee to collect (on top of amount) /// @param executionData Calldata for ViaRouter /// @param value Value to transfer struct ExecutionCall { address token; uint256 amount; address quoter; bytes quoteData; uint256 fee; bytes executionData; uint256 value; } // EVENTS /// @notice Event emitted when gasless transfer is performed event Transfer(address from, TransferCall call); /// @notice Event emitted when gasless execution is performed event Execution(address from, ExecutionCall call); /// @notice Event emitted when funds are withdrawn from contract event Withdrawn(IERC20 token, address to, uint256 amount); /// @notice Event emitted when permit selector is set for some token event PermitSelectorSet(address token, bytes4 selector); // CONSTRUCTOR /// @notice Contract constructor /// @param router_ Address of ViaRouter contract /// @param permit2_ Address of Permit2 contract constructor(address router_, address permit2_) EIP712("Transfer Money", "1.0.0") { router = router_; permit2 = permit2_; } // PUBLIC FUNCTIONS /// @notice Function used to perform transfer /// @param call TransferCall struct /// @param usePermit2 Use Permit2 for transfer /// @param sig EIP712 signature by `from` account /// @param permit Off-chain permit calldata for given token function transfer( TransferCall calldata call, bool usePermit2, bytes calldata sig, bytes calldata permit ) public { // Determine sender address from = msg.sender; if (sig.length > 0) { bytes32 digest = _hashTypedDataV4(_hashTransferCall(call)); from = ECDSA.recover(digest, sig); } // Execute permit if required if (permit.length > 0) { _permit(call.token, permit, usePermit2); } // Execute transfer _transfer(from, call, usePermit2); } /// @notice Function used to perform execution /// @param call ExecutionCall struct /// @param usePermit2 Use Permit2 for transfer /// @param sig EIP712 signature by `from` account function execute( ExecutionCall calldata call, bool usePermit2, bytes calldata sig, bytes calldata permit ) public payable { // Determine sender address from = msg.sender; if (sig.length > 0) { bytes32 digest = _hashTypedDataV4(_hashExecutionCall(call)); from = ECDSA.recover(digest, sig); } // Check for value require(msg.value == call.value, Errors.INVALID_MESSAGE_VALUE); // Execute permit if required if (permit.length != 0) { _permit(call.token, permit, usePermit2); } // Execute request _execute(from, call, usePermit2); } /// @notice Function to call a batch of transfers and executions /// @param transferCalls Array of transfer calls /// @param executionCalls Array of execution calls /// @param sig EIP712 signature of call by `from` account /// @param permitTokens List of tokens to execute permits on /// @param permits Permits to execute function batchCall( TransferCall[] calldata transferCalls, ExecutionCall[] calldata executionCalls, bytes calldata sig, address[] calldata permitTokens, bytes[] calldata permits ) external payable { // Determine sender address from = msg.sender; if (sig.length > 0) { bytes32 digest = _hashTypedDataV4( _hashBatchCall(transferCalls, executionCalls) ); from = ECDSA.recover(digest, sig); } // Check total value uint256 totalValue; for (uint256 i = 0; i < executionCalls.length; i++) { totalValue += executionCalls[i].value; } require(totalValue == msg.value, Errors.INVALID_MESSAGE_VALUE); // Check that nonce sequence is valid (only 0th should be checked) require( transferCalls[0].nonce != type(uint256).max, Errors.INVALID_NONCE ); for (uint256 i = 1; i < transferCalls.length; i++) { require( transferCalls[i].nonce == type(uint256).max, Errors.INVALID_NONCE ); } // Check permits lenghts match require(permitTokens.length == permits.length, Errors.LENGHTS_MISMATCH); // Execute permits for (uint256 i = 0; i < permitTokens.length; i++) { _permit(permitTokens[i], permits[i], false); } // Process transfer calls for (uint256 i = 0; i < transferCalls.length; i++) { _transfer(from, transferCalls[i], false); } // Process executions calls for (uint256 i = 0; i < executionCalls.length; i++) { _execute(from, executionCalls[i], false); } } // RESTRICTED FUNCTIONS /// @notice Owner's function to withdraw collected fees /// @param token Token to transfer /// @param to Address to transfer to /// @param amount Amount to transfer function withdraw( IERC20 token, address to, uint256 amount ) external onlyOwner { token.safeTransfer(to, amount); emit Withdrawn(token, to, amount); } /// @notice Owner's function to set permit selector for some tokens /// @param tokens List of tokens to set selectors for /// @param selectors List of permit selectors for respective tokens function setPermitSelectors( address[] calldata tokens, bytes4[] calldata selectors ) external onlyOwner { require(tokens.length == selectors.length, Errors.LENGHTS_MISMATCH); for (uint256 i = 0; i < tokens.length; i++) { _setPermitSelector(tokens[i], selectors[i]); } } // INTERNAL FUNCTIONS /// @notice Function used to perform gasless transfer /// @param from Address to transfer from /// @param call TransferCall struct /// @param usePermit2 Use Permit2 contract for transfer function _transfer( address from, TransferCall calldata call, bool usePermit2 ) private { if (call.nonce != type(uint256).max) { // Check that nonce was not used yet require(!nonceUsed[from][call.nonce], Errors.NONCE_ALREADY_USED); // Mark nonce as used nonceUsed[from][call.nonce] = true; } // Transfer amount and fee if (usePermit2) { IAllowanceTransfer(permit2).transferFrom( from, call.to, call.amount.toUint160(), call.token ); if (call.fee > 0) { IAllowanceTransfer(permit2).transferFrom( from, address(this), call.fee.toUint160(), call.token ); } } else { IERC20(call.token).safeTransferFrom(from, call.to, call.amount); if (call.fee > 0) { IERC20(call.token).safeTransferFrom( from, address(this), call.fee ); } } // Emit event emit Transfer(from, call); } /// @notice Function used to perform gasless transfer /// @param from Address to transfer from /// @param call ExecutionCall struct /// @param usePermit2 Use Permit2 for transfer function _execute( address from, ExecutionCall calldata call, bool usePermit2 ) private { // Check that execution selector is correct bytes4 selector = bytes4(call.executionData); require( selector == IViaRouter.execute.selector || selector == IViaRouter.executeNew.selector, Errors.INVALID_ROUTER_SELECTOR ); // Detemite amount (through quoter if required) and execution data uint256 amount = call.amount; if (call.quoter != address(0)) { bytes memory response = call.quoter.functionStaticCall( call.quoteData ); (amount) = abi.decode(response, (uint256)); } // Transfer amount and fee to relay contract if (usePermit2) { IAllowanceTransfer(permit2).transferFrom( from, address(this), (amount + call.fee).toUint160(), call.token ); } else { IERC20(call.token).safeTransferFrom( from, address(this), amount + call.fee ); } // Approve router for spending Transfers.approve(call.token, router, amount); // Execute router call router.functionCallWithValue(call.executionData, call.value); // Emit event emit Execution(from, call); } /// @notice Internal function to set permit selector for some token /// @param token Address of the token /// @param selector Permit function selector function _setPermitSelector(address token, bytes4 selector) private { permitSelectors[token] = selector; emit PermitSelectorSet(token, selector); } // INTERNAL VIEW FUNCTIONS function _hashTransferCall(TransferCall calldata transferCall) private pure returns (bytes32) { return keccak256( abi.encode( TRANSFER_CALL_TYPEHASH, transferCall.token, transferCall.to, transferCall.amount, transferCall.fee, transferCall.nonce ) ); } function _hashExecutionCall(ExecutionCall calldata executionCall) private pure returns (bytes32) { return keccak256( abi.encode( EXECUTION_CALL_TYPEHASH, executionCall.token, executionCall.amount, executionCall.quoter, keccak256(executionCall.quoteData), executionCall.fee, keccak256(executionCall.executionData), executionCall.value ) ); } /// @notice Internal function that hashes batch call according to EIP712 /// @param transferCalls Array of transfer calls /// @param executionCalls Array of execution calls function _hashBatchCall( TransferCall[] calldata transferCalls, ExecutionCall[] calldata executionCalls ) private pure returns (bytes32) { // Hash transfer calls bytes32[] memory transferCallHashes = new bytes32[]( transferCalls.length ); for (uint256 i = 0; i < transferCalls.length; i++) { transferCallHashes[i] = _hashTransferCall(transferCalls[i]); } // Hash execution calls bytes32[] memory executionCallHashes = new bytes32[]( executionCalls.length ); for (uint256 i = 0; i < executionCalls.length; i++) { executionCallHashes[i] = _hashExecutionCall(executionCalls[i]); } // Hash batch return keccak256( abi.encode( BATCH_CALL_TYPEHASH, keccak256(abi.encodePacked(transferCallHashes)), keccak256(abi.encodePacked(executionCallHashes)) ) ); } /// @notice Internal function that executes permit on given token, checking for selector /// @param token Address of the token to permit on /// @param permit Permit calldata /// @param usePermit2 Use Permit2 contract function _permit( address token, bytes calldata permit, bool usePermit2 ) private { address target; if (usePermit2) { require( IAllowanceTransfer.permit.selector == bytes4(permit), Errors.INVALID_PERMIT_SELECTOR ); target = permit2; } else { require( permitSelectors[token] == bytes4(permit), Errors.INVALID_PERMIT_SELECTOR ); target = token; } target.functionCall(permit); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248) { require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits"); return int248(value); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240) { require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits"); return int240(value); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232) { require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits"); return int232(value); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224) { require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits"); return int224(value); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216) { require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits"); return int216(value); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208) { require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits"); return int208(value); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200) { require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits"); return int200(value); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192) { require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits"); return int192(value); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184) { require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits"); return int184(value); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176) { require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits"); return int176(value); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168) { require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits"); return int168(value); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160) { require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits"); return int160(value); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152) { require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits"); return int152(value); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144) { require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits"); return int144(value); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136) { require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits"); return int136(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120) { require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits"); return int120(value); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112) { require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits"); return int112(value); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104) { require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits"); return int104(value); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96) { require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits"); return int96(value); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88) { require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits"); return int88(value); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80) { require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits"); return int80(value); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72) { require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits"); return int72(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56) { require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits"); return int56(value); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48) { require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits"); return int48(value); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40) { require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits"); return int40(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24) { require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits"); return int24(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IViaRouter { // STRUCTS struct ViaData { address assetIn; uint256 amountIn; uint256 fee; uint256 deadline; bytes32 id; } struct SwapData { address target; address assetOut; bytes callData; } enum SwapType { None, ExactIn, ExactOut } struct NewSwapData { SwapType swapType; address target; address assetOut; bytes callData; address quoter; bytes quoteData; } struct BridgeData { address target; bytes callData; } // FUNCTIONS function execute( ViaData calldata viaData, SwapData calldata swapData, BridgeData calldata bridgeData, bytes calldata validatorSig ) external payable; function executeNew( ViaData calldata viaData, NewSwapData memory swapData, BridgeData calldata bridgeData, bytes calldata validatorSig ) external payable; function executeBatch( ViaData[] calldata viaDatas, NewSwapData[] calldata swapDatas, BridgeData[] calldata bridgeDatas, uint256[] calldata extraNativeValues, bytes calldata validatorSig ) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title AllowanceTransfer /// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts /// @dev Requires user's token approval on the Permit2 contract interface IAllowanceTransfer { /// @notice The permit data for a token struct PermitDetails { // ERC20 token address address token; // the maximum amount allowed to spend uint160 amount; // timestamp at which a spender's token allowances become invalid uint48 expiration; // an incrementing value indexed per owner,token,and spender for each signature uint48 nonce; } /// @notice The permit message signed for a single token allownce struct PermitSingle { // the permit data for a single token alownce PermitDetails details; // address permissioned on the allowed tokens address spender; // deadline on the permit signature uint256 sigDeadline; } /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce /// @param owner The owner of the tokens being approved /// @param permitSingle Data signed over by the owner specifying the terms of approval /// @param signature The owner's signature over the permit data function permit( address owner, PermitSingle memory permitSingle, bytes calldata signature ) external; /// @notice Transfer approved tokens from one address to another /// @param from The address to transfer from /// @param to The address of the recipient /// @param amount The amount of the token to transfer /// @param token The token address to transfer /// @dev Requires the from address to have approved at least the desired amount /// of tokens to msg.sender. function transferFrom( address from, address to, uint160 amount, address token ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ 32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ ", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "../interfaces/IViaRouter.sol"; abstract contract ViaRouterEvents is IViaRouter { // EVENTS /// @notice Event emitted when new validator is set event ValidatorSet(address indexed validator_); /// @notice Event emitted when address is set as adapter event AdapterSet(address indexed adapter, bool indexed value); /// @notice Event emitted when address is set as whitelisted target event WhitelistedSet(address indexed target, bool indexed whitelisted); /// @notice Event emitted when collected fee is withdrawn from contract event FeeWithdrawn( address indexed token, address indexed receiver, uint256 amount ); /// @notice Event emitted when swap and/or bridge request is executed event RequestExecuted( ViaData viaData, SwapData swapData, BridgeData bridgeData ); /// @notice Event emitted when swap and/or bridge request is executed event NewRequestExecuted( ViaData viaData, NewSwapData swapData, BridgeData bridgeData ); /// @notice Event emitted when batch request is executed event BatchRequestExecuted( ViaData[] viaDatas, SwapData[] swapDatas, BridgeData[] bridgeDatas, uint256[] extraNativeValues ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./ViaRouterStorage.sol"; import "./ViaRouterEvents.sol"; import "../libraries/Transfers.sol"; import "../libraries/Errors.sol"; import "../libraries/Whitelist.sol"; abstract contract ViaRouterControls is ViaRouterStorage, ViaRouterEvents { using Transfers for address; // PUBLIC OWNER FUNCTIONS /// @notice Sets new validator (owner only) /// @param validator_ Address of the new validator function setValidator(address validator_) external onlyOwner { validator = validator_; emit ValidatorSet(validator_); } /// @notice Sets address as enabled or disabled adapter (owner only) /// @param adapter Address to set /// @param active True to enable as adapter, false to disable function setAdapter(address adapter, bool active) external onlyOwner { adapters[adapter] = active; emit AdapterSet(adapter, active); } /// @notice Sets whitelist state for list of target contracts /// @param targets List of addresses of target contracts to set /// @param whitelisted List of flags if each address should be whitelisted or blacklisted function setWhitelistedTargets( address[] calldata targets, bool[] calldata whitelisted ) external onlyOwner { require(targets.length == whitelisted.length, Errors.LENGHTS_MISMATCH); for (uint256 i = 0; i < targets.length; i++) { Whitelist.setWhitelisted(targets[i], whitelisted[i]); emit WhitelistedSet(targets[i], whitelisted[i]); } } /// @notice Withdraws collected fee from contract (owner only) /// @param token Token to withdraw (address(0) to withdrawn native token) /// @param receiver Receiver of the withdrawal /// @param amount Amount to withdraw function withdrawFee( address token, address receiver, uint256 amount ) external onlyOwner { require( collectedFees[token] >= amount, Errors.INSUFFICIENT_COLLECTED_FEES ); uint256 balanceBefore = Transfers.getBalance(token); Transfers.transferOut(token, receiver, amount); uint256 balanceAfter = Transfers.getBalance(token); collectedFees[token] -= balanceBefore - balanceAfter; emit FeeWithdrawn(token, receiver, amount); } // PUBLIC VIEW FUNCTIONS /// @notice Checks if address is whitelisted as target /// @param target Address to check /// @return _ True if whitelisted, false otherwise function isWhitelistedTarget(address target) external view returns (bool) { return Whitelist.isWhitelisted(target); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../interfaces/IViaRouter.sol"; abstract contract ViaRouterStorage is OwnableUpgradeable, ReentrancyGuardUpgradeable, IViaRouter { // STORAGE /// @notice Address that pre-validates execution requests address public validator; /// @notice Mapping of addresses being execution adapters mapping(address => bool) public adapters; /// @notice Mapping from execution IDs to then being executed (to prevent double execution) mapping(bytes32 => bool) public executedId; /// @notice Mapping from token addresses to fee amounts collected in form of them mapping(address => uint256) public collectedFees; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; library Whitelist { /// STORAGE bytes32 internal constant NAMESPACE = keccak256("com.via.whitelist"); struct WhitelistStorage { mapping(address => bool) whitelist; } /// FUNCTIONS /// @notice Returns if target contract is allowed /// @param target Address of the target contract /// @return _ True if allowed, false otherwise function isWhitelisted(address target) internal view returns (bool) { return _getStorage().whitelist[target]; } /// @notice Function that sets whitelist state of target contract /// @param target Address of the target contract /// @param whitelisted True if allowed, false otherwise function setWhitelisted(address target, bool whitelisted) internal { _getStorage().whitelist[target] = whitelisted; } /// @notice Function that gets shared storage struct /// @return wls Storage struct function _getStorage() internal pure returns (WhitelistStorage storage wls) { bytes32 position = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { wls.slot := position } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./components/ViaRouterControls.sol"; import "./components/ViaRouterBase.sol"; contract ViaRouter is ViaRouterControls, ViaRouterBase { // INITIALIZER /// @notice Contract constructor, left for implementation initialization constructor() initializer {} /// @notice Upgradeable contract's initializer /// @param validator_ Address of the validator function initialize(address validator_) external initializer { __Ownable_init(); __ReentrancyGuard_init(); validator = validator_; emit ValidatorSet(validator_); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "./ViaRouterStorage.sol"; import "./ViaRouterEvents.sol"; import "../libraries/Transfers.sol"; import "../libraries/Errors.sol"; import "../libraries/Whitelist.sol"; import "../interfaces/IAdapter.sol"; abstract contract ViaRouterBase is ViaRouterStorage, ViaRouterEvents { using Address for address; using Address for address payable; using Transfers for address; // PUBLIC FUNCTIONS /// @notice Primary function that executes swap and/or bridge with given params /// @param viaData General execution data /// @param swapData Execution swap data /// @param bridgeData Execution bridge data /// @param validatorSig Validator's ECDSA signature of the execution function execute( ViaData calldata viaData, SwapData calldata swapData, BridgeData calldata bridgeData, bytes calldata validatorSig ) public payable { // Check if validator signature is correct bytes32 digest = ECDSAUpgradeable.toEthSignedMessageHash( abi.encode(viaData, swapData, bridgeData, block.chainid) ); _checkValidatorSignature(digest, validatorSig); // Execute request SwapType swapType = swapData.target == address(0) ? SwapType.None : SwapType.ExactIn; _executeSingle( viaData, NewSwapData({ swapType: swapType, target: swapData.target, assetOut: swapData.assetOut, callData: swapData.callData, quoter: address(0), quoteData: bytes("") }), bridgeData, true, type(uint256).max ); // Emit event emit RequestExecuted(viaData, swapData, bridgeData); } /// @notice Primary function that executes swap and/or bridge with given params (new format) /// @param viaData General execution data /// @param swapData Execution swap data /// @param bridgeData Execution bridge data /// @param validatorSig Validator's ECDSA signature of the execution function executeNew( ViaData calldata viaData, NewSwapData memory swapData, BridgeData calldata bridgeData, bytes calldata validatorSig ) public payable { // Check if validator signature is correct bytes32 digest = ECDSAUpgradeable.toEthSignedMessageHash( abi.encode(viaData, swapData, bridgeData, block.chainid) ); _checkValidatorSignature(digest, validatorSig); // Execute request _executeSingle(viaData, swapData, bridgeData, true, type(uint256).max); // Emit event emit NewRequestExecuted(viaData, swapData, bridgeData); } function executeBatch( ViaData[] calldata viaDatas, NewSwapData[] calldata swapDatas, BridgeData[] calldata bridgeDatas, uint256[] calldata extraNativeValues, bytes calldata validatorSig ) external payable { // Check if validator signature is correct bytes32 digest = ECDSAUpgradeable.toEthSignedMessageHash( abi.encode( viaDatas, swapDatas, bridgeDatas, extraNativeValues, block.chainid ) ); _checkValidatorSignature(digest, validatorSig); // Check array lengths require( viaDatas.length == swapDatas.length && viaDatas.length == bridgeDatas.length && viaDatas.length == extraNativeValues.length, Errors.LENGHTS_MISMATCH ); // Check passed value and IDs uint256 totalValue; for (uint256 i = 0; i < viaDatas.length; i++) { totalValue += extraNativeValues[i]; if (viaDatas[i].assetIn.isNative()) { totalValue += viaDatas[i].amountIn; } if (i > 0) { require( viaDatas[i].id == viaDatas[i - 1].id, Errors.ID_MISMATCH ); } } require(totalValue == msg.value, Errors.INVALID_MESSAGE_VALUE); // Check that request has not been executed already require(!executedId[viaDatas[0].id], Errors.DOUBLE_EXECUTION); // Mark request as executed executedId[viaDatas[0].id] = true; // Execute each part for (uint256 i = 0; i < viaDatas.length; i++) { _executeSingle( viaDatas[i], swapDatas[i], bridgeDatas[i], false, extraNativeValues[i] ); } } // PRIVATE FUNCTIONS /// @notice Internal function that processes single swap/bridge execution /// @param viaData General execution data /// @param swapData Execution swap data /// @param bridgeData Execution bridge data /// @param checkId Flag if execution ID should be check for uniqueness /// @param extraNativeValue Extra native value to use (type(uint256).max to use all passed) function _executeSingle( ViaData calldata viaData, NewSwapData memory swapData, BridgeData calldata bridgeData, bool checkId, uint256 extraNativeValue ) private { // Check that deadline has not passed yet require( block.timestamp <= viaData.deadline, Errors.DEADLINE_HAS_PASSED ); if (checkId) { // Check that request has not been executed already require(!executedId[viaData.id], Errors.DOUBLE_EXECUTION); // Mark request as executed executedId[viaData.id] = true; } // Check if either swap or bridge is executed require( swapData.target != address(0) || bridgeData.target != address(0), Errors.EMPTY_EXECUTION ); // Execute swap (if required) ( address assetOut, uint256 amountOut, uint256 passedExtraNativeValue ) = _swap(viaData.assetIn, viaData.amountIn, viaData.fee, swapData); // Determine extra native value if (extraNativeValue == type(uint256).max) { extraNativeValue = passedExtraNativeValue; } // Execute bridge (if required) _bridge(assetOut, amountOut, extraNativeValue, bridgeData); } /// @notice Internal function that executes swap (if required) /// @param assetIn Asset to swap /// @param amountIn Amount to swap /// @param fee Fee to collect /// @param swapData Swap details function _swap( address assetIn, uint256 amountIn, uint256 fee, NewSwapData memory swapData ) private returns ( address assetOut, uint256 amountOut, uint256 extraNativeValue ) { // In case of ExactOut, quote for required amount if (swapData.swapType == SwapType.ExactOut) { bytes memory response = swapData.quoter.functionStaticCall( swapData.quoteData ); (amountIn) = abi.decode(response, (uint256)); amountIn += fee; } // Transfer incoming asset to ViaRouter contract extraNativeValue = assetIn.transferIn(amountIn); // Collect fees from incoming asset collectedFees[assetIn] += fee; amountIn -= fee; // If no swap required, just pass incoming asset and amount if (swapData.swapType == SwapType.None) { return (assetIn, amountIn, extraNativeValue); } // Check that target is allowed require( Whitelist.isWhitelisted(swapData.target), Errors.INVALID_TARGET ); // Save balance of outcoming asset before swap uint256 balanceOutBefore = Transfers.getBalance(swapData.assetOut); // Approve incoming asset assetIn.approve(swapData.target, amountIn); // Call swap target with passed calldata swapData.target.functionCallWithValue( swapData.callData, assetIn.isNative() ? amountIn : 0 ); // Calculate and return received amount of outcoming token uint256 balanceOutAfter = Transfers.getBalance(swapData.assetOut); return ( swapData.assetOut, balanceOutAfter - balanceOutBefore, extraNativeValue ); } /// @notice Internal function that executes bridge (if required) /// @param assetIn Asset to swap /// @param amountIn Amount to swap /// @param extraNativeValue Extra value of native token passed (used be some bridges) /// @param bridgeData Bridge details function _bridge( address assetIn, uint256 amountIn, uint256 extraNativeValue, BridgeData calldata bridgeData ) private { // If no bridging required, just return if (bridgeData.target == address(0)) { return; } // Check that target is a valid adapter require(adapters[bridgeData.target], Errors.NOT_AN_ADAPTER); // Delegate call to adapter bridgeData.target.functionDelegateCall( abi.encodeWithSelector( IAdapter.call.selector, assetIn, amountIn, extraNativeValue, bridgeData.callData ) ); } // PRIVATE VIEW FUNCTIONS /// @notice Internal function that checks that execution was signed by validator /// @param digest Digest of signed data /// @param validatorSig Validator's ECDSA signature function _checkValidatorSignature( bytes32 digest, bytes calldata validatorSig ) private view { // Recover ECDSA signer address signer = ECDSAUpgradeable.recover(digest, validatorSig); // Check that signer matches current validator require(signer == validator, Errors.NOT_SIGNED_BY_VALIDATOR); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ 32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ ", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "../libraries/Transfers.sol"; import "../libraries/Whitelist.sol"; import "../libraries/Errors.sol"; import "../interfaces/IAdapter.sol"; contract UniversalAdapter is IAdapter { using Address for address; using Transfers for address; /// @inheritdoc IAdapter function call( address assetIn, uint256 amountIn, uint256 extraNativeValue, bytes memory args ) external payable override { // Decode args to receive variables ( address approvalTarget, address callTarget, bytes memory callData ) = abi.decode(args, (address, address, bytes)); // Check that target is allowed require(Whitelist.isWhitelisted(callTarget), Errors.INVALID_TARGET); // Approve incoming asset assetIn.approve(approvalTarget, amountIn); // Call bridge target with passed calldata uint256 baseValue = assetIn.isNative() ? amountIn : 0; callTarget.functionCallWithValue( callData, baseValue + extraNativeValue ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "../libraries/Transfers.sol"; import "../libraries/Whitelist.sol"; import "../libraries/Errors.sol"; import "../interfaces/IAdapter.sol"; import "../interfaces/external/IMultichain.sol"; contract MultichainAdapter is IAdapter { using Transfers for address; struct AnySwapOutArgs { address multichainRouter; address anyToken; address receiver; uint256 chainid; } /// @inheritdoc IAdapter function call( address tokenIn, uint256 amountIn, uint256, bytes memory args ) external payable override { AnySwapOutArgs memory swapArgs = abi.decode(args, (AnySwapOutArgs)); // Check that target is allowed require( Whitelist.isWhitelisted(swapArgs.multichainRouter), Errors.INVALID_TARGET ); // Call bridge if (tokenIn == address(0)) { IMultichain(swapArgs.multichainRouter).anySwapOutNative{ value: amountIn }({ token: swapArgs.anyToken, to: swapArgs.receiver, toChainID: swapArgs.chainid }); } else { tokenIn.approve(swapArgs.multichainRouter, amountIn); IMultichain(swapArgs.multichainRouter).anySwapOutUnderlying({ token: swapArgs.anyToken, to: swapArgs.receiver, amount: amountIn, toChainID: swapArgs.chainid }); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IMultichain { function anySwapOutUnderlying( address token, address to, uint256 amount, uint256 toChainID ) external; function anySwapOutNative( address token, address to, uint toChainID ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../libraries/Transfers.sol"; import "../interfaces/external/ISymbiosisMetaRouter.sol"; contract SymbiosisAdapter is AdapterBase { using Transfers for address; /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct MetaRouteArgs { bytes firstSwapCalldata; bytes secondSwapCalldata; address[] approvedTokens; address firstDexRouter; address secondDexRouter; bool nativeIn; address relayRecipient; bytes otherSideCalldata; address approveTo; } /// @inheritdoc AdapterBase function call( address assetIn, uint256 amountIn, uint256, bytes memory args ) external payable override { MetaRouteArgs memory routeArgs = abi.decode(args, (MetaRouteArgs)); if (!routeArgs.nativeIn) { assetIn.approve(routeArgs.approveTo, amountIn); } uint256 value = routeArgs.nativeIn ? amountIn : 0; ISymbiosisMetaRouter(target).metaRoute{value: value}( ISymbiosisMetaRouter.MetaRouteArgs({ firstSwapCalldata: routeArgs.firstSwapCalldata, secondSwapCalldata: routeArgs.secondSwapCalldata, approvedTokens: routeArgs.approvedTokens, firstDexRouter: routeArgs.firstDexRouter, secondDexRouter: routeArgs.secondDexRouter, amount: amountIn, nativeIn: routeArgs.nativeIn, relayRecipient: routeArgs.relayRecipient, otherSideCalldata: routeArgs.otherSideCalldata }) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ISymbiosisMetaRouter { struct MetaRouteArgs { bytes firstSwapCalldata; bytes secondSwapCalldata; address[] approvedTokens; address firstDexRouter; address secondDexRouter; uint256 amount; bool nativeIn; address relayRecipient; bytes otherSideCalldata; } function metaRoute(MetaRouteArgs memory args) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "../libraries/Transfers.sol"; import "../libraries/Whitelist.sol"; import "../libraries/Errors.sol"; import "../interfaces/IAdapter.sol"; import "../interfaces/external/IHopBridge.sol"; contract HopAdapter is IAdapter { using Transfers for address; /// @notice ID of L1 chain (Ethereum) uint256 public constant L1_CHAIN_ID = 1; struct SendToL2Args { address bridge; uint256 chainId; address recipient; uint256 amountOutMin; uint256 deadline; address relayer; uint256 relayerFee; } struct SwapAndSendArgs { address bridge; uint256 chainId; address recipient; uint256 bonderFee; uint256 amountOutMin; uint256 deadline; uint256 destinationAmountOutMin; uint256 destinationDeadline; } /// @inheritdoc IAdapter function call( address tokenIn, uint256 amountIn, uint256, bytes memory args ) external payable override { /* Hop Bridge uses 2 interfaces for bridging depending on sneding being done from L1 or L2: 1. If user sends funds from L1 (Ethereum Mainnet), he should use `sendToL2` function 2. If users send funds from L2 (all other chains), he should use `swapAndSend` function */ if (block.chainid == L1_CHAIN_ID) { // Decode bridge arguments SendToL2Args memory _args = abi.decode(args, (SendToL2Args)); // Check that target is allowed require( Whitelist.isWhitelisted(_args.bridge), Errors.INVALID_TARGET ); // Approve token tokenIn.approve(_args.bridge, amountIn); // Bridge uint256 _amountIn = (tokenIn == address(0)) ? amountIn : 0; IHopBridge(_args.bridge).sendToL2{value: _amountIn}( _args.chainId, _args.recipient, amountIn, _args.amountOutMin, _args.deadline, _args.relayer, _args.relayerFee ); } else { // Decode bridge arguments SwapAndSendArgs memory _args = abi.decode(args, (SwapAndSendArgs)); // Check that target is allowed require( Whitelist.isWhitelisted(_args.bridge), Errors.INVALID_TARGET ); // Approve token tokenIn.approve(_args.bridge, amountIn); // Bridge uint256 _amountIn = (tokenIn == address(0)) ? amountIn : 0; IHopBridge(_args.bridge).swapAndSend{value: _amountIn}( _args.chainId, _args.recipient, amountIn, _args.bonderFee, _args.amountOutMin, _args.deadline, _args.destinationAmountOutMin, _args.destinationDeadline ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IHopBridge { function sendToL2( uint256 chainId, address recipient, uint256 amount, uint256 amountOutMin, uint256 deadline, address relayer, uint256 relayerFee ) external payable; function swapAndSend( uint256 chainId, address recipient, uint256 amount, uint256 bonderFee, uint256 amountOutMin, uint256 deadline, uint256 destinationAmountOutMin, uint256 destinationDeadline ) external payable; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializing the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { 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 This is a virtual function that should be overridden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overridden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >0.0.0; import '@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol'; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol) pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall( TransparentUpgradeableProxy proxy, address implementation, bytes memory data ) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * May emit a {RoleGranted} event. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`. * However, to ensure consistency with the upgradeable transpiler, we will continue * to reserve a slot. * @custom:oz-renamed-from _PERMIT_TYPEHASH */ // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../extensions/ERC20Burnable.sol"; import "../extensions/ERC20Pausable.sol"; import "../../../access/AccessControlEnumerable.sol"; import "../../../utils/Context.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. * * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ */ contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.16; import "@openzeppelin/contracts/token/ERC20/presets/ERC20PresetMinterPauser.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; contract ERC20Mock is ERC20PresetMinterPauser, ERC20Permit { constructor(string memory name_, string memory symbol_) ERC20PresetMinterPauser(name_, symbol_) ERC20Permit(name_) {} function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20PresetMinterPauser) { super._beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >0.0.0; import '@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol'; // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "../libraries/Whitelist.sol"; import "./AdapterBase.sol"; import "../interfaces/external/IAllbridgeCore.sol"; contract AllbridgeCoreAdapter is AdapterBase { struct AllbridgeCoreArgs { address approveTo; bytes32 recipient; uint8 destinationChainId; bytes32 receiveToken; uint256 nonce; uint8 messenger; } /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} /// @inheritdoc AdapterBase function call( address tokenIn, uint256 amountIn, uint256 extraNativeValue, bytes memory args ) external payable override { // Decode args to receive variables AllbridgeCoreArgs memory allbridgeArgs = abi.decode( args, (AllbridgeCoreArgs) ); // Check that approve target is allowed require( Whitelist.isWhitelisted(allbridgeArgs.approveTo), Errors.INVALID_TARGET ); // Approve token Transfers.approve(tokenIn, allbridgeArgs.approveTo, amountIn); // Send bridge transaction uint256 value = (tokenIn == address(0)) ? amountIn + extraNativeValue : extraNativeValue; IAllbridgeCore(target).swapAndBridge{value: value}( bytes32(uint256(uint160(tokenIn))), amountIn, allbridgeArgs.recipient, allbridgeArgs.destinationChainId, allbridgeArgs.receiveToken, allbridgeArgs.nonce, allbridgeArgs.messenger ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IAllbridgeCore { function swapAndBridge( bytes32 token, uint256 amount, bytes32 recipient, uint8 destinationChainId, bytes32 receiveToken, uint256 nonce, uint8 messenger ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../libraries/Errors.sol"; import "../interfaces/external/IConnext.sol"; contract ConnextAdapter is AdapterBase { constructor(address target_) AdapterBase(target_) {} function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { IConnext.PrepareArgs memory prepareArgs = abi.decode( args, (IConnext.PrepareArgs) ); require( prepareArgs.invariantData.sendingAssetId == tokenIn, Errors.INVALID_INCOMING_TOKEN ); prepareArgs.amount = amountIn; uint256 value = tokenIn == address(0) ? amountIn : 0; IConnext(target).prepare{value: value}(prepareArgs); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConnext { // Structs // Holds all data that is constant between sending and // receiving chains. The hash of this is what gets signed // to ensure the signature can be used on both chains. struct InvariantTransactionData { address receivingChainTxManagerAddress; address user; address router; address initiator; // msg.sender of sending side address sendingAssetId; address receivingAssetId; address sendingChainFallback; // funds sent here on cancel address receivingAddress; address callTo; uint256 sendingChainId; uint256 receivingChainId; bytes32 callDataHash; // hashed to prevent free option bytes32 transactionId; } // Holds all data that varies between sending and receiving // chains. The hash of this is stored onchain to ensure the // information passed in is valid. struct VariantTransactionData { uint256 amount; uint256 expiry; uint256 preparedBlockNumber; } // All Transaction data, constant and variable struct TransactionData { address receivingChainTxManagerAddress; address user; address router; address initiator; // msg.sender of sending side address sendingAssetId; address receivingAssetId; address sendingChainFallback; address receivingAddress; address callTo; bytes32 callDataHash; bytes32 transactionId; uint256 sendingChainId; uint256 receivingChainId; uint256 amount; uint256 expiry; uint256 preparedBlockNumber; // Needed for removal of active blocks on fulfill/cancel } // The structure of the signed data for fulfill struct SignedFulfillData { bytes32 transactionId; uint256 relayerFee; string functionIdentifier; // "fulfill" or "cancel" uint256 receivingChainId; // For domain separation address receivingChainTxManagerAddress; // For domain separation } // The structure of the signed data for cancellation struct SignedCancelData { bytes32 transactionId; string functionIdentifier; uint256 receivingChainId; address receivingChainTxManagerAddress; // For domain separation } /** * Arguments for calling prepare() * @param invariantData The data for a crosschain transaction that will * not change between sending and receiving chains. * The hash of this data is used as the key to store * the inforamtion that does change between chains * (amount,expiry,preparedBlock) for verification * @param amount The amount of the transaction on this chain * @param expiry The block.timestamp when the transaction will no longer be * fulfillable and is freely cancellable on this chain * @param encryptedCallData The calldata to be executed when the tx is * fulfilled. Used in the function to allow the user * to reconstruct the tx from events. Hash is stored * onchain to prevent shenanigans. * @param encodedBid The encoded bid that was accepted by the user for this * crosschain transfer. It is supplied as a param to the * function but is only used in event emission * @param bidSignature The signature of the bidder on the encoded bid for * this transaction. Only used within the function for * event emission. The validity of the bid and * bidSignature are enforced offchain * @param encodedMeta The meta for the function */ struct PrepareArgs { InvariantTransactionData invariantData; uint256 amount; uint256 expiry; bytes encryptedCallData; bytes encodedBid; bytes bidSignature; bytes encodedMeta; } /** * @param txData All of the data (invariant and variant) for a crosschain * transaction. The variant data provided is checked against * what was stored when the `prepare` function was called. * @param relayerFee The fee that should go to the relayer when they are * calling the function on the receiving chain for the user * @param signature The users signature on the transaction id + fee that * can be used by the router to unlock the transaction on * the sending chain * @param callData The calldata to be sent to and executed by the * `FulfillHelper` * @param encodedMeta The meta for the function */ struct FulfillArgs { TransactionData txData; uint256 relayerFee; bytes signature; bytes callData; bytes encodedMeta; } /** * Arguments for calling cancel() * @param txData All of the data (invariant and variant) for a crosschain * transaction. The variant data provided is checked against * what was stored when the `prepare` function was called. * @param signature The user's signature that allows a transaction to be * cancelled by a relayer * @param encodedMeta The meta for the function */ struct CancelArgs { TransactionData txData; bytes signature; bytes encodedMeta; } // Adding/removing asset events event RouterAdded(address indexed addedRouter, address indexed caller); event RouterRemoved(address indexed removedRouter, address indexed caller); // Adding/removing router events event AssetAdded(address indexed addedAssetId, address indexed caller); event AssetRemoved(address indexed removedAssetId, address indexed caller); // Liquidity events event LiquidityAdded( address indexed router, address indexed assetId, uint256 amount, address caller ); event LiquidityRemoved( address indexed router, address indexed assetId, uint256 amount, address recipient ); // Transaction events event TransactionPrepared( address indexed user, address indexed router, bytes32 indexed transactionId, TransactionData txData, address caller, PrepareArgs args ); event TransactionFulfilled( address indexed user, address indexed router, bytes32 indexed transactionId, FulfillArgs args, bool success, bool isContract, bytes returnData, address caller ); event TransactionCancelled( address indexed user, address indexed router, bytes32 indexed transactionId, CancelArgs args, address caller ); // Getters function getChainId() external view returns (uint256); function getStoredChainId() external view returns (uint256); // Owner only methods function addRouter(address router) external; function removeRouter(address router) external; function addAssetId(address assetId) external; function removeAssetId(address assetId) external; // Router only methods function addLiquidityFor( uint256 amount, address assetId, address router ) external payable; function addLiquidity(uint256 amount, address assetId) external payable; function removeLiquidity( uint256 amount, address assetId, address payable recipient ) external; // Methods for crosschain transfers // called in the following order (in happy case) // 1. prepare by user on sending chain // 2. prepare by router on receiving chain // 3. fulfill by user on receiving chain // 4. fulfill by router on sending chain function prepare(PrepareArgs calldata args) external payable returns (TransactionData memory); function fulfill(FulfillArgs calldata args) external returns (TransactionData memory); function cancel(CancelArgs calldata args) external returns (TransactionData memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/IWormhole.sol"; contract WormholeAdapter is AdapterBase { /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct TransferArgs { uint16 recipientChain; bytes32 recipient; uint256 arbiterFee; uint32 nonce; } /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { if (amountIn == 0) { // Claim from Wormhole bridge IWormhole(target).completeTransfer(args); return; } TransferArgs memory transferArgs = abi.decode(args, (TransferArgs)); if (tokenIn == address(0)) { // Wrap and transfer ETH IWormhole(target).wrapAndTransferETH{value: amountIn}( transferArgs.recipientChain, transferArgs.recipient, transferArgs.arbiterFee, transferArgs.nonce ); } else { // Transfer ERC-20 tken IWormhole(target).transferTokens( tokenIn, amountIn, transferArgs.recipientChain, transferArgs.recipient, transferArgs.arbiterFee, transferArgs.nonce ); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IWormhole { function wrapAndTransferETH( uint16 recipientChain, bytes32 recipient, uint256 arbiterFee, uint32 nonce ) external payable returns (uint64 sequence); function transferTokens( address token, uint256 amount, uint16 recipientChain, bytes32 recipient, uint256 arbiterFee, uint32 nonce ) external payable returns (uint64 sequence); function completeTransfer(bytes memory encodedVm) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/IStargateRouter.sol"; contract StargateAdapter is AdapterBase { struct StargateArgs { uint16 _dstChainId; uint256 _srcPoolId; uint256 _dstPoolId; address payable _refundAddress; uint256 _minAmountLD; bytes _to; } /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} /// @inheritdoc AdapterBase function call( address tokenIn, uint256 amountIn, uint256 extraNativeValue, bytes memory args ) external payable override { StargateArgs memory stargateArgs = abi.decode(args, (StargateArgs)); Transfers.approve(tokenIn, target, amountIn); uint256 baseValue = (tokenIn == address(0)) ? amountIn : 0; IStargateRouter(target).swap{value: baseValue + extraNativeValue}( stargateArgs._dstChainId, stargateArgs._srcPoolId, stargateArgs._dstPoolId, stargateArgs._refundAddress, amountIn, stargateArgs._minAmountLD, IStargateRouter.lzTxObj(0, 0, "0x"), stargateArgs._to, "0x" ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IStargateRouter { struct lzTxObj { uint256 dstGasForCall; uint256 dstNativeAmount; bytes dstNativeAddr; } function swap( uint16 _dstChainId, uint256 _srcPoolId, uint256 _dstPoolId, address payable _refundAddress, uint256 _amountLD, uint256 _minAmountLD, lzTxObj memory _lzTxParams, bytes calldata _to, bytes calldata _payload ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/IPolygonBridge.sol"; contract PolygonBridgeAdapter is AdapterBase { /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct BridgeArgs { address receiver; } /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { BridgeArgs memory bridgeArgs = abi.decode(args, (BridgeArgs)); bytes memory encodedAmount = abi.encodePacked(amountIn); IPolygonBridge(target).depositFor( bridgeArgs.receiver, tokenIn, encodedAmount ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPolygonBridge { function depositFor( address user, address rootToken, bytes memory depositData ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/IHyphen.sol"; contract HyphenAdapter is AdapterBase { /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct DepositArgs { address receiver; uint256 toChainId; string tag; } /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { DepositArgs memory depositArgs = abi.decode(args, (DepositArgs)); if (tokenIn == address(0)) { IHyphen(target).depositNative( depositArgs.receiver, depositArgs.toChainId, depositArgs.tag ); } else { IHyphen(target).depositErc20( depositArgs.toChainId, tokenIn, depositArgs.receiver, amountIn, depositArgs.tag ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IHyphen { function depositErc20( uint256 toChainId, address tokenAddress, address receiver, uint256 amount, string memory tag ) external; function depositNative( address receiver, uint256 toChainId, string memory tag ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "./AdapterBase.sol"; import "../interfaces/external/ICBridge.sol"; contract CBridgeAdapter is AdapterBase { /// @notice Adapter constructor /// @param target_ Target contract for this adapter constructor(address target_) AdapterBase(target_) {} struct SendArgs { address receiver; uint64 chainid; uint64 nonce; uint32 slippage; } /// @inheritdoc AdapterBase function _executeCall( address tokenIn, uint256 amountIn, bytes memory args ) internal override { SendArgs memory sendArgs = abi.decode(args, (SendArgs)); ICBridge(target).send({ _receiver: sendArgs.receiver, _token: tokenIn, _amount: amountIn, _dstChainId: sendArgs.chainid, _nonce: sendArgs.nonce, _maxSlippage: sendArgs.slippage }); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // taking from the verified code here - https://polygonscan.com/address/0x88DCDC47D2f83a99CF0000FDF667A468bB958a78#code interface ICBridge { function send( address _receiver, address _token, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage // not easy to calculate, check https://cbridge-docs.celer.network/developer/api-reference/gateway-estimateamt ) external; // I did not have a chance to check it on mainnet, because cBrdige does not support BNB neither MATIC function sendNative( address _receiver, uint256 _amount, uint64 _dstChainId, uint64 _nonce, uint32 _maxSlippage ) external payable; event Send( bytes32 transferId, address sender, address receiver, address token, uint256 amount, uint64 dstChainId, uint64 nonce, uint32 maxSlippage ); event Relay( bytes32 transferId, address sender, address receiver, address token, uint256 amount, uint64 srcChainId, bytes32 srcTransferId ); }
File 7 of 8: UniversalAdapter
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "../libraries/Transfers.sol"; import "../libraries/Whitelist.sol"; import "../libraries/Errors.sol"; import "../interfaces/IAdapter.sol"; contract UniversalAdapter is IAdapter { using Address for address; using Transfers for address; /// @inheritdoc IAdapter function call( address assetIn, uint256 amountIn, uint256 extraNativeValue, bytes memory args ) external payable override { // Decode args to receive variables ( address approvalTarget, address callTarget, bytes memory callData ) = abi.decode(args, (address, address, bytes)); // Check that target is allowed require(Whitelist.isWhitelisted(callTarget), Errors.INVALID_TARGET); // Approve incoming asset assetIn.approve(approvalTarget, amountIn); // Call bridge target with passed calldata uint256 baseValue = assetIn.isNative() ? amountIn : 0; callTarget.functionCallWithValue( callData, baseValue + extraNativeValue ); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; interface IAdapter { /// @notice Executes call with given params /// @param assetIn Incoming asset /// @param amountIn Incoming amount /// @param nativeExtraValue Extra value of native token that can be used by call /// @param args Encoded additional arguments for current adapter function call( address assetIn, uint256 amountIn, uint256 nativeExtraValue, bytes memory args ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; library Errors { // ViaRouter string internal constant INSUFFICIENT_COLLECTED_FEES = "ICF"; string internal constant EMPTY_EXECUTION = "EE"; string internal constant DEADLINE_HAS_PASSED = "DHP"; string internal constant DOUBLE_EXECUTION = "DE"; string internal constant NOT_SIGNED_BY_VALIDATOR = "NSV"; string internal constant NOT_AN_ADAPTER = "NAA"; string internal constant INVALID_SPLIT = "ISP"; // Transfers string internal constant INVALID_MESSAGE_VALUE = "IMV"; string internal constant INVALID_RECEIVED_AMOUNT = "IRA"; // Adapters string internal constant INVALID_INCOMING_TOKEN = "IIT"; // Gasless Relay string internal constant INVALID_SIGNATURE = "IVS"; string internal constant NONCE_ALREADY_USED = "NAU"; string internal constant INVALID_ROUTER_SELECTOR = "IRS"; string internal constant INVALID_PERMIT_SELECTOR = "IPS"; // Generic string internal constant ZERO_ADDRESS = "ZA"; string internal constant INVALID_TARGET = "IVT"; string internal constant LENGHTS_MISMATCH = "LMM"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Errors.sol"; library Transfers { using SafeERC20 for IERC20; using Address for address payable; /// @notice Transfers (or checks sent value) given asset from sender to running contract /// @param asset Asset to transfer (address(0) to check native sent value) /// @param amount Amount to transfer /// @return extraValue Extra amount of native token passed function transferIn(address asset, uint256 amount) internal returns (uint256 extraValue) { if (isNative(asset)) { require(msg.value >= amount, Errors.INVALID_MESSAGE_VALUE); return msg.value - amount; } else { uint256 balanceBefore = IERC20(asset).balanceOf(address(this)); IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); require( IERC20(asset).balanceOf(address(this)) - balanceBefore == amount, Errors.INVALID_RECEIVED_AMOUNT ); return msg.value; } } /// @notice Transfers given token from running contract to given address /// @param asset Asset to transfer (address(0) to transfer native token) /// @param to Address to transfer to /// @param amount Amount to transfer function transferOut( address asset, address to, uint256 amount ) internal { if (isNative(asset)) { payable(to).sendValue(amount); } else { IERC20(asset).safeTransfer(to, amount); } } /// @notice Approves given token to given spender (with checks for address(0) as native) /// @param asset Token to approve /// @param spender Spender address /// @param amount Amount to approve function approve( address asset, address spender, uint256 amount ) internal { if (isNative(asset)) { return; } uint256 allowance = IERC20(asset).allowance(address(this), spender); if (allowance > 0) { // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 IERC20(asset).safeApprove(spender, 0); } IERC20(asset).safeIncreaseAllowance(spender, amount); } /// @notice Gets balance of given token /// @param asset Token to get balance of (address(0) for native token) function getBalance(address asset) internal view returns (uint256) { if (isNative(asset)) { return address(this).balance; } else { return IERC20(asset).balanceOf(address(this)); } } function isNative(address asset) internal pure returns (bool) { return asset == address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.16; library Whitelist { /// STORAGE bytes32 internal constant NAMESPACE = keccak256("com.via.whitelist"); struct WhitelistStorage { mapping(address => bool) whitelist; } /// FUNCTIONS /// @notice Returns if target contract is allowed /// @param target Address of the target contract /// @return _ True if allowed, false otherwise function isWhitelisted(address target) internal view returns (bool) { return _getStorage().whitelist[target]; } /// @notice Function that sets whitelist state of target contract /// @param target Address of the target contract /// @param whitelisted True if allowed, false otherwise function setWhitelisted(address target, bool whitelisted) internal { _getStorage().whitelist[target] = whitelisted; } /// @notice Function that gets shared storage struct /// @return wls Storage struct function _getStorage() internal pure returns (WhitelistStorage storage wls) { bytes32 position = NAMESPACE; // solhint-disable-next-line no-inline-assembly assembly { wls.slot := position } } }
File 8 of 8: Portal
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; interface IBridge { function transmitRequestV2( bytes memory _callData, address _receiveSide, address _oppositeBridge, uint256 _chainId ) external; function receiveRequestV2( bytes memory _callData, address _receiveSide ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; interface IWrapper { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "../MetaRouteStructs.sol"; interface IMetaRouter { function metaRoute( MetaRouteStructs.MetaRouteTransaction calldata _metarouteTransaction ) external payable; function externalCall( address _token, uint256 _amount, address _receiveSide, bytes calldata _calldata, uint256 _offset, address _revertableAddress ) external; function returnSwap( address _token, uint256 _amount, address _router, bytes calldata _swapCalldata, address _burnToken, address _synthesis, bytes calldata _burnCalldata ) external; function metaMintSwap( MetaRouteStructs.MetaMintTransaction calldata _metaMintTransaction ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; library MetaRouteStructs { struct MetaBurnTransaction { uint256 stableBridgingFee; uint256 amount; bytes32 crossChainID; address syntCaller; address finalReceiveSide; address sToken; bytes finalCallData; uint256 finalOffset; address chain2address; address receiveSide; address oppositeBridge; address revertableAddress; uint256 chainID; bytes32 clientID; } struct MetaMintTransaction { uint256 stableBridgingFee; uint256 amount; bytes32 crossChainID; bytes32 externalID; address tokenReal; uint256 chainID; address to; address[] swapTokens; address secondDexRouter; bytes secondSwapCalldata; address finalReceiveSide; bytes finalCalldata; uint256 finalOffset; } struct MetaRouteTransaction { bytes firstSwapCalldata; bytes secondSwapCalldata; address[] approvedTokens; address firstDexRouter; address secondDexRouter; uint256 amount; bool nativeIn; address relayRecipient; bytes otherSideCalldata; } struct MetaSynthesizeTransaction { uint256 stableBridgingFee; uint256 amount; address rtoken; address chain2address; address receiveSide; address oppositeBridge; address syntCaller; uint256 chainID; address[] swapTokens; address secondDexRouter; bytes secondSwapCalldata; address finalReceiveSide; bytes finalCalldata; uint256 finalOffset; address revertableAddress; bytes32 clientID; } struct MetaRevertTransaction { uint256 stableBridgingFee; bytes32 internalID; address receiveSide; address managerChainBridge; address sourceChainBridge; uint256 managerChainId; uint256 sourceChainId; address router; bytes swapCalldata; address sourceChainSynthesis; address burnToken; bytes burnCalldata; bytes32 clientID; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "./interfaces/IBridge.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "../utils/RelayRecipientUpgradeable.sol"; import "./interfaces/IWrapper.sol"; import "./metarouter/interfaces/IMetaRouter.sol"; /** * @title A contract that synthesizes tokens * @notice In order to create a synthetic representation on another network, the user must call synthesize function here * @dev All function calls are currently implemented without side effects */ contract Portal is RelayRecipientUpgradeable { /// ** PUBLIC states ** address public wrapper; address public bridge; uint256 public requestCount; bool public paused; mapping(bytes32 => TxState) public requests; mapping(bytes32 => UnsynthesizeState) public unsynthesizeStates; mapping(address => uint256) public balanceOf; mapping(address => uint256) public tokenThreshold; mapping(address => bool) public tokenWhitelist; IMetaRouter public metaRouter; /// ** STRUCTS ** enum RequestState { Default, Sent, Reverted } enum UnsynthesizeState { Default, Unsynthesized, RevertRequest } struct TxState { address recipient; address chain2address; uint256 amount; address rtoken; RequestState state; } struct SynthesizeWithPermitTransaction { uint256 stableBridgingFee; bytes approvalData; address token; uint256 amount; address chain2address; address receiveSide; address oppositeBridge; address revertableAddress; uint256 chainID; bytes32 clientID; } /// ** EVENTS ** event SynthesizeRequest( bytes32 id, // todo it wasn't indexed address indexed from, uint256 indexed chainID, address indexed revertableAddress, // todo it was indexed address to, uint256 amount, address token ); event RevertBurnRequest(bytes32 indexed id, address indexed to); event ClientIdLog(bytes32 requestId, bytes32 indexed clientId); event MetaRevertRequest(bytes32 indexed id, address indexed to); event BurnCompleted( bytes32 indexed id, bytes32 indexed crossChainID, address indexed to, uint256 amount, uint256 bridgingFee, address token ); event RevertSynthesizeCompleted( bytes32 indexed id, address indexed to, uint256 amount, uint256 bridgingFee, address token ); event Paused(address account); event Unpaused(address account); event SetWhitelistToken(address token, bool activate); event SetTokenThreshold(address token, uint256 threshold); event SetMetaRouter(address metaRouter); /// ** MODIFIERs ** modifier onlyBridge() { require(bridge == msg.sender, "Symb: caller is not the bridge"); _; } modifier whenNotPaused() { require(!paused, "Symb: paused"); _; } /// ** INITIALIZER ** /** * init */ function initialize( address _bridge, address _trustedForwarder, address _wrapper, address _whitelistedToken, IMetaRouter _metaRouter ) public virtual initializer { __RelayRecipient_init(_trustedForwarder); bridge = _bridge; wrapper = _wrapper; metaRouter = _metaRouter; if (_whitelistedToken != address(0)) { tokenWhitelist[_whitelistedToken] = true; } } /// ** EXTERNAL PURE functions ** /** * @notice Returns version */ function versionRecipient() external pure returns (string memory) { return "2.0.1"; } // ** EXTERNAL functions ** /** * @notice Sends synthesize request * @dev Token -> sToken on a second chain * @param _stableBridgingFee Bridging fee on another network * @param _token The address of the token that the user wants to synthesize * @param _amount Number of tokens to synthesize * @param _chain2address The address to which the user wants to receive the synth asset on another network * @param _receiveSide Synthesis address on another network * @param _oppositeBridge Bridge address on another network * @param _revertableAddress An address on another network that allows the user to revert a stuck request * @param _chainID Chain id of the network where synthesization will take place */ function synthesize( uint256 _stableBridgingFee, address _token, uint256 _amount, address _chain2address, address _receiveSide, address _oppositeBridge, address _revertableAddress, uint256 _chainID, bytes32 _clientID ) external whenNotPaused returns (bytes32) { require(tokenWhitelist[_token], "Symb: unauthorized token"); require(_amount >= tokenThreshold[_token], "Symb: amount under threshold"); TransferHelper.safeTransferFrom( _token, _msgSender(), address(this), _amount ); return sendSynthesizeRequest( _stableBridgingFee, _token, _amount, _chain2address, _receiveSide, _oppositeBridge, _revertableAddress, _chainID, _clientID ); } /** * @notice Sends metaSynthesizeOffchain request * @dev Token -> sToken on a second chain -> final token on a second chain * @param _metaSynthesizeTransaction metaSynthesize offchain transaction data */ function metaSynthesize( MetaRouteStructs.MetaSynthesizeTransaction memory _metaSynthesizeTransaction ) external whenNotPaused returns (bytes32) { require(tokenWhitelist[_metaSynthesizeTransaction.rtoken], "Symb: unauthorized token"); require(_metaSynthesizeTransaction.amount >= tokenThreshold[_metaSynthesizeTransaction.rtoken], "Symb: amount under threshold"); TransferHelper.safeTransferFrom( _metaSynthesizeTransaction.rtoken, _msgSender(), address(this), _metaSynthesizeTransaction.amount ); return sendMetaSynthesizeRequest(_metaSynthesizeTransaction); } /** * @notice Native -> sToken on a second chain * @param _stableBridgingFee Bridging fee on another network * @param _chain2address The address to which the user wants to receive the synth asset on another network * @param _receiveSide Synthesis address on another network * @param _oppositeBridge Bridge address on another network * @param _chainID Chain id of the network where synthesization will take place */ function synthesizeNative( uint256 _stableBridgingFee, address _chain2address, address _receiveSide, address _oppositeBridge, address _revertableAddress, uint256 _chainID, bytes32 _clientID ) external payable whenNotPaused returns (bytes32) { require(tokenWhitelist[wrapper], "Symb: unauthorized token"); require(msg.value >= tokenThreshold[wrapper], "Symb: amount under threshold"); IWrapper(wrapper).deposit{value : msg.value}(); return sendSynthesizeRequest( _stableBridgingFee, wrapper, msg.value, _chain2address, _receiveSide, _oppositeBridge, _revertableAddress, _chainID, _clientID ); } /** * @notice Token -> sToken on a second chain withPermit * @param _syntWithPermitTx SynthesizeWithPermit offchain transaction data */ function synthesizeWithPermit( SynthesizeWithPermitTransaction memory _syntWithPermitTx ) external whenNotPaused returns (bytes32) { require(tokenWhitelist[_syntWithPermitTx.token], "Symb: unauthorized token"); require(_syntWithPermitTx.amount >= tokenThreshold[_syntWithPermitTx.token], "Symb: amount under threshold"); { ( address owner, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) = abi.decode( _syntWithPermitTx.approvalData, (address, uint256, uint256, uint8, bytes32, bytes32) ); IERC20Permit(_syntWithPermitTx.token).permit( owner, address(this), value, deadline, v, r, s ); } TransferHelper.safeTransferFrom( _syntWithPermitTx.token, _msgSender(), address(this), _syntWithPermitTx.amount ); return sendSynthesizeRequest( _syntWithPermitTx.stableBridgingFee, _syntWithPermitTx.token, _syntWithPermitTx.amount, _syntWithPermitTx.chain2address, _syntWithPermitTx.receiveSide, _syntWithPermitTx.oppositeBridge, _syntWithPermitTx.revertableAddress, _syntWithPermitTx.chainID, _syntWithPermitTx.clientID ); } /** * @notice Emergency unsynthesize * @dev Can called only by bridge after initiation on a second chain * @dev If a transaction arrives at the synthesization chain with an already completed revert synthesize contract will fail this transaction, * since the state was changed during the call to the desynthesis request * @param _stableBridgingFee Bridging fee * @param _externalID the synthesize transaction that was received from the event when it was originally called synthesize on the Portal contract */ function revertSynthesize(uint256 _stableBridgingFee, bytes32 _externalID) external onlyBridge whenNotPaused { TxState storage txState = requests[_externalID]; require( txState.state == RequestState.Sent, "Symb: state not open or tx does not exist" ); txState.state = RequestState.Reverted; // close balanceOf[txState.rtoken] = balanceOf[txState.rtoken] - txState.amount; TransferHelper.safeTransfer( txState.rtoken, txState.recipient, txState.amount - _stableBridgingFee ); TransferHelper.safeTransfer( txState.rtoken, bridge, _stableBridgingFee ); emit RevertSynthesizeCompleted( _externalID, txState.recipient, txState.amount - _stableBridgingFee, _stableBridgingFee, txState.rtoken ); } /** * @notice Revert synthesize * @dev After revertSynthesizeRequest in Synthesis this method is called * @param _stableBridgingFee Bridging fee * @param _externalID the burn transaction that was received from the event when it was originally called burn on the Synthesis contract * @param _token The address of the token to unsynthesize * @param _amount Number of tokens to unsynthesize * @param _to The address to receive tokens */ function unsynthesize( uint256 _stableBridgingFee, bytes32 _externalID, bytes32 _crossChainID, address _token, uint256 _amount, address _to ) external onlyBridge whenNotPaused { require( unsynthesizeStates[_externalID] == UnsynthesizeState.Default, "Symb: synthetic tokens emergencyUnburn" ); balanceOf[_token] = balanceOf[_token] - _amount; unsynthesizeStates[_externalID] = UnsynthesizeState.Unsynthesized; TransferHelper.safeTransfer(_token, _to, _amount - _stableBridgingFee); TransferHelper.safeTransfer(_token, bridge, _stableBridgingFee); emit BurnCompleted(_externalID, _crossChainID, _to, _amount - _stableBridgingFee, _stableBridgingFee, _token); } /** * @notice Unsynthesize and final call on second chain * @dev Token -> sToken on a first chain -> final token on a second chain * @param _stableBridgingFee Number of tokens to send to bridge (fee) * @param _externalID the metaBurn transaction that was received from the event when it was originally called metaBurn on the Synthesis contract * @param _to The address to receive tokens * @param _amount Number of tokens to unsynthesize * @param _rToken The address of the token to unsynthesize * @param _finalReceiveSide router for final call * @param _finalCalldata encoded call of a final function * @param _finalOffset offset to patch _amount to _finalCalldata */ function metaUnsynthesize( uint256 _stableBridgingFee, bytes32 _crossChainID, bytes32 _externalID, address _to, uint256 _amount, address _rToken, address _finalReceiveSide, bytes memory _finalCalldata, uint256 _finalOffset ) external onlyBridge whenNotPaused { require( unsynthesizeStates[_externalID] == UnsynthesizeState.Default, "Symb: synthetic tokens emergencyUnburn" ); balanceOf[_rToken] = balanceOf[_rToken] - _amount; unsynthesizeStates[_externalID] = UnsynthesizeState.Unsynthesized; TransferHelper.safeTransfer(_rToken, bridge, _stableBridgingFee); _amount = _amount - _stableBridgingFee; if (_finalCalldata.length == 0) { TransferHelper.safeTransfer(_rToken, _to, _amount); emit BurnCompleted(_externalID, _crossChainID, address(this), _amount, _stableBridgingFee, _rToken); return; } // transfer ERC20 tokens to MetaRouter TransferHelper.safeTransfer( _rToken, address(metaRouter), _amount ); // metaRouter call metaRouter.externalCall(_rToken, _amount, _finalReceiveSide, _finalCalldata, _finalOffset, _to); emit BurnCompleted(_externalID, _crossChainID, address(this), _amount, _stableBridgingFee, _rToken); } /** * @notice Revert burnSyntheticToken() operation * @dev Can called only by bridge after initiation on a second chain * @dev Further, this transaction also enters the relay network and is called on the other side under the method "revertBurn" * @param _stableBridgingFee Bridging fee on another network * @param _internalID the synthesize transaction that was received from the event when it was originally called burn on the Synthesize contract * @param _receiveSide Synthesis address on another network * @param _oppositeBridge Bridge address on another network * @param _chainId Chain id of the network */ function revertBurnRequest( uint256 _stableBridgingFee, bytes32 _internalID, address _receiveSide, address _oppositeBridge, uint256 _chainId, bytes32 _clientID ) external whenNotPaused { bytes32 externalID = keccak256(abi.encodePacked(_internalID, address(this), _msgSender(), block.chainid)); require( unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized, "Symb: Real tokens already transfered" ); unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest; { bytes memory out = abi.encodeWithSelector( bytes4(keccak256(bytes("revertBurn(uint256,bytes32)"))), _stableBridgingFee, externalID ); IBridge(bridge).transmitRequestV2( out, _receiveSide, _oppositeBridge, _chainId ); } emit RevertBurnRequest(_internalID, _msgSender()); emit ClientIdLog(_internalID, _clientID); } function metaRevertRequest( MetaRouteStructs.MetaRevertTransaction memory _metaRevertTransaction ) external whenNotPaused { if (_metaRevertTransaction.swapCalldata.length != 0){ bytes32 externalID = keccak256(abi.encodePacked(_metaRevertTransaction.internalID, address(this), _msgSender(), block.chainid)); require( unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized, "Symb: Real tokens already transfered" ); unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest; { bytes memory out = abi.encodeWithSelector( bytes4(keccak256(bytes("revertMetaBurn(uint256,bytes32,address,bytes,address,address,bytes)"))), _metaRevertTransaction.stableBridgingFee, externalID, _metaRevertTransaction.router, _metaRevertTransaction.swapCalldata, _metaRevertTransaction.sourceChainSynthesis, _metaRevertTransaction.burnToken, _metaRevertTransaction.burnCalldata ); IBridge(bridge).transmitRequestV2( out, _metaRevertTransaction.receiveSide, _metaRevertTransaction.managerChainBridge, _metaRevertTransaction.managerChainId ); emit RevertBurnRequest(_metaRevertTransaction.internalID, _msgSender()); emit ClientIdLog(_metaRevertTransaction.internalID, _metaRevertTransaction.clientID); } } else { if (_metaRevertTransaction.burnCalldata.length != 0){ bytes32 externalID = keccak256(abi.encodePacked(_metaRevertTransaction.internalID, address(this), _msgSender(), block.chainid)); require( unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized, "Symb: Real tokens already transfered" ); unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest; bytes memory out = abi.encodeWithSelector( bytes4(keccak256(bytes("revertBurnAndBurn(uint256,bytes32,address,address,uint256,address)"))), _metaRevertTransaction.stableBridgingFee, externalID, address(this), _metaRevertTransaction.sourceChainBridge, block.chainid, _msgSender() ); IBridge(bridge).transmitRequestV2( out, _metaRevertTransaction.sourceChainSynthesis, _metaRevertTransaction.managerChainBridge, _metaRevertTransaction.managerChainId ); emit RevertBurnRequest(_metaRevertTransaction.internalID, _msgSender()); emit ClientIdLog(_metaRevertTransaction.internalID, _metaRevertTransaction.clientID); } else { bytes memory out = abi.encodeWithSelector( bytes4(keccak256(bytes("revertSynthesizeRequestByBridge(uint256,bytes32,address,address,uint256,address,bytes32)"))), _metaRevertTransaction.stableBridgingFee, _metaRevertTransaction.internalID, _metaRevertTransaction.receiveSide, _metaRevertTransaction.sourceChainBridge, block.chainid, _msgSender(), _metaRevertTransaction.clientID ); IBridge(bridge).transmitRequestV2( out, _metaRevertTransaction.sourceChainSynthesis, _metaRevertTransaction.managerChainBridge, _metaRevertTransaction.managerChainId ); } } emit MetaRevertRequest(_metaRevertTransaction.internalID, _msgSender()); } // ** ONLYOWNER functions ** /** * @notice Set paused flag to true */ function pause() external onlyOwner { paused = true; emit Paused(_msgSender()); } /** * @notice Set paused flag to false */ function unpause() external onlyOwner { paused = false; emit Unpaused(_msgSender()); } /** * @notice Sets token to tokenWhitelist * @param _token Address of token to add to whitelist * @param _activate true - add to whitelist, false - remove from whitelist */ function setWhitelistToken(address _token, bool _activate) external onlyOwner { tokenWhitelist[_token] = _activate; emit SetWhitelistToken(_token, _activate); } /** * @notice Sets minimal price for token * @param _token Address of token to set threshold * @param _threshold threshold to set */ function setTokenThreshold(address _token, uint256 _threshold) external onlyOwner { tokenThreshold[_token] = _threshold; emit SetTokenThreshold(_token, _threshold); } /** * @notice Sets MetaRouter address * @param _metaRouter Address of metaRouter */ function setMetaRouter(IMetaRouter _metaRouter) external onlyOwner { require(address(_metaRouter) != address(0), "Symb: metaRouter cannot be zero address"); metaRouter = _metaRouter; emit SetMetaRouter(address(_metaRouter)); } /// ** INTERNAL functions ** /** * @dev Sends synthesize request * @dev Internal function used in synthesize, synthesizeNative, synthesizeWithPermit */ function sendSynthesizeRequest( uint256 _stableBridgingFee, address _token, uint256 _amount, address _chain2address, address _receiveSide, address _oppositeBridge, address _revertableAddress, uint256 _chainID, bytes32 _clientID ) internal returns (bytes32 internalID) { balanceOf[_token] = balanceOf[_token] + _amount; if (_revertableAddress == address(0)) { _revertableAddress = _chain2address; } internalID = keccak256(abi.encodePacked(this, requestCount, block.chainid)); { bytes32 externalID = keccak256(abi.encodePacked(internalID, _receiveSide, _revertableAddress, _chainID)); { bytes memory out = abi.encodeWithSelector( bytes4( keccak256( bytes( "mintSyntheticToken(uint256,bytes32,bytes32,address,uint256,uint256,address)" ) ) ), _stableBridgingFee, externalID, internalID, _token, block.chainid, _amount, _chain2address ); requests[externalID] = TxState({ recipient : _msgSender(), chain2address : _chain2address, rtoken : _token, amount : _amount, state : RequestState.Sent }); requestCount++; IBridge(bridge).transmitRequestV2( out, _receiveSide, _oppositeBridge, _chainID ); } } emit SynthesizeRequest( internalID, _msgSender(), _chainID, _revertableAddress, _chain2address, _amount, _token ); emit ClientIdLog(internalID, _clientID); } /** * @dev Sends metaSynthesizeOffchain request * @dev Internal function used in metaSynthesizeOffchain */ function sendMetaSynthesizeRequest( MetaRouteStructs.MetaSynthesizeTransaction memory _metaSynthesizeTransaction ) internal returns (bytes32 internalID) { balanceOf[_metaSynthesizeTransaction.rtoken] = balanceOf[_metaSynthesizeTransaction.rtoken] + _metaSynthesizeTransaction.amount; if (_metaSynthesizeTransaction.revertableAddress == address(0)) { _metaSynthesizeTransaction.revertableAddress = _metaSynthesizeTransaction.chain2address; } internalID = keccak256(abi.encodePacked(this, requestCount, block.chainid)); bytes32 externalID = keccak256( abi.encodePacked(internalID, _metaSynthesizeTransaction.receiveSide, _metaSynthesizeTransaction.revertableAddress, _metaSynthesizeTransaction.chainID) ); MetaRouteStructs.MetaMintTransaction memory _metaMintTransaction = MetaRouteStructs.MetaMintTransaction( _metaSynthesizeTransaction.stableBridgingFee, _metaSynthesizeTransaction.amount, internalID, externalID, _metaSynthesizeTransaction.rtoken, block.chainid, _metaSynthesizeTransaction.chain2address, _metaSynthesizeTransaction.swapTokens, _metaSynthesizeTransaction.secondDexRouter, _metaSynthesizeTransaction.secondSwapCalldata, _metaSynthesizeTransaction.finalReceiveSide, _metaSynthesizeTransaction.finalCalldata, _metaSynthesizeTransaction.finalOffset ); { bytes memory out = abi.encodeWithSignature( "metaMintSyntheticToken((uint256,uint256,bytes32,bytes32,address,uint256,address,address[]," "address,bytes,address,bytes,uint256))", _metaMintTransaction ); requests[externalID] = TxState({ recipient : _metaSynthesizeTransaction.syntCaller, chain2address : _metaSynthesizeTransaction.chain2address, rtoken : _metaSynthesizeTransaction.rtoken, amount : _metaSynthesizeTransaction.amount, state : RequestState.Sent }); requestCount++; IBridge(bridge).transmitRequestV2( out, _metaSynthesizeTransaction.receiveSide, _metaSynthesizeTransaction.oppositeBridge, _metaSynthesizeTransaction.chainID ); } emit SynthesizeRequest( internalID, _metaSynthesizeTransaction.syntCaller, _metaSynthesizeTransaction.chainID, _metaSynthesizeTransaction.revertableAddress, _metaSynthesizeTransaction.chain2address, _metaSynthesizeTransaction.amount, _metaSynthesizeTransaction.rtoken ); emit ClientIdLog(internalID, _metaSynthesizeTransaction.clientID); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract RelayRecipientUpgradeable is OwnableUpgradeable { address private _trustedForwarder; function __RelayRecipient_init(address trustedForwarder) internal onlyInitializing { __Ownable_init(); _trustedForwarder = trustedForwarder; } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } }