ETH Price: $2,550.87 (-0.39%)

Transaction Decoder

Block:
18210548 at Sep-25-2023 04:54:11 AM +UTC
Transaction Fee:
0.003951098351161 ETH $10.08
Gas Used:
491,240 Gas / 8.043112025 Gwei

Emitted Events:

79 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000e6ef6d5a8c02b156e2ae29d557d4dbb92620b295, 0x0000000000000000000000009d1a92e601db0901e69bd810029f2c14bcca3128, 00000000000000000000000000000000000000000000000000000000b280b887 )
80 FiatTokenProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x0000000000000000000000009d1a92e601db0901e69bd810029f2c14bcca3128, 0x000000000000000000000000ecc19e177d24551aa7ed6bc6fe566eca726cc8a9, 00000000000000000000000000000000000000000000000000000000b280b887 )
81 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000009d1a92e601db0901e69bd810029f2c14bcca3128, 0x000000000000000000000000ecc19e177d24551aa7ed6bc6fe566eca726cc8a9, 00000000000000000000000000000000000000000000000000000000b280b887 )
82 Pool.Swap( chainId=110, dstPoolId=1, from=StargateComposer, amountSD=2991941926, eqReward=2748526, eqFee=89843, protocolFee=2748526, lpFee=0 )
83 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000ecc19e177d24551aa7ed6bc6fe566eca726cc8a9, 0x000000000000000000000000df0770df86a8034b3efef0a1bb3c889b8332ff56, 00000000000000000000000000000000000000000000000000000000b280b887 )
84 Pool.SendCredits( dstChainId=110, dstPoolId=1, credits=0, idealBalance=14344480513574 )
85 OptimizedTransparentUpgradeableProxy.0xdf21c415b78ed2552cc9971249e32a053abce6087a0ae0fbf3f78db5174a3493( 0xdf21c415b78ed2552cc9971249e32a053abce6087a0ae0fbf3f78db5174a3493, 00000000000000000000000000000000000000000000000000026c27e8bfb2e4 )
86 UltraLightNodeV2.RelayerParams( adapterParams=0x00010000000000000000000000000000000000000000000000000000000000091438, outboundProofType=2 )
87 OptimizedTransparentUpgradeableProxy.0x4e41ee13e03cd5e0446487b524fdc48af6acf26c074dacdbdfb6b574b42c8146( 0x4e41ee13e03cd5e0446487b524fdc48af6acf26c074dacdbdfb6b574b42c8146, 000000000000000000000000000000000000000000000000000000000000006e, 0000000000000000000000000000000000000000000000000000000000000002, 000000000000000000000000000000000000000000000000000000000000000f, 000000000000000000000000296f55f8fb28e498b858d0bcda06d955b2cb3f97, 00000000000000000000000000000000000000000000000000003bea9a78e400 )
88 UltraLightNodeV2.Packet( payload=0x000000000001EADB0065296F55F8FB28E498B858D0BCDA06D955B2CB3F97006E352D8275AAE3E0C2404D9F68F6CEE084B5BEB3DD00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000668A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D0BD5AA5E2600000000000000000000000000000000000000000000000000000000B25569260000000000000000000000000000000000000000000000000000000000015EF3000000000000000000000000000000000000000000000000000000000029F06E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000029F06E00000000000000000000000000000000000000000000000000000000B2AAA8F500000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000014ECC19E177D24551AA7ED6BC6FE566ECA726CC8A900000000000000000000000000000000000000000000000000000000000000000000000000000000000000A84AB421DE52B3112D02442B040DD3DC73E8AF63B59D1A92E601DB0901E69BD810029F2C14BCCA3128000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12000000000000000000000000000000000000000000000000 )
89 Bridge.SendMsg( msgType=1, nonce=125659 )
90 WooCrossChainRouterV2.WooCrossSwapOnSrcChain( refId=171491695617613063, sender=[Sender] 0xe6ef6d5a8c02b156e2ae29d557d4dbb92620b295, to=[Sender] 0xe6ef6d5a8c02b156e2ae29d557d4dbb92620b295, fromToken=FiatTokenProxy, fromAmount=2994780295, minBridgeAmount=2994780295, realBridgeAmount=2994780295 )

Account State Difference:

  Address   Before After State Difference Code
0x4D73AdB7...401A178E2
(Layer Zero: Ultra Light Node v2)
10.506753883150553212 Eth10.50750163056837616 Eth0.000747747417822948
0x5B905fE0...FAbf76068
(LayerZero: Nonce)
0x66A71Dce...C225Cd675
(LayerZero: Ethereum Endpoint)
(beaverbuild)
19.715237722896144742 Eth19.716072830896144742 Eth0.000835108
0xA0b86991...E3606eB48
0xdf0770dF...B8332FF56
0xe6eF6d5a...92620b295
0.014376809188571358 Eth
Nonce: 155
0.00967796341958741 Eth
Nonce: 156
0.004698845768983948

Execution Trace

ETH 0.000747747417822948 WooCrossChainRouterV2.crossSwap( refId=171491695617613063, to=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, srcInfos=[{name:fromToken, type:address, order:1, indexed:false, value:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, valueString:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48}, {name:bridgeToken, type:address, order:2, indexed:false, value:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, valueString:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48}, {name:fromAmount, type:uint256, order:3, indexed:false, value:2994780295, valueString:2994780295}, {name:minBridgeAmount, type:uint256, order:4, indexed:false, value:2994780295, valueString:2994780295}], dstInfos=[{name:chainId, type:uint16, order:1, indexed:false, value:110, valueString:110}, {name:toToken, type:address, order:2, indexed:false, value:0xaf88d065e77c8cC2239327C5EDb3A432268e5831, valueString:0xaf88d065e77c8cC2239327C5EDb3A432268e5831}, {name:bridgeToken, type:address, order:3, indexed:false, value:0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8, valueString:0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8}, {name:minToAmount, type:uint256, order:4, indexed:false, value:2963176722, valueString:2963176722}, {name:airdropNativeAmount, type:uint256, order:5, indexed:false, value:0, valueString:0}] )
  • FiatTokenProxy.23b872dd( )
    • FiatTokenV2_1.transferFrom( from=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, to=0x9D1A92e601db0901e69bd810029F2C14bCCA3128, value=2994780295 ) => ( True )
    • FiatTokenProxy.70a08231( )
      • FiatTokenV2_1.balanceOf( account=0x9D1A92e601db0901e69bd810029F2C14bCCA3128 ) => ( 3249787972 )
      • FiatTokenProxy.095ea7b3( )
        • FiatTokenV2_1.approve( spender=0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9, value=2994780295 ) => ( True )
        • ETH 0.000747747417822948 StargateComposer.swap( _dstChainId=110, _srcPoolId=1, _dstPoolId=1, _refundAddress=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, _amountLD=2994780295, _minAmountLD=2964832492, _lzTxParams=[{name:dstGasForCall, type:uint256, order:1, indexed:false, value:360000, valueString:360000}, {name:dstNativeAmount, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:dstNativeAddr, type:bytes, order:3, indexed:false, value:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295, valueString:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295}], _to=0x4AB421DE52B3112D02442B040DD3DC73E8AF63B5, _payload=0x000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12 )
          • FiatTokenProxy.23b872dd( )
            • FiatTokenV2_1.transferFrom( from=0x9D1A92e601db0901e69bd810029F2C14bCCA3128, to=0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9, value=2994780295 ) => ( True )
            • ETH 0.000747747417822948 Router.swap( _dstChainId=110, _srcPoolId=1, _dstPoolId=1, _refundAddress=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, _amountLD=2994780295, _minAmountLD=2964832492, _lzTxParams=[{name:dstGasForCall, type:uint256, order:1, indexed:false, value:420000, valueString:420000}, {name:dstNativeAmount, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:dstNativeAddr, type:bytes, order:3, indexed:false, value:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295, valueString:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295}], _to=0xECC19E177D24551AA7ED6BC6FE566ECA726CC8A9, _payload=0x4AB421DE52B3112D02442B040DD3DC73E8AF63B59D1A92E601DB0901E69BD810029F2C14BCCA3128000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12 )
              • Factory.getPool( 1 ) => ( 0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56 )
              • Pool.STATICCALL( )
              • Pool.swap( _dstChainId=110, _dstPoolId=1, _from=0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9, _amountLD=2994780295, _minAmountLD=2964832492, newLiquidity=True ) => ( [{name:amount, type:uint256, order:1, indexed:false, value:2991941926, valueString:2991941926}, {name:eqFee, type:uint256, order:2, indexed:false, value:89843, valueString:89843}, {name:eqReward, type:uint256, order:3, indexed:false, value:2748526, valueString:2748526}, {name:lpFee, type:uint256, order:4, indexed:false, value:0, valueString:0}, {name:protocolFee, type:uint256, order:5, indexed:false, value:2748526, valueString:2748526}, {name:lkbRemove, type:uint256, order:6, indexed:false, value:2997528821, valueString:2997528821}] )
                • StargateFeeLibraryV07.getFees( _srcPoolId=1, _dstPoolId=1, _dstChainId=110, _from=0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9, _amountSD=2994780295 ) => ( s=[{name:amount, type:uint256, order:1, indexed:false, value:0, valueString:0}, {name:eqFee, type:uint256, order:2, indexed:false, value:89843, valueString:89843}, {name:eqReward, type:uint256, order:3, indexed:false, value:2748526, valueString:2748526}, {name:lpFee, type:uint256, order:4, indexed:false, value:0, valueString:0}, {name:protocolFee, type:uint256, order:5, indexed:false, value:2748526, valueString:2748526}, {name:lkbRemove, type:uint256, order:6, indexed:false, value:0, valueString:0}] )
                  • Factory.getPool( 1 ) => ( 0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56 )
                  • Pool.STATICCALL( )
                  • Pool.STATICCALL( )
                  • FiatTokenProxy.70a08231( )
                    • FiatTokenV2_1.balanceOf( account=0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56 ) => ( 22422283602657 )
                    • Pool.STATICCALL( )
                    • Pool.STATICCALL( )
                    • Factory.getPool( 1 ) => ( 0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56 )
                    • Pool.getChainPath( _dstChainId=110, _dstPoolId=1 ) => ( [{name:ready, type:bool, order:1, indexed:false, value:true, valueString:True}, {name:dstChainId, type:uint16, order:2, indexed:false, value:110, valueString:110}, {name:dstPoolId, type:uint256, order:3, indexed:false, value:1, valueString:1}, {name:weight, type:uint256, order:4, indexed:false, value:3252, valueString:3252}, {name:balance, type:uint256, order:5, indexed:false, value:1438359672068, valueString:1438359672068}, {name:lkb, type:uint256, order:6, indexed:false, value:6543750567353, valueString:6543750567353}, {name:credits, type:uint256, order:7, indexed:false, value:0, valueString:0}, {name:idealBalance, type:uint256, order:8, indexed:false, value:2353793873936, valueString:2353793873936}] )
                    • LPStaking.poolInfo( 0 ) => ( lpToken=0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56, allocPoint=3699, lastRewardBlock=18210501, accStargatePerShare=114712108642349213873296 )
                    • Pool.STATICCALL( )
                    • FiatTokenProxy.23b872dd( )
                      • FiatTokenV2_1.transferFrom( from=0xeCc19E177d24551aA7ed6Bc6FE566eCa726CC8a9, to=0xdf0770dF86a8034b3EFEf0A1Bb3c889B8332FF56, value=2994780295 ) => ( True )
                      • Pool.sendCredits( _dstChainId=110, _dstPoolId=1 ) => ( c=[{name:credits, type:uint256, order:1, indexed:false, value:0, valueString:0}, {name:idealBalance, type:uint256, order:2, indexed:false, value:14344480513574, valueString:14344480513574}] )
                      • ETH 0.000747747417822948 Bridge.swap( _chainId=110, _srcPoolId=1, _dstPoolId=1, _refundAddress=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, _c=[{name:credits, type:uint256, order:1, indexed:false, value:0, valueString:0}, {name:idealBalance, type:uint256, order:2, indexed:false, value:14344480513574, valueString:14344480513574}], _s=[{name:amount, type:uint256, order:1, indexed:false, value:2991941926, valueString:2991941926}, {name:eqFee, type:uint256, order:2, indexed:false, value:89843, valueString:89843}, {name:eqReward, type:uint256, order:3, indexed:false, value:2748526, valueString:2748526}, {name:lpFee, type:uint256, order:4, indexed:false, value:0, valueString:0}, {name:protocolFee, type:uint256, order:5, indexed:false, value:2748526, valueString:2748526}, {name:lkbRemove, type:uint256, order:6, indexed:false, value:2997528821, valueString:2997528821}], _lzTxParams=[{name:dstGasForCall, type:uint256, order:1, indexed:false, value:420000, valueString:420000}, {name:dstNativeAmount, type:uint256, order:2, indexed:false, value:0, valueString:0}, {name:dstNativeAddr, type:bytes, order:3, indexed:false, value:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295, valueString:0xE6EF6D5A8C02B156E2AE29D557D4DBB92620B295}], _to=0xECC19E177D24551AA7ED6BC6FE566ECA726CC8A9, _payload=0x4AB421DE52B3112D02442B040DD3DC73E8AF63B59D1A92E601DB0901E69BD810029F2C14BCCA3128000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12 )
                        • Endpoint.getOutboundNonce( _dstChainId=110, _srcAddress=0x296F55F8Fb28E498B858d0BcDA06D955B2Cb3f97 ) => ( 125658 )
                        • ETH 0.000747747417822948 Endpoint.send( _dstChainId=110, _destination=0x352D8275AAE3E0C2404D9F68F6CEE084B5BEB3DD296F55F8FB28E498B858D0BCDA06D955B2CB3F97, _payload=0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000668A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D0BD5AA5E2600000000000000000000000000000000000000000000000000000000B25569260000000000000000000000000000000000000000000000000000000000015EF3000000000000000000000000000000000000000000000000000000000029F06E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000029F06E00000000000000000000000000000000000000000000000000000000B2AAA8F500000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000014ECC19E177D24551AA7ED6BC6FE566ECA726CC8A900000000000000000000000000000000000000000000000000000000000000000000000000000000000000A84AB421DE52B3112D02442B040DD3DC73E8AF63B59D1A92E601DB0901E69BD810029F2C14BCCA3128000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12000000000000000000000000000000000000000000000000, _refundAddress=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, _zroPaymentAddress=0x296F55F8Fb28E498B858d0BcDA06D955B2Cb3f97, _adapterParams=0x00010000000000000000000000000000000000000000000000000000000000091438 )
                          • ETH 0.000747747417822948 UltraLightNodeV2.send( _ua=0x296F55F8Fb28E498B858d0BcDA06D955B2Cb3f97, 125659, _dstChainId=110, _path=0x352D8275AAE3E0C2404D9F68F6CEE084B5BEB3DD296F55F8FB28E498B858D0BCDA06D955B2CB3F97, _payload=0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000668A0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000D0BD5AA5E2600000000000000000000000000000000000000000000000000000000B25569260000000000000000000000000000000000000000000000000000000000015EF3000000000000000000000000000000000000000000000000000000000029F06E0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000029F06E00000000000000000000000000000000000000000000000000000000B2AAA8F500000000000000000000000000000000000000000000000000000000000001C000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000014ECC19E177D24551AA7ED6BC6FE566ECA726CC8A900000000000000000000000000000000000000000000000000000000000000000000000000000000000000A84AB421DE52B3112D02442B040DD3DC73E8AF63B59D1A92E601DB0901E69BD810029F2C14BCCA3128000000000000000000000000000000000000000000000000026142C9DF379D07000000000000000000000000E6EF6D5A8C02B156E2AE29D557D4DBB92620B295000000000000000000000000AF88D065E77C8CC2239327C5EDB3A432268E583100000000000000000000000000000000000000000000000000000000B09E7D12000000000000000000000000000000000000000000000000, _refundAddress=0xe6eF6d5a8c02b156e2ae29D557D4dbb92620b295, _zroPaymentAddress=0x296F55F8Fb28E498B858d0BcDA06D955B2Cb3f97, _adapterParams=0x00010000000000000000000000000000000000000000000000000000000000091438 )
                            • NonceContract.increment( _chainId=110, _ua=0x296F55F8Fb28E498B858d0BcDA06D955B2Cb3f97, _path=0x352D8275AAE3E0C2404D9F68F6CEE084B5BEB3DD296F55F8FB28E498B858D0BCDA06D955B2CB3F97 ) => ( 125659 )
                            • OptimizedTransparentUpgradeableProxy.5886ea65( )
                            • OptimizedTransparentUpgradeableProxy.c5e193cd( )
                            • TreasuryV2.getFees( payInZro=False, relayerFee=681868617822948, oracleFee=65878800000000 ) => ( 0 )
                              crossSwap[WooCrossChainRouterV2 (ln:56)]
                              File 1 of 16: WooCrossChainRouterV2
                              // SPDX-License-Identifier: MIT
                              pragma solidity =0.8.14;
                              // OpenZeppelin Contracts
                              import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
                              import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
                              import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
                              import {ICommonOFT, IOFTWithFee} from "@layerzerolabs/solidity-examples/contracts/token/oft/v2/fee/IOFTWithFee.sol";
                              // Local Contracts
                              import {IWETH} from "./interfaces/IWETH.sol";
                              import {IWooCrossChainRouterV2} from "./interfaces/IWooCrossChainRouterV2.sol";
                              import {IWooRouterV2} from "./interfaces/IWooRouterV2.sol";
                              import {IStargateEthVault} from "./interfaces/Stargate/IStargateEthVault.sol";
                              import {IStargateRouter} from "./interfaces/Stargate/IStargateRouter.sol";
                              import {ILzApp} from "./interfaces/LayerZero/ILzApp.sol";
                              import {TransferHelper} from "./libraries/TransferHelper.sol";
                              /// @title WOOFi cross chain router implementation.
                              /// @notice Router for stateless execution of cross chain swap against WOOFi private pool.
                              /// @custom:stargate-contracts https://stargateprotocol.gitbook.io/stargate/developers/contract-addresses/mainnet
                              contract WooCrossChainRouterV2 is IWooCrossChainRouterV2, Ownable, ReentrancyGuard {
                                  using EnumerableSet for EnumerableSet.AddressSet;
                                  /* ----- Constants ----- */
                                  address public constant ETH_PLACEHOLDER_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
                                  /* ----- Variables ----- */
                                  IWooRouterV2 public wooRouter;
                                  IStargateRouter public stargateRouter;
                                  address public immutable weth;
                                  uint256 public bridgeSlippage; // 1 in 10000th: default 1%
                                  uint256 public dstGasForSwapCall;
                                  uint256 public dstGasForNoSwapCall;
                                  uint16 public sgChainIdLocal; // Stargate chainId on local chain
                                  mapping(uint16 => address) public wooCrossChainRouters; // chainId => WooCrossChainRouter address
                                  mapping(uint16 => address) public sgETHs; // chainId => SGETH token address
                                  mapping(uint16 => mapping(address => uint256)) public sgPoolIds; // chainId => token address => Stargate poolId
                                  mapping(address => address) public tokenToOFTs; // token address(sgChainIdLocal) => OFT address
                                  EnumerableSet.AddressSet private directBridgeTokens;
                                  receive() external payable {}
                                  constructor(
                                      address _weth,
                                      address _wooRouter,
                                      address _stargateRouter,
                                      uint16 _sgChainIdLocal
                                  ) {
                                      wooRouter = IWooRouterV2(_wooRouter);
                                      stargateRouter = IStargateRouter(_stargateRouter);
                                      weth = _weth;
                                      bridgeSlippage = 100;
                                      dstGasForSwapCall = 360000;
                                      dstGasForNoSwapCall = 80000;
                                      sgChainIdLocal = _sgChainIdLocal;
                                      _initSgETHs();
                                      _initSgPoolIds();
                                      _initTokenToOFTs(_sgChainIdLocal);
                                  }
                                  /* ----- Functions ----- */
                                  function crossSwap(
                                      uint256 refId,
                                      address payable to,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) external payable nonReentrant {
                                      require(srcInfos.fromToken != address(0), "WooCrossChainRouterV2: !srcInfos.fromToken");
                                      require(
                                          dstInfos.toToken != address(0) && dstInfos.toToken != sgETHs[dstInfos.chainId],
                                          "WooCrossChainRouterV2: !dstInfos.toToken"
                                      );
                                      require(to != address(0), "WooCrossChainRouterV2: !to");
                                      uint256 msgValue = msg.value;
                                      uint256 bridgeAmount;
                                      {
                                          // Step 1: transfer
                                          if (srcInfos.fromToken == ETH_PLACEHOLDER_ADDR) {
                                              require(srcInfos.fromAmount <= msgValue, "WooCrossChainRouterV2: !srcInfos.fromAmount");
                                              srcInfos.fromToken = weth;
                                              IWETH(weth).deposit{value: srcInfos.fromAmount}();
                                              msgValue -= srcInfos.fromAmount;
                                          } else {
                                              TransferHelper.safeTransferFrom(srcInfos.fromToken, msg.sender, address(this), srcInfos.fromAmount);
                                          }
                                          // Step 2: local swap by WooRouter or not
                                          // 1.WOO is directBridgeToken, path(always) WOO(Arbitrum) => WOO(BSC)
                                          // 2.WOO not the directBridgeToken, path(maybe): WOO(Arbitrum) -> USDC(Arbitrum) => BUSD(BSC) -> WOO(BSC)
                                          // 3.Ethereum no WOOFi liquidity, tokens(WOO, ETH, USDC) always will be bridged directly without swap
                                          if (!directBridgeTokens.contains(srcInfos.fromToken) && srcInfos.fromToken != srcInfos.bridgeToken) {
                                              TransferHelper.safeApprove(srcInfos.fromToken, address(wooRouter), srcInfos.fromAmount);
                                              bridgeAmount = wooRouter.swap(
                                                  srcInfos.fromToken,
                                                  srcInfos.bridgeToken,
                                                  srcInfos.fromAmount,
                                                  srcInfos.minBridgeAmount,
                                                  payable(address(this)),
                                                  to
                                              );
                                          } else {
                                              require(
                                                  srcInfos.fromAmount == srcInfos.minBridgeAmount,
                                                  "WooCrossChainRouterV2: !srcInfos.minBridgeAmount"
                                              );
                                              bridgeAmount = srcInfos.fromAmount;
                                          }
                                          require(
                                              bridgeAmount <= IERC20(srcInfos.bridgeToken).balanceOf(address(this)),
                                              "WooCrossChainRouterV2: !bridgeAmount"
                                          );
                                      }
                                      // Step 3: cross chain swap by [OFT / StargateRouter]
                                      address oft = tokenToOFTs[srcInfos.bridgeToken];
                                      if (oft != address(0)) {
                                          _bridgeByOFT(refId, to, msgValue, bridgeAmount, IOFTWithFee(oft), srcInfos, dstInfos);
                                      } else {
                                          _bridgeByStargate(refId, to, msgValue, bridgeAmount, srcInfos, dstInfos);
                                      }
                                      emit WooCrossSwapOnSrcChain(
                                          refId,
                                          _msgSender(),
                                          to,
                                          srcInfos.fromToken,
                                          srcInfos.fromAmount,
                                          srcInfos.minBridgeAmount,
                                          bridgeAmount
                                      );
                                  }
                                  function onOFTReceived(
                                      uint16 srcChainId,
                                      bytes memory, // srcAddress
                                      uint64, // nonce
                                      bytes32 from,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external {
                                      require(_isLegitOFT(_msgSender()), "WooCrossChainRouterV2: INVALID_CALLER");
                                      require(
                                          wooCrossChainRouters[srcChainId] == address(uint160(uint256(from))),
                                          "WooCrossChainRouterV2: INVALID_FROM"
                                      );
                                      // _msgSender() should be OFT address if requires above are passed
                                      address bridgedToken = IOFTWithFee(_msgSender()).token();
                                      // make sure the same order to abi.encode when decode payload
                                      (uint256 refId, address to, address toToken, uint256 minToAmount) = abi.decode(
                                          payload,
                                          (uint256, address, address, uint256)
                                      );
                                      _handleERC20Received(refId, to, toToken, bridgedToken, amountLD, minToAmount);
                                  }
                                  function sgReceive(
                                      uint16, // srcChainId
                                      bytes memory, // srcAddress
                                      uint256, // nonce
                                      address bridgedToken,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external {
                                      require(msg.sender == address(stargateRouter), "WooCrossChainRouterV2: INVALID_CALLER");
                                      // make sure the same order to abi.encode when decode payload
                                      (uint256 refId, address to, address toToken, uint256 minToAmount) = abi.decode(
                                          payload,
                                          (uint256, address, address, uint256)
                                      );
                                      // toToken won't be SGETH, and bridgedToken won't be ETH_PLACEHOLDER_ADDR
                                      if (bridgedToken == sgETHs[sgChainIdLocal]) {
                                          // bridgedToken is SGETH, received native token
                                          _handleNativeReceived(refId, to, toToken, amountLD, minToAmount);
                                      } else {
                                          // bridgedToken is not SGETH, received ERC20 token
                                          _handleERC20Received(refId, to, toToken, bridgedToken, amountLD, minToAmount);
                                      }
                                  }
                                  function quoteLayerZeroFee(
                                      uint256 refId,
                                      address to,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) external view returns (uint256, uint256) {
                                      bytes memory payload = abi.encode(refId, to, dstInfos.toToken, dstInfos.minToAmount);
                                      address oft = tokenToOFTs[srcInfos.bridgeToken];
                                      if (oft != address(0)) {
                                          // bridge via OFT if it's OFT
                                          uint256 dstGasForCall = _getDstGasForCall(dstInfos);
                                          bytes memory adapterParams = _getAdapterParams(to, oft, dstGasForCall, dstInfos);
                                          bool useZro = false;
                                          bytes32 dstWooCrossChainRouter = bytes32(uint256(uint160(wooCrossChainRouters[dstInfos.chainId])));
                                          return
                                              IOFTWithFee(oft).estimateSendAndCallFee(
                                                  dstInfos.chainId,
                                                  dstWooCrossChainRouter,
                                                  srcInfos.minBridgeAmount,
                                                  payload,
                                                  uint64(dstGasForCall),
                                                  useZro,
                                                  adapterParams
                                              );
                                      } else {
                                          // otherwise bridge via Stargate
                                          IStargateRouter.lzTxObj memory obj = _getLzTxObj(to, dstInfos);
                                          return
                                              stargateRouter.quoteLayerZeroFee(
                                                  dstInfos.chainId,
                                                  1, // https://stargateprotocol.gitbook.io/stargate/developers/function-types
                                                  obj.dstNativeAddr,
                                                  payload,
                                                  obj
                                              );
                                      }
                                  }
                                  function allDirectBridgeTokens() external view returns (address[] memory) {
                                      uint256 length = directBridgeTokens.length();
                                      address[] memory tokens = new address[](length);
                                      unchecked {
                                          for (uint256 i = 0; i < length; ++i) {
                                              tokens[i] = directBridgeTokens.at(i);
                                          }
                                      }
                                      return tokens;
                                  }
                                  function allDirectBridgeTokensLength() external view returns (uint256) {
                                      return directBridgeTokens.length();
                                  }
                                  function _initSgETHs() internal {
                                      // Ethereum
                                      sgETHs[101] = 0x72E2F4830b9E45d52F80aC08CB2bEC0FeF72eD9c;
                                      // Arbitrum
                                      sgETHs[110] = 0x82CbeCF39bEe528B5476FE6d1550af59a9dB6Fc0;
                                      // Optimism
                                      sgETHs[111] = 0xb69c8CBCD90A39D8D3d3ccf0a3E968511C3856A0;
                                  }
                                  function _initSgPoolIds() internal {
                                      // poolId > 0 means able to be bridge token
                                      // Ethereum
                                      sgPoolIds[101][0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = 1; // USDC
                                      sgPoolIds[101][0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2] = 13; // WETH
                                      sgPoolIds[101][0x4691937a7508860F876c9c0a2a617E7d9E945D4B] = 20; // WOO
                                      // BNB Chain
                                      sgPoolIds[102][0x55d398326f99059fF775485246999027B3197955] = 2; // USDT
                                      sgPoolIds[102][0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56] = 5; // BUSD
                                      sgPoolIds[102][0x4691937a7508860F876c9c0a2a617E7d9E945D4B] = 20; // WOO
                                      // Avalanche
                                      sgPoolIds[106][0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E] = 1; // USDC
                                      sgPoolIds[106][0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7] = 2; // USDT
                                      sgPoolIds[106][0xaBC9547B534519fF73921b1FBA6E672b5f58D083] = 20; // WOO
                                      // Polygon
                                      sgPoolIds[109][0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174] = 1; // USDC
                                      sgPoolIds[109][0xc2132D05D31c914a87C6611C10748AEb04B58e8F] = 2; // USDT
                                      sgPoolIds[109][0x1B815d120B3eF02039Ee11dC2d33DE7aA4a8C603] = 20; // WOO
                                      // Arbitrum
                                      sgPoolIds[110][0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8] = 1; // USDC
                                      sgPoolIds[110][0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9] = 2; // USDT
                                      sgPoolIds[110][0x82aF49447D8a07e3bd95BD0d56f35241523fBab1] = 13; // WETH
                                      sgPoolIds[110][0xcAFcD85D8ca7Ad1e1C6F82F651fA15E33AEfD07b] = 20; // WOO
                                      // Optimism
                                      sgPoolIds[111][0x7F5c764cBc14f9669B88837ca1490cCa17c31607] = 1; // USDC
                                      sgPoolIds[111][0x4200000000000000000000000000000000000006] = 13; // WETH
                                      sgPoolIds[111][0x871f2F2ff935FD1eD867842FF2a7bfD051A5E527] = 20; // WOO
                                      // Fantom
                                      sgPoolIds[112][0x04068DA6C83AFCFA0e13ba15A6696662335D5B75] = 1; // USDC
                                      sgPoolIds[112][0x6626c47c00F1D87902fc13EECfaC3ed06D5E8D8a] = 20; // WOO
                                  }
                                  function _initTokenToOFTs(uint16 _sgChainIdLocal) internal {
                                      address btcbOFT = 0x2297aEbD383787A160DD0d9F71508148769342E3; // BTCbOFT && BTCbProxyOFT
                                      if (_sgChainIdLocal == 106) {
                                          // BTC.b(ERC20) on Avalanche address
                                          tokenToOFTs[0x152b9d0FdC40C096757F570A51E494bd4b943E50] = btcbOFT;
                                      }
                                      tokenToOFTs[btcbOFT] = btcbOFT;
                                  }
                                  function _getDstGasForCall(DstInfos memory dstInfos) internal view returns (uint256) {
                                      return (dstInfos.toToken == dstInfos.bridgeToken) ? dstGasForNoSwapCall : dstGasForSwapCall;
                                  }
                                  function _getAdapterParams(
                                      address to,
                                      address oft,
                                      uint256 dstGasForCall,
                                      DstInfos memory dstInfos
                                  ) internal view returns (bytes memory) {
                                      // OFT src logic: require(providedGasLimit >= minGasLimit)
                                      // uint256 minGasLimit = minDstGasLookup[_dstChainId][_type] + dstGasForCall;
                                      // _type: 0(send), 1(send_and_call)
                                      uint256 providedGasLimit = ILzApp(oft).minDstGasLookup(dstInfos.chainId, 1) + dstGasForCall;
                                      // https://layerzero.gitbook.io/docs/evm-guides/advanced/relayer-adapter-parameters#airdrop
                                      return
                                          abi.encodePacked(
                                              uint16(2), // version: 2 is able to airdrop native token on destination but 1 is not
                                              providedGasLimit, // gasAmount: destination transaction gas for LayerZero to delivers
                                              dstInfos.airdropNativeAmount, // nativeForDst: airdrop native token amount
                                              to // addressOnDst: address to receive airdrop native token on destination
                                          );
                                  }
                                  function _getLzTxObj(address to, DstInfos memory dstInfos) internal view returns (IStargateRouter.lzTxObj memory) {
                                      uint256 dstGasForCall = _getDstGasForCall(dstInfos);
                                      return IStargateRouter.lzTxObj(dstGasForCall, dstInfos.airdropNativeAmount, abi.encodePacked(to));
                                  }
                                  function _isLegitOFT(address caller) internal view returns (bool) {
                                      return tokenToOFTs[caller] != address(0);
                                  }
                                  function _bridgeByOFT(
                                      uint256 refId,
                                      address payable to,
                                      uint256 msgValue,
                                      uint256 bridgeAmount,
                                      IOFTWithFee oft,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) internal {
                                      {
                                          address token = oft.token();
                                          require(token == srcInfos.bridgeToken, "WooCrossChainRouterV2: !token");
                                          if (token != address(oft)) {
                                              // oft.token() != address(oft) means is a ProxyOFT
                                              // for example: BTC.b on Avalanche is ERC20, need BTCbProxyOFT to lock up BTC.b
                                              TransferHelper.safeApprove(srcInfos.bridgeToken, address(oft), bridgeAmount);
                                          }
                                      }
                                      // OFT src logic: require(_removeDust(bridgeAmount) >= minAmount)
                                      uint256 minAmount = (bridgeAmount * (10000 - bridgeSlippage)) / 10000;
                                      bytes memory payload = abi.encode(refId, to, dstInfos.toToken, dstInfos.minToAmount);
                                      uint256 dstGasForCall = _getDstGasForCall(dstInfos);
                                      ICommonOFT.LzCallParams memory callParams;
                                      {
                                          bytes memory adapterParams = _getAdapterParams(to, address(oft), dstGasForCall, dstInfos);
                                          callParams = ICommonOFT.LzCallParams(
                                              payable(msg.sender), // refundAddress
                                              address(0), // zroPaymentAddress
                                              adapterParams //adapterParams
                                          );
                                      }
                                      bytes32 dstWooCrossChainRouter = bytes32(uint256(uint160(wooCrossChainRouters[dstInfos.chainId])));
                                      oft.sendAndCall{value: msgValue}(
                                          address(this),
                                          dstInfos.chainId,
                                          dstWooCrossChainRouter,
                                          bridgeAmount,
                                          minAmount,
                                          payload,
                                          uint64(dstGasForCall),
                                          callParams
                                      );
                                  }
                                  function _bridgeByStargate(
                                      uint256 refId,
                                      address payable to,
                                      uint256 msgValue,
                                      uint256 bridgeAmount,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) internal {
                                      uint256 srcPoolId = sgPoolIds[sgChainIdLocal][srcInfos.bridgeToken];
                                      require(srcPoolId > 0, "WooCrossChainRouterV2: !srcInfos.bridgeToken");
                                      uint256 dstPoolId = sgPoolIds[dstInfos.chainId][dstInfos.bridgeToken];
                                      require(dstPoolId > 0, "WooCrossChainRouterV2: !dstInfos.bridgeToken");
                                      bytes memory payload = abi.encode(refId, to, dstInfos.toToken, dstInfos.minToAmount);
                                      uint256 dstMinBridgeAmount = (bridgeAmount * (10000 - bridgeSlippage)) / 10000;
                                      bytes memory dstWooCrossChainRouter = abi.encodePacked(wooCrossChainRouters[dstInfos.chainId]);
                                      IStargateRouter.lzTxObj memory obj = _getLzTxObj(to, dstInfos);
                                      if (srcInfos.bridgeToken == weth) {
                                          IWETH(weth).withdraw(bridgeAmount);
                                          address sgETH = sgETHs[sgChainIdLocal];
                                          IStargateEthVault(sgETH).deposit{value: bridgeAmount}(); // logic from Stargate RouterETH.sol
                                          TransferHelper.safeApprove(sgETH, address(stargateRouter), bridgeAmount);
                                      } else {
                                          TransferHelper.safeApprove(srcInfos.bridgeToken, address(stargateRouter), bridgeAmount);
                                      }
                                      stargateRouter.swap{value: msgValue}(
                                          dstInfos.chainId, // dst chain id
                                          srcPoolId, // bridge token's pool id on src chain
                                          dstPoolId, // bridge token's pool id on dst chain
                                          payable(_msgSender()), // rebate address
                                          bridgeAmount, // swap amount on src chain
                                          dstMinBridgeAmount, // min received amount on dst chain
                                          obj, // config: dstGasForCall, dstAirdropNativeAmount, dstReceiveAirdropNativeTokenAddr
                                          dstWooCrossChainRouter, // smart contract to call on dst chain
                                          payload // payload to piggyback
                                      );
                                  }
                                  function _handleNativeReceived(
                                      uint256 refId,
                                      address to,
                                      address toToken,
                                      uint256 bridgedAmount,
                                      uint256 minToAmount
                                  ) internal {
                                      address msgSender = _msgSender();
                                      if (toToken == ETH_PLACEHOLDER_ADDR) {
                                          TransferHelper.safeTransferETH(to, bridgedAmount);
                                          emit WooCrossSwapOnDstChain(
                                              refId,
                                              msgSender,
                                              to,
                                              weth,
                                              bridgedAmount,
                                              toToken,
                                              ETH_PLACEHOLDER_ADDR,
                                              minToAmount,
                                              bridgedAmount
                                          );
                                      } else {
                                          try
                                              wooRouter.swap{value: bridgedAmount}(
                                                  ETH_PLACEHOLDER_ADDR,
                                                  toToken,
                                                  bridgedAmount,
                                                  minToAmount,
                                                  payable(to),
                                                  to
                                              )
                                          returns (uint256 realToAmount) {
                                              emit WooCrossSwapOnDstChain(
                                                  refId,
                                                  msgSender,
                                                  to,
                                                  weth,
                                                  bridgedAmount,
                                                  toToken,
                                                  toToken,
                                                  minToAmount,
                                                  realToAmount
                                              );
                                          } catch {
                                              TransferHelper.safeTransferETH(to, bridgedAmount);
                                              emit WooCrossSwapOnDstChain(
                                                  refId,
                                                  msgSender,
                                                  to,
                                                  weth,
                                                  bridgedAmount,
                                                  toToken,
                                                  ETH_PLACEHOLDER_ADDR,
                                                  minToAmount,
                                                  bridgedAmount
                                              );
                                          }
                                      }
                                  }
                                  function _handleERC20Received(
                                      uint256 refId,
                                      address to,
                                      address toToken,
                                      address bridgedToken,
                                      uint256 bridgedAmount,
                                      uint256 minToAmount
                                  ) internal {
                                      address msgSender = _msgSender();
                                      if (toToken == bridgedToken) {
                                          TransferHelper.safeTransfer(bridgedToken, to, bridgedAmount);
                                          emit WooCrossSwapOnDstChain(
                                              refId,
                                              msgSender,
                                              to,
                                              bridgedToken,
                                              bridgedAmount,
                                              toToken,
                                              toToken,
                                              minToAmount,
                                              bridgedAmount
                                          );
                                      } else {
                                          TransferHelper.safeApprove(bridgedToken, address(wooRouter), bridgedAmount);
                                          try wooRouter.swap(bridgedToken, toToken, bridgedAmount, minToAmount, payable(to), to) returns (
                                              uint256 realToAmount
                                          ) {
                                              emit WooCrossSwapOnDstChain(
                                                  refId,
                                                  msgSender,
                                                  to,
                                                  bridgedToken,
                                                  bridgedAmount,
                                                  toToken,
                                                  toToken,
                                                  minToAmount,
                                                  realToAmount
                                              );
                                          } catch {
                                              TransferHelper.safeTransfer(bridgedToken, to, bridgedAmount);
                                              emit WooCrossSwapOnDstChain(
                                                  refId,
                                                  msgSender,
                                                  to,
                                                  bridgedToken,
                                                  bridgedAmount,
                                                  toToken,
                                                  bridgedToken,
                                                  minToAmount,
                                                  bridgedAmount
                                              );
                                          }
                                      }
                                  }
                                  /* ----- Owner & Admin Functions ----- */
                                  function setWooRouter(address _wooRouter) external onlyOwner {
                                      require(_wooRouter != address(0), "WooCrossChainRouterV2: !_wooRouter");
                                      wooRouter = IWooRouterV2(_wooRouter);
                                  }
                                  function setStargateRouter(address _stargateRouter) external onlyOwner {
                                      require(_stargateRouter != address(0), "WooCrossChainRouterV2: !_stargateRouter");
                                      stargateRouter = IStargateRouter(_stargateRouter);
                                  }
                                  function setBridgeSlippage(uint256 _bridgeSlippage) external onlyOwner {
                                      require(_bridgeSlippage <= 10000, "WooCrossChainRouterV2: !_bridgeSlippage");
                                      bridgeSlippage = _bridgeSlippage;
                                  }
                                  function setDstGasForSwapCall(uint256 _dstGasForSwapCall) external onlyOwner {
                                      dstGasForSwapCall = _dstGasForSwapCall;
                                  }
                                  function setDstGasForNoSwapCall(uint256 _dstGasForNoSwapCall) external onlyOwner {
                                      dstGasForNoSwapCall = _dstGasForNoSwapCall;
                                  }
                                  function setSgChainIdLocal(uint16 _sgChainIdLocal) external onlyOwner {
                                      sgChainIdLocal = _sgChainIdLocal;
                                  }
                                  function setWooCrossChainRouter(uint16 chainId, address wooCrossChainRouter) external onlyOwner {
                                      require(wooCrossChainRouter != address(0), "WooCrossChainRouterV2: !wooCrossChainRouter");
                                      wooCrossChainRouters[chainId] = wooCrossChainRouter;
                                  }
                                  function setSgETH(uint16 chainId, address token) external onlyOwner {
                                      require(token != address(0), "WooCrossChainRouterV2: !token");
                                      sgETHs[chainId] = token;
                                  }
                                  function setSgPoolId(
                                      uint16 chainId,
                                      address token,
                                      uint256 poolId
                                  ) external onlyOwner {
                                      sgPoolIds[chainId][token] = poolId;
                                  }
                                  function setTokenToOFT(address token, address oft) external onlyOwner {
                                      tokenToOFTs[token] = oft;
                                  }
                                  function addDirectBridgeToken(address token) external onlyOwner {
                                      bool success = directBridgeTokens.add(token);
                                      require(success, "WooCrossChainRouterV2: token exist");
                                  }
                                  function removeDirectBridgeToken(address token) external onlyOwner {
                                      bool success = directBridgeTokens.remove(token);
                                      require(success, "WooCrossChainRouterV2: token not exist");
                                  }
                                  function inCaseTokenGotStuck(address stuckToken) external onlyOwner {
                                      if (stuckToken == ETH_PLACEHOLDER_ADDR) {
                                          TransferHelper.safeTransferETH(msg.sender, address(this).balance);
                                      } else {
                                          uint256 amount = IERC20(stuckToken).balanceOf(address(this));
                                          TransferHelper.safeTransfer(stuckToken, msg.sender, amount);
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              /// @title Wrapped ETH.
                              interface IWETH {
                                  /// @dev Deposit ETH into WETH
                                  function deposit() external payable;
                                  /// @dev Transfer WETH to receiver
                                  /// @param to address of WETH receiver
                                  /// @param value amount of WETH to transfer
                                  /// @return get true when succeed, else false
                                  function transfer(address to, uint256 value) external returns (bool);
                                  /// @dev Withdraw WETH to ETH
                                  function withdraw(uint256) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity =0.8.14;
                              /*
                              ░██╗░░░░░░░██╗░█████╗░░█████╗░░░░░░░███████╗██╗
                              ░██║░░██╗░░██║██╔══██╗██╔══██╗░░░░░░██╔════╝██║
                              ░╚██╗████╗██╔╝██║░░██║██║░░██║█████╗█████╗░░██║
                              ░░████╔═████║░██║░░██║██║░░██║╚════╝██╔══╝░░██║
                              ░░╚██╔╝░╚██╔╝░╚█████╔╝╚█████╔╝░░░░░░██║░░░░░██║
                              ░░░╚═╝░░░╚═╝░░░╚════╝░░╚════╝░░░░░░░╚═╝░░░░░╚═╝
                              *
                              * MIT License
                              * ===========
                              *
                              * Copyright (c) 2020 WooTrade
                              *
                              * Permission is hereby granted, free of charge, to any person obtaining a copy
                              * of this software and associated documentation files (the "Software"), to deal
                              * in the Software without restriction, including without limitation the rights
                              * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                              * copies of the Software, and to permit persons to whom the Software is
                              * furnished to do so, subject to the following conditions:
                              *
                              * The above copyright notice and this permission notice shall be included in all
                              * copies or substantial portions of the Software.
                              *
                              * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                              * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                              * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                              * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                              * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                              * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                              */
                              /// @title WOOFi cross chain router interface (version 2).
                              /// @notice functions to interface with WOOFi cross chain swap.
                              interface IWooCrossChainRouterV2 {
                                  /* ----- Structs ----- */
                                  struct SrcInfos {
                                      address fromToken;
                                      address bridgeToken;
                                      uint256 fromAmount;
                                      uint256 minBridgeAmount;
                                  }
                                  struct DstInfos {
                                      uint16 chainId;
                                      address toToken;
                                      address bridgeToken;
                                      uint256 minToAmount;
                                      uint256 airdropNativeAmount;
                                  }
                                  /* ----- Events ----- */
                                  event WooCrossSwapOnSrcChain(
                                      uint256 indexed refId,
                                      address indexed sender,
                                      address indexed to,
                                      address fromToken,
                                      uint256 fromAmount,
                                      uint256 minBridgeAmount,
                                      uint256 realBridgeAmount
                                  );
                                  event WooCrossSwapOnDstChain(
                                      uint256 indexed refId,
                                      address indexed sender,
                                      address indexed to,
                                      address bridgedToken,
                                      uint256 bridgedAmount,
                                      address toToken,
                                      address realToToken,
                                      uint256 minToAmount,
                                      uint256 realToAmount
                                  );
                                  /* ----- State Variables ----- */
                                  function weth() external view returns (address);
                                  function bridgeSlippage() external view returns (uint256);
                                  function dstGasForSwapCall() external view returns (uint256);
                                  function dstGasForNoSwapCall() external view returns (uint256);
                                  function sgChainIdLocal() external view returns (uint16);
                                  function wooCrossChainRouters(uint16 chainId) external view returns (address wooCrossChainRouter);
                                  function sgETHs(uint16 chainId) external view returns (address sgETH);
                                  function sgPoolIds(uint16 chainId, address token) external view returns (uint256 poolId);
                                  /* ----- Functions ----- */
                                  function crossSwap(
                                      uint256 refId,
                                      address payable to,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) external payable;
                                  function sgReceive(
                                      uint16 srcChainId,
                                      bytes memory srcAddress,
                                      uint256 nonce,
                                      address bridgedToken,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external;
                                  function quoteLayerZeroFee(
                                      uint256 refId,
                                      address to,
                                      SrcInfos memory srcInfos,
                                      DstInfos memory dstInfos
                                  ) external view returns (uint256 nativeAmount, uint256 zroAmount);
                                  function allDirectBridgeTokens() external view returns (address[] memory tokens);
                                  function allDirectBridgeTokensLength() external view returns (uint256 length);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity =0.8.14;
                              /*
                              ░██╗░░░░░░░██╗░█████╗░░█████╗░░░░░░░███████╗██╗
                              ░██║░░██╗░░██║██╔══██╗██╔══██╗░░░░░░██╔════╝██║
                              ░╚██╗████╗██╔╝██║░░██║██║░░██║█████╗█████╗░░██║
                              ░░████╔═████║░██║░░██║██║░░██║╚════╝██╔══╝░░██║
                              ░░╚██╔╝░╚██╔╝░╚█████╔╝╚█████╔╝░░░░░░██║░░░░░██║
                              ░░░╚═╝░░░╚═╝░░░╚════╝░░╚════╝░░░░░░░╚═╝░░░░░╚═╝
                              *
                              * MIT License
                              * ===========
                              *
                              * Copyright (c) 2020 WooTrade
                              *
                              * Permission is hereby granted, free of charge, to any person obtaining a copy
                              * of this software and associated documentation files (the "Software"), to deal
                              * in the Software without restriction, including without limitation the rights
                              * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                              * copies of the Software, and to permit persons to whom the Software is
                              * furnished to do so, subject to the following conditions:
                              *
                              * The above copyright notice and this permission notice shall be included in all
                              * copies or substantial portions of the Software.
                              *
                              * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                              * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                              * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                              * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                              * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                              * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                              */
                              import "../interfaces/IWooPPV2.sol";
                              /// @title Woo router interface (version 2)
                              /// @notice functions to interface with WooFi swap
                              interface IWooRouterV2 {
                                  /* ----- Type declarations ----- */
                                  enum SwapType {
                                      WooSwap,
                                      DodoSwap
                                  }
                                  /* ----- Events ----- */
                                  event WooRouterSwap(
                                      SwapType swapType,
                                      address indexed fromToken,
                                      address indexed toToken,
                                      uint256 fromAmount,
                                      uint256 toAmount,
                                      address from,
                                      address indexed to,
                                      address rebateTo
                                  );
                                  event WooPoolChanged(address newPool);
                                  /* ----- Router properties ----- */
                                  function WETH() external view returns (address);
                                  function wooPool() external view returns (IWooPPV2);
                                  /* ----- Main query & swap APIs ----- */
                                  /// @notice query the amount to swap fromToken -> toToken
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of fromToken to swap
                                  /// @return toAmount the predicted amount to receive
                                  function querySwap(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount
                                  ) external view returns (uint256 toAmount);
                                  /// @notice query the amount to swap fromToken -> toToken,
                                  ///     WITHOUT checking the reserve balance; so it
                                  ///     always returns the quoted amount (for reference).
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of fromToken to swap
                                  /// @return toAmount the predicted amount to receive
                                  function tryQuerySwap(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount
                                  ) external view returns (uint256 toAmount);
                                  /// @notice Swap `fromToken` to `toToken`.
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of `fromToken` to swap
                                  /// @param minToAmount the minimum amount of `toToken` to receive
                                  /// @param to the destination address
                                  /// @param rebateTo the rebate address (optional, can be 0)
                                  /// @return realToAmount the amount of toToken to receive
                                  function swap(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount,
                                      uint256 minToAmount,
                                      address payable to,
                                      address rebateTo
                                  ) external payable returns (uint256 realToAmount);
                                  /* ----- 3rd party DEX swap ----- */
                                  /// @notice swap fromToken -> toToken via an external 3rd swap
                                  /// @param approveTarget the contract address for token transfer approval
                                  /// @param swapTarget the contract address for swap
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of fromToken to swap
                                  /// @param minToAmount the min amount of swapped toToken
                                  /// @param to the destination address
                                  /// @param data call data for external call
                                  function externalSwap(
                                      address approveTarget,
                                      address swapTarget,
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount,
                                      uint256 minToAmount,
                                      address payable to,
                                      bytes calldata data
                                  ) external payable returns (uint256 realToAmount);
                              }
                              // SPDX-License-Identifier: GPL-3.0-or-later
                              pragma solidity ^0.8.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: MIT
                              pragma solidity ^0.8.0;
                              interface IStargateEthVault {
                                  function deposit() external payable;
                                  function transfer(address to, uint256 value) external returns (bool);
                                  function withdraw(uint256) external;
                                  function approve(address guy, uint256 wad) external returns (bool);
                                  function transferFrom(
                                      address src,
                                      address dst,
                                      uint256 wad
                                  ) external returns (bool);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              interface IStargateRouter {
                                  struct lzTxObj {
                                      uint256 dstGasForCall;
                                      uint256 dstNativeAmount;
                                      bytes dstNativeAddr;
                                  }
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external;
                                  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;
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external returns (uint256);
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable;
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              /**
                               * @dev Interface of the LzApp that functions not exist in the @layerzerolabs package
                               */
                              interface ILzApp {
                                  function minDstGasLookup(uint16 _dstChainId, uint16 _type) external view returns (uint256 _minGasLimit);
                              }
                              // 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 (security/ReentrancyGuard.sol)
                              pragma solidity ^0.8.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor() {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and making it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // 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;
                                  }
                              }
                              // 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) (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.5.0;
                              import "../ICommonOFT.sol";
                              /**
                               * @dev Interface of the IOFT core standard
                               */
                              interface IOFTWithFee is ICommonOFT {
                                  /**
                                   * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from`
                                   * `_from` the owner of token
                                   * `_dstChainId` the destination chain identifier
                                   * `_toAddress` can be any size depending on the `dstChainId`.
                                   * `_amount` the quantity of tokens in wei
                                   * `_minAmount` the minimum amount of tokens to receive on dstChain
                                   * `_refundAddress` the address LayerZero refunds if too much message fee is sent
                                   * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token)
                                   * `_adapterParams` is a flexible bytes array to indicate messaging adapter services
                                   */
                                  function sendFrom(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, uint _minAmount, LzCallParams calldata _callParams) external payable;
                                  function sendAndCall(address _from, uint16 _dstChainId, bytes32 _toAddress, uint _amount, uint _minAmount, bytes calldata _payload, uint64 _dstGasForCall, LzCallParams calldata _callParams) external payable;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity =0.8.14;
                              /*
                              ░██╗░░░░░░░██╗░█████╗░░█████╗░░░░░░░███████╗██╗
                              ░██║░░██╗░░██║██╔══██╗██╔══██╗░░░░░░██╔════╝██║
                              ░╚██╗████╗██╔╝██║░░██║██║░░██║█████╗█████╗░░██║
                              ░░████╔═████║░██║░░██║██║░░██║╚════╝██╔══╝░░██║
                              ░░╚██╔╝░╚██╔╝░╚█████╔╝╚█████╔╝░░░░░░██║░░░░░██║
                              ░░░╚═╝░░░╚═╝░░░╚════╝░░╚════╝░░░░░░░╚═╝░░░░░╚═╝
                              *
                              * MIT License
                              * ===========
                              *
                              * Copyright (c) 2020 WooTrade
                              *
                              * Permission is hereby granted, free of charge, to any person obtaining a copy
                              * of this software and associated documentation files (the "Software"), to deal
                              * in the Software without restriction, including without limitation the rights
                              * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                              * copies of the Software, and to permit persons to whom the Software is
                              * furnished to do so, subject to the following conditions:
                              *
                              * The above copyright notice and this permission notice shall be included in all
                              * copies or substantial portions of the Software.
                              *
                              * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                              * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                              * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                              * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                              * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                              * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                              */
                              /// @title Woo private pool for swap.
                              /// @notice Use this contract to directly interfact with woo's synthetic proactive
                              ///         marketing making pool.
                              /// @author woo.network
                              interface IWooPPV2 {
                                  /* ----- Events ----- */
                                  event Deposit(address indexed token, address indexed sender, uint256 amount);
                                  event Withdraw(address indexed token, address indexed receiver, uint256 amount);
                                  event Migrate(address indexed token, address indexed receiver, uint256 amount);
                                  event AdminUpdated(address indexed addr, bool flag);
                                  event FeeAddrUpdated(address indexed newFeeAddr);
                                  event WooracleUpdated(address indexed newWooracle);
                                  event WooSwap(
                                      address indexed fromToken,
                                      address indexed toToken,
                                      uint256 fromAmount,
                                      uint256 toAmount,
                                      address from,
                                      address indexed to,
                                      address rebateTo,
                                      uint256 swapVol,
                                      uint256 swapFee
                                  );
                                  /* ----- External Functions ----- */
                                  /// @notice The quote token address (immutable).
                                  /// @return address of quote token
                                  function quoteToken() external view returns (address);
                                  /// @notice Gets the pool size of the specified token (swap liquidity).
                                  /// @param token the token address
                                  /// @return the pool size
                                  function poolSize(address token) external view returns (uint256);
                                  /// @notice Query the amount to swap `fromToken` to `toToken`, without checking the pool reserve balance.
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of `fromToken` to swap
                                  /// @return toAmount the swapped amount of `toToken`
                                  function tryQuery(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount
                                  ) external view returns (uint256 toAmount);
                                  /// @notice Query the amount to swap `fromToken` to `toToken`, with checking the pool reserve balance.
                                  /// @dev tx reverts when 'toToken' balance is insufficient.
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of `fromToken` to swap
                                  /// @return toAmount the swapped amount of `toToken`
                                  function query(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount
                                  ) external view returns (uint256 toAmount);
                                  /// @notice Swap `fromToken` to `toToken`.
                                  /// @param fromToken the from token
                                  /// @param toToken the to token
                                  /// @param fromAmount the amount of `fromToken` to swap
                                  /// @param minToAmount the minimum amount of `toToken` to receive
                                  /// @param to the destination address
                                  /// @param rebateTo the rebate address (optional, can be address ZERO)
                                  /// @return realToAmount the amount of toToken to receive
                                  function swap(
                                      address fromToken,
                                      address toToken,
                                      uint256 fromAmount,
                                      uint256 minToAmount,
                                      address to,
                                      address rebateTo
                                  ) external returns (uint256 realToAmount);
                                  /// @notice Deposit the specified token into the liquidity pool of WooPPV2.
                                  /// @param token the token to deposit
                                  /// @param amount the deposit amount
                                  function deposit(address token, uint256 amount) 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
                              pragma solidity >=0.5.0;
                              import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
                              /**
                               * @dev Interface of the IOFT core standard
                               */
                              interface ICommonOFT is IERC165 {
                                  struct LzCallParams {
                                      address payable refundAddress;
                                      address zroPaymentAddress;
                                      bytes adapterParams;
                                  }
                                  /**
                                   * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`)
                                   * _dstChainId - L0 defined chain id to send tokens too
                                   * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain
                                   * _amount - amount of the tokens to transfer
                                   * _useZro - indicates to use zro to pay L0 fees
                                   * _adapterParam - flexible bytes array to indicate messaging adapter services in L0
                                   */
                                  function estimateSendFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
                                  function estimateSendAndCallFee(uint16 _dstChainId, bytes32 _toAddress, uint _amount, bytes calldata _payload, uint64 _dstGasForCall, bool _useZro, bytes calldata _adapterParams) external view returns (uint nativeFee, uint zroFee);
                                  /**
                                   * @dev returns the circulating amount of tokens on current chain
                                   */
                                  function circulatingSupply() external view returns (uint);
                                  /**
                                   * @dev returns the address of the ERC20 token
                                   */
                                  function token() external view returns (address);
                              }
                              // 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);
                              }
                              

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

                              File 3 of 16: Pool
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./LPTokenERC20.sol";
                              import "./interfaces/IStargateFeeLibrary.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              /// Pool contracts on other chains and managed by the Stargate protocol.
                              contract Pool is LPTokenERC20, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 public constant BP_DENOMINATOR = 10000;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct ChainPath {
                                      bool ready; // indicate if the counter chainPath has been created.
                                      uint16 dstChainId;
                                      uint256 dstPoolId;
                                      uint256 weight;
                                      uint256 balance;
                                      uint256 lkb;
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  struct SwapObj {
                                      uint256 amount;
                                      uint256 eqFee;
                                      uint256 eqReward;
                                      uint256 lpFee;
                                      uint256 protocolFee;
                                      uint256 lkbRemove;
                                  }
                                  struct CreditObj {
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // chainPath
                                  ChainPath[] public chainPaths; // list of connected chains with shared pools
                                  mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
                                  // metadata
                                  uint256 public immutable poolId; // shared id between chains to represent same pool
                                  uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
                                  uint256 public localDecimals; // the decimals for the token
                                  uint256 public immutable convertRate; // the decimals for the token
                                  address public immutable token; // the token for the pool
                                  address public immutable router; // the token for the pool
                                  bool public stopSwap; // flag to stop swapping in extreme cases
                                  // Fee and Liquidity
                                  uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
                                  uint256 public totalWeight; // total weight for pool percentages
                                  uint256 public mintFeeBP; // fee basis points for the mint/deposit
                                  uint256 public protocolFeeBalance; // fee balance created from dao fee
                                  uint256 public mintFeeBalance; // fee balance created from mint fee
                                  uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
                                  address public feeLibrary; // address for retrieving fee params for swaps
                                  // Delta related
                                  uint256 public deltaCredit; // credits accumulated from txn
                                  bool public batched; // flag to indicate if we want batch processing.
                                  bool public defaultSwapMode; // flag for the default mode for swap
                                  bool public defaultLPMode; // flag for the default mode for lp
                                  uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
                                  uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
                                  event Burn(address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
                                  event Swap(
                                      uint16 chainId,
                                      uint256 dstPoolId,
                                      address from,
                                      uint256 amountSD,
                                      uint256 eqReward,
                                      uint256 eqFee,
                                      uint256 protocolFee,
                                      uint256 lpFee
                                  );
                                  event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
                                  event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
                                  event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
                                  event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
                                  event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
                                  event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
                                  event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
                                  event FeesUpdated(uint256 mintFeeBP);
                                  event FeeLibraryUpdated(address feeLibraryAddr);
                                  event StopSwapUpdated(bool swapStop);
                                  event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
                                  event WithdrawMintFeeBalance(address to, uint256 amountSD);
                                  event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: only the router can call this method");
                                      _;
                                  }
                                  constructor(
                                      uint256 _poolId,
                                      address _router,
                                      address _token,
                                      uint256 _sharedDecimals,
                                      uint256 _localDecimals,
                                      address _feeLibrary,
                                      string memory _name,
                                      string memory _symbol
                                  ) LPTokenERC20(_name, _symbol) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      poolId = _poolId;
                                      router = _router;
                                      token = _token;
                                      sharedDecimals = _sharedDecimals;
                                      decimals = uint8(_sharedDecimals);
                                      localDecimals = _localDecimals;
                                      convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
                                      totalWeight = 0;
                                      feeLibrary = _feeLibrary;
                                      //delta algo related
                                      batched = false;
                                      defaultSwapMode = true;
                                      defaultLPMode = true;
                                  }
                                  function getChainPathsLength() public view returns (uint256) {
                                      return chainPaths.length;
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
                                      return _mintLocal(_to, _amountLD, true, true);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      bool newLiquidity
                                  ) external nonReentrant onlyRouter returns (SwapObj memory) {
                                      require(!stopSwap, "Stargate: swap func stopped");
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      uint256 amountSD = amountLDtoSD(_amountLD);
                                      uint256 minAmountSD = amountLDtoSD(_minAmountLD);
                                      // request fee params from library
                                      SwapObj memory s = IStargateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
                                      // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
                                      eqFeePool = eqFeePool.sub(s.eqReward);
                                      // update the new amount the user gets minus the fees
                                      s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
                                      // users will also get the eqReward
                                      require(s.amount.add(s.eqReward) >= minAmountSD, "Stargate: slippage too high");
                                      // behaviours
                                      //     - protocolFee: booked, stayed and withdrawn at remote.
                                      //     - eqFee: booked, stayed and withdrawn at remote.
                                      //     - lpFee: booked and stayed at remote, can be withdrawn anywhere
                                      s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
                                      // check for transfer solvency.
                                      require(cp.balance >= s.lkbRemove, "Stargate: dst balance too low");
                                      cp.balance = cp.balance.sub(s.lkbRemove);
                                      if (newLiquidity) {
                                          deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
                                      } else if (s.eqReward > 0) {
                                          deltaCredit = deltaCredit.add(s.eqReward);
                                      }
                                      // distribute credits on condition.
                                      if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultSwapMode);
                                      }
                                      emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
                                      return s;
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      cp.lkb = cp.lkb.add(cp.credits);
                                      c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
                                      c.credits = cp.credits;
                                      cp.credits = 0;
                                      emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemRemote   ->                        swapRemote
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLP
                                  ) external nonReentrant onlyRouter {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 amountSD = _burnLocal(_from, _amountLP);
                                      //run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
                                  }
                                  function instantRedeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      address _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 _deltaCredit = deltaCredit; // sload optimization.
                                      uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
                                      if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
                                      amountSD = _burnLocal(_from, _amountLP);
                                      deltaCredit = _deltaCredit.sub(amountSD);
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      bytes calldata _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      // safeguard.
                                      require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Stargate: counter chainPath is not ready");
                                      amountSD = _burnLocal(_from, _amountLP);
                                      // run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(false);
                                      }
                                      emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      CreditObj memory _c
                                  ) external nonReentrant onlyRouter {
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      cp.balance = cp.balance.add(_c.credits);
                                      if (cp.idealBalance != _c.idealBalance) {
                                          cp.idealBalance = _c.idealBalance;
                                      }
                                      emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      SwapObj memory _s
                                  ) external nonReentrant onlyRouter returns (uint256 amountLD) {
                                      // booking lpFee
                                      totalLiquidity = totalLiquidity.add(_s.lpFee);
                                      // booking eqFee
                                      eqFeePool = eqFeePool.add(_s.eqFee);
                                      // booking stargateFee
                                      protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
                                      // update LKB
                                      uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
                                      chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
                                      // user receives the amount + the srcReward
                                      amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
                                      _safeTransfer(token, _to, amountLD);
                                      emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _amountToMintSD
                                  ) external nonReentrant onlyRouter {
                                      if (_amountToMintSD > 0) {
                                          _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
                                      }
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      cp.lkb = cp.lkb.sub(_amountSD);
                                      uint256 amountLD = amountSDtoLD(_amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal(amount)   ->               redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      uint256 _amountSD
                                  ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      if (_amountSD > cp.balance) {
                                          mintAmount = _amountSD - cp.balance;
                                          swapAmount = cp.balance;
                                          cp.balance = 0;
                                      } else {
                                          cp.balance = cp.balance.sub(_amountSD);
                                          swapAmount = _amountSD;
                                          mintAmount = 0;
                                      }
                                      emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyRouter {
                                      for (uint256 i = 0; i < chainPaths.length; ++i) {
                                          ChainPath memory cp = chainPaths[i];
                                          bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
                                          require(!exists, "Stargate: cant createChainPath of existing dstChainId and _dstPoolId");
                                      }
                                      totalWeight = totalWeight.add(_weight);
                                      chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
                                      chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setWeightForChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      totalWeight = totalWeight.sub(cp.weight).add(_weight);
                                      cp.weight = _weight;
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setFee(uint256 _mintFeeBP) external onlyRouter {
                                      require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
                                      mintFeeBP = _mintFeeBP;
                                      emit FeesUpdated(mintFeeBP);
                                  }
                                  function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
                                      require(_feeLibraryAddr != address(0x0), "Stargate: fee library cant be 0x0");
                                      feeLibrary = _feeLibraryAddr;
                                      emit FeeLibraryUpdated(_feeLibraryAddr);
                                  }
                                  function setSwapStop(bool _swapStop) external onlyRouter {
                                      stopSwap = _swapStop;
                                      emit StopSwapUpdated(_swapStop);
                                  }
                                  function setDeltaParam(
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyRouter {
                                      require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Stargate: wrong Delta param");
                                      batched = _batched;
                                      swapDeltaBP = _swapDeltaBP;
                                      lpDeltaBP = _lpDeltaBP;
                                      defaultSwapMode = _defaultSwapMode;
                                      defaultLPMode = _defaultLPMode;
                                      emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(bool _fullMode) external onlyRouter {
                                      _delta(_fullMode);
                                  }
                                  function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == false, "Stargate: chainPath is already active");
                                      // this func will only be called once
                                      cp.ready = true;
                                  }
                                  function withdrawProtocolFeeBalance(address _to) external onlyRouter {
                                      if (protocolFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
                                          protocolFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawProtocolFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  function withdrawMintFeeBalance(address _to) external onlyRouter {
                                      if (mintFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
                                          mintFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawMintFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  // Conversion Helpers
                                  //---------------------------------------------------------------------------
                                  function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
                                      return amountSDtoLD(_amountLPtoSD(_amountLP));
                                  }
                                  function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant convert LPtoSD when totalSupply == 0");
                                      return _amountLP.mul(totalLiquidity).div(totalSupply);
                                  }
                                  function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
                                      require(totalLiquidity > 0, "Stargate: cant convert SDtoLP when totalLiq == 0");
                                      return _amountSD.mul(totalSupply).div(totalLiquidity);
                                  }
                                  function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.mul(convertRate);
                                  }
                                  function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.div(convertRate);
                                  }
                                  function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
                                      require(chainPaths.length > 0, "Stargate: no chainpaths exist");
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
                                      ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant burn when totalSupply == 0");
                                      uint256 amountOfLPTokens = balanceOf[_from];
                                      require(amountOfLPTokens >= _amountLP, "Stargate: not enough LP tokens to burn");
                                      uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
                                      //subtract totalLiquidity accordingly
                                      totalLiquidity = totalLiquidity.sub(amountSD);
                                      _burn(_from, _amountLP);
                                      emit Burn(_from, _amountLP, amountSD);
                                      return amountSD;
                                  }
                                  function _delta(bool fullMode) internal {
                                      if (deltaCredit > 0 && totalWeight > 0) {
                                          uint256 cpLength = chainPaths.length;
                                          uint256[] memory deficit = new uint256[](cpLength);
                                          uint256 totalDeficit = 0;
                                          // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
                                          for (uint256 i = 0; i < cpLength; ++i) {
                                              ChainPath storage cp = chainPaths[i];
                                              // (liquidity * (weight/totalWeight)) - (lkb+credits)
                                              uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
                                              uint256 currLiq = cp.lkb.add(cp.credits);
                                              if (balLiq > currLiq) {
                                                  // save gas since we know balLiq > currLiq and we know deficit[i] > 0
                                                  deficit[i] = balLiq - currLiq;
                                                  totalDeficit = totalDeficit.add(deficit[i]);
                                              }
                                          }
                                          // indicates how much delta credit is distributed
                                          uint256 spent;
                                          // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
                                          // run full Delta, allocate all credits
                                          if (totalDeficit == 0) {
                                              // only fullMode delta will allocate excess credits
                                              if (fullMode && deltaCredit > 0) {
                                                  // credit ChainPath by weights
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      // credits = credits + toBalanceChange + remaining allocation based on weight
                                                      uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
                                                      spent = spent.add(amtToCredit);
                                                      cp.credits = cp.credits.add(amtToCredit);
                                                  }
                                              } // else do nth
                                          } else if (totalDeficit <= deltaCredit) {
                                              if (fullMode) {
                                                  // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
                                                  uint256 excessCredit = deltaCredit - totalDeficit;
                                                  // algorithm steps 14-16: calculate credits
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          // credits = credits + deficit + remaining allocation based on weight
                                                          uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              } else {
                                                  // totalDeficit <= deltaCredit but not running fullMode
                                                  // credit chainPaths as is if any deficit, not using all deltaCredit
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          uint256 amtToCredit = deficit[i];
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              }
                                          } else {
                                              // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
                                              for (uint256 i = 0; i < cpLength; ++i) {
                                                  if (deficit[i] > 0) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
                                                      spent = spent.add(proportionalDeficit);
                                                      cp.credits = cp.credits.add(proportionalDeficit);
                                                  }
                                              }
                                          }
                                          // deduct the amount of credit sent
                                          deltaCredit = deltaCredit.sub(spent);
                                      }
                                  }
                                  function _mintLocal(
                                      address _to,
                                      uint256 _amountLD,
                                      bool _feesEnabled,
                                      bool _creditDelta
                                  ) internal returns (uint256 amountSD) {
                                      require(totalWeight > 0, "Stargate: No ChainPaths exist");
                                      amountSD = amountLDtoSD(_amountLD);
                                      uint256 mintFeeSD = 0;
                                      if (_feesEnabled) {
                                          mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
                                          amountSD = amountSD.sub(mintFeeSD);
                                          mintFeeBalance = mintFeeBalance.add(mintFeeSD);
                                      }
                                      if (_creditDelta) {
                                          deltaCredit = deltaCredit.add(amountSD);
                                      }
                                      uint256 amountLPTokens = amountSD;
                                      if (totalSupply != 0) {
                                          amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
                                      }
                                      totalLiquidity = totalLiquidity.add(amountSD);
                                      _mint(_to, amountLPTokens);
                                      emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
                                      // add to credits and call delta. short circuit to save gas
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                  }
                                  function _safeTransfer(
                                      address _token,
                                      address _to,
                                      uint256 _value
                                  ) private {
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
                                      require(success && (data.length == 0 || abi.decode(data, (bool))), "Stargate: TRANSFER_FAILED");
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract LPTokenERC20 {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  string public name;
                                  string public symbol;
                                  bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  // set in constructor
                                  bytes32 public DOMAIN_SEPARATOR;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  uint256 public decimals;
                                  uint256 public totalSupply;
                                  mapping(address => uint256) public balanceOf;
                                  mapping(address => mapping(address => uint256)) public allowance;
                                  mapping(address => uint256) public nonces;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  constructor(string memory _name, string memory _symbol) {
                                      name = _name;
                                      symbol = _symbol;
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      DOMAIN_SEPARATOR = keccak256(
                                          abi.encode(
                                              keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                              keccak256(bytes(name)),
                                              keccak256(bytes("1")),
                                              chainId,
                                              address(this)
                                          )
                                      );
                                  }
                                  function _mint(address to, uint256 value) internal {
                                      totalSupply = totalSupply.add(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(address(0), to, value);
                                  }
                                  function _burn(address from, uint256 value) internal {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      totalSupply = totalSupply.sub(value);
                                      emit Transfer(from, address(0), value);
                                  }
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) private {
                                      allowance[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                                  function approve(address spender, uint256 value) external returns (bool) {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  function transfer(address to, uint256 value) external returns (bool) {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) external returns (bool) {
                                      if (allowance[from][msg.sender] != uint256(-1)) {
                                          allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                      }
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
                                      return true;
                                  }
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "Bridge: EXPIRED");
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\\x19\\x01",
                                              DOMAIN_SEPARATOR,
                                              keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                          )
                                      );
                                      address recoveredAddress = ecrecover(digest, v, r, s);
                                      require(recoveredAddress != address(0) && recoveredAddress == owner, "Bridge: INVALID_SIGNATURE");
                                      _approve(owner, spender, value);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              import "../Pool.sol";
                              interface IStargateFeeLibrary {
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external returns (Pool.SwapObj memory s);
                                  function getVersion() external view returns (string memory);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                      return msg.data;
                                  }
                              }
                              

                              File 4 of 16: OptimizedTransparentUpgradeableProxy
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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 {
                                      // 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 virtual view 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 {
                                      _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 () payable external {
                                      _fallback();
                                  }
                                  /**
                                   * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                                   * is empty.
                                   */
                                  receive () payable external {
                                      _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.7.0;
                              import "./Proxy.sol";
                              import "../utils/Address.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.
                               * 
                               * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
                               * {TransparentUpgradeableProxy}.
                               */
                              contract UpgradeableProxy is Proxy {
                                  /**
                                   * @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));
                                      _setImplementation(_logic);
                                      if(_data.length > 0) {
                                          // solhint-disable-next-line avoid-low-level-calls
                                          (bool success,) = _logic.delegatecall(_data);
                                          require(success);
                                      }
                                  }
                                  /**
                                   * @dev Emitted when the implementation is upgraded.
                                   */
                                  event Upgraded(address indexed implementation);
                                  /**
                                   * @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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                                  /**
                                   * @dev Returns the current implementation address.
                                   */
                                  function _implementation() internal override view returns (address impl) {
                                      bytes32 slot = _IMPLEMENTATION_SLOT;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          impl := sload(slot)
                                      }
                                  }
                                  /**
                                   * @dev Upgrades the proxy to a new implementation.
                                   * 
                                   * Emits an {Upgraded} event.
                                   */
                                  function _upgradeTo(address newImplementation) internal {
                                      _setImplementation(newImplementation);
                                      emit Upgraded(newImplementation);
                                  }
                                  /**
                                   * @dev Stores a new address in the EIP1967 implementation slot.
                                   */
                                  function _setImplementation(address newImplementation) private {
                                      require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
                                      bytes32 slot = _IMPLEMENTATION_SLOT;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          sstore(slot, newImplementation)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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) {
                                      // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                      // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                      // for accounts without code, i.e. `keccak256('')`
                                      bytes32 codehash;
                                      bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly { codehash := extcodehash(account) }
                                      return (codehash != accountHash && codehash != 0x0);
                                  }
                                  /**
                                   * @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");
                                      return _functionCallWithValue(target, data, value, errorMessage);
                                  }
                                  function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
                                      require(isContract(target), "Address: call to non-contract");
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
                                      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.7.0;
                              import "../openzeppelin/proxy/UpgradeableProxy.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 inerface of your proxy.
                               */
                              contract OptimizedTransparentUpgradeableProxy is UpgradeableProxy {
                                  address internal immutable _ADMIN;
                                  /**
                                   * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                                   * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
                                   */
                                  constructor(
                                      address initialLogic,
                                      address initialAdmin,
                                      bytes memory _data
                                  ) payable UpgradeableProxy(initialLogic, _data) {
                                      assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                                      bytes32 slot = _ADMIN_SLOT;
                                      _ADMIN = initialAdmin;
                                      // still store it to work with EIP-1967
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          sstore(slot, initialAdmin)
                                      }
                                  }
                                  /**
                                   * @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 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                                  /**
                                   * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                                   */
                                  modifier ifAdmin() {
                                      if (msg.sender == _admin()) {
                                          _;
                                      } 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) {
                                      return _admin();
                                  }
                                  /**
                                   * @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) {
                                      return _implementation();
                                  }
                                  /**
                                   * @dev Upgrade the implementation of the proxy.
                                   *
                                   * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                                   */
                                  function upgradeTo(address newImplementation) external ifAdmin {
                                      _upgradeTo(newImplementation);
                                  }
                                  /**
                                   * @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 {
                                      _upgradeTo(newImplementation);
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, ) = newImplementation.delegatecall(data);
                                      require(success);
                                  }
                                  /**
                                   * @dev Returns the current admin.
                                   */
                                  function _admin() internal view returns (address adm) {
                                      return _ADMIN;
                                  }
                                  /**
                                   * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                                   */
                                  function _beforeFallback() internal virtual override {
                                      require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                                      super._beforeFallback();
                                  }
                              }
                              

                              File 5 of 16: UltraLightNodeV2
                              {"Address.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly { size := extcodesize(account) }\n        return size \u003e 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity\u0027s `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance \u003e= amount, \"Address: insufficient balance\");\n\n        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n        (bool success, ) = recipient.call{ value: amount }(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain`call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n      return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n        require(address(this).balance \u003e= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.call{ value: value }(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        // solhint-disable-next-line avoid-low-level-calls\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return _verifyCallResult(success, returndata, errorMessage);\n    }\n\n    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length \u003e 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"},"Buffer.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\n// https://github.com/ensdomains/buffer\n\npragma solidity ^0.7.0;\n\n/**\n * @dev A library for working with mutable byte buffers in Solidity.\n *\n * Byte buffers are mutable and expandable, and provide a variety of primitives\n * for writing to them. At any time you can fetch a bytes object containing the\n * current contents of the buffer. The bytes object should not be stored between\n * operations, as it may change due to resizing of the buffer.\n */\nlibrary Buffer {\n    /**\n     * @dev Represents a mutable buffer. Buffers have a current value (buf) and\n     *      a capacity. The capacity may be longer than the current value, in\n     *      which case it can be extended without the need to allocate more memory.\n     */\n    struct buffer {\n        bytes buf;\n        uint capacity;\n    }\n\n    /**\n     * @dev Initializes a buffer with an initial capacity.a co\n     * @param buf The buffer to initialize.\n     * @param capacity The number of bytes of space to allocate the buffer.\n     * @return The buffer, for chaining.\n     */\n    function init(buffer memory buf, uint capacity) internal pure returns (buffer memory) {\n        if (capacity % 32 != 0) {\n            capacity += 32 - (capacity % 32);\n        }\n        // Allocate space for the buffer data\n        buf.capacity = capacity;\n        assembly {\n            let ptr := mload(0x40)\n            mstore(buf, ptr)\n            mstore(ptr, 0)\n            mstore(0x40, add(32, add(ptr, capacity)))\n        }\n        return buf;\n    }\n\n\n    /**\n     * @dev Writes a byte string to a buffer. Resizes if doing so would exceed\n     *      the capacity of the buffer.\n     * @param buf The buffer to append to.\n     * @param off The start offset to write to.\n     * @param rawData The data to append.\n     * @param len The number of bytes to copy.\n     * @return The original buffer, for chaining.\n     */\n    function writeRawBytes(\n        buffer memory buf,\n        uint off,\n        bytes memory rawData,\n        uint offData,\n        uint len\n    ) internal pure returns (buffer memory) {\n        if (off + len \u003e buf.capacity) {\n            resize(buf, max(buf.capacity, len + off) * 2);\n        }\n\n        uint dest;\n        uint src;\n        assembly {\n            // Memory address of the buffer data\n            let bufptr := mload(buf)\n            // Length of existing buffer data\n            let buflen := mload(bufptr)\n            // Start address = buffer address + offset + sizeof(buffer length)\n            dest := add(add(bufptr, 32), off)\n            // Update buffer length if we\u0027re extending it\n            if gt(add(len, off), buflen) {\n                mstore(bufptr, add(len, off))\n            }\n            src := add(rawData, offData)\n        }\n\n        // Copy word-length chunks while possible\n        for (; len \u003e= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        // Copy remaining bytes\n        uint mask = 256**(32 - len) - 1;\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n\n        return buf;\n    }\n\n    /**\n     * @dev Writes a byte string to a buffer. Resizes if doing so would exceed\n     *      the capacity of the buffer.\n     * @param buf The buffer to append to.\n     * @param off The start offset to write to.\n     * @param data The data to append.\n     * @param len The number of bytes to copy.\n     * @return The original buffer, for chaining.\n     */\n    function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {\n        require(len \u003c= data.length);\n\n        if (off + len \u003e buf.capacity) {\n            resize(buf, max(buf.capacity, len + off) * 2);\n        }\n\n        uint dest;\n        uint src;\n        assembly {\n        // Memory address of the buffer data\n            let bufptr := mload(buf)\n        // Length of existing buffer data\n            let buflen := mload(bufptr)\n        // Start address = buffer address + offset + sizeof(buffer length)\n            dest := add(add(bufptr, 32), off)\n        // Update buffer length if we\u0027re extending it\n            if gt(add(len, off), buflen) {\n                mstore(bufptr, add(len, off))\n            }\n            src := add(data, 32)\n        }\n\n        // Copy word-length chunks while possible\n        for (; len \u003e= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        // Copy remaining bytes\n        uint mask = 256**(32 - len) - 1;\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n\n        return buf;\n    }\n\n    function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {\n        return write(buf, buf.buf.length, data, data.length);\n    }\n\n    function resize(buffer memory buf, uint capacity) private pure {\n        bytes memory oldbuf = buf.buf;\n        init(buf, capacity);\n        append(buf, oldbuf);\n    }\n\n    function max(uint a, uint b) private pure returns (uint) {\n        if (a \u003e b) {\n            return a;\n        }\n        return b;\n    }\n}\n"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity \u003e=0.6.0 \u003c0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address payable) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes memory) {\n        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n        return msg.data;\n    }\n}\n"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller\u0027s account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller\u0027s tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender\u0027s allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller\u0027s\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"},"ILayerZeroEndpoint.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.5.0;\n\nimport \"./ILayerZeroUserApplicationConfig.sol\";\n\ninterface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {\n    // @notice send a LayerZero message to the specified address at a LayerZero endpoint.\n    // @param _dstChainId - the destination chain identifier\n    // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains\n    // @param _payload - a custom bytes payload to send to the destination contract\n    // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address\n    // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction\n    // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination\n    function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;\n\n    // @notice used by the messaging library to publish verified payload\n    // @param _srcChainId - the source chain identifier\n    // @param _srcAddress - the source contract (as bytes) at the source chain\n    // @param _dstAddress - the address on destination chain\n    // @param _nonce - the unbound message ordering nonce\n    // @param _gasLimit - the gas limit for external contract execution\n    // @param _payload - verified payload to send to the destination contract\n    function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;\n\n    // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain\n    // @param _srcChainId - the source chain identifier\n    // @param _srcAddress - the source chain contract address\n    function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);\n\n    // @notice get the outboundNonce from this source chain which, consequently, is always an EVM\n    // @param _srcAddress - the source chain contract address\n    function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);\n\n    // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery\n    // @param _dstChainId - the destination chain identifier\n    // @param _userApplication - the user app address on this EVM chain\n    // @param _payload - the custom message to send over LayerZero\n    // @param _payInZRO - if false, user app pays the protocol fee in native token\n    // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain\n    function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);\n\n    // @notice get this Endpoint\u0027s immutable source identifier\n    function getChainId() external view returns (uint16);\n\n    // @notice the interface to retry failed message on this Endpoint destination\n    // @param _srcChainId - the source chain identifier\n    // @param _srcAddress - the source chain contract address\n    // @param _payload - the payload to be retried\n    function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;\n\n    // @notice query if any STORED payload (message blocking) at the endpoint.\n    // @param _srcChainId - the source chain identifier\n    // @param _srcAddress - the source chain contract address\n    function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n    // @notice query if the _libraryAddress is valid for sending msgs.\n    // @param _userApplication - the user app address on this EVM chain\n    function getSendLibraryAddress(address _userApplication) external view returns (address);\n\n    // @notice query if the _libraryAddress is valid for receiving msgs.\n    // @param _userApplication - the user app address on this EVM chain\n    function getReceiveLibraryAddress(address _userApplication) external view returns (address);\n\n    // @notice query if the non-reentrancy guard for send() is on\n    // @return true if the guard is on. false otherwise\n    function isSendingPayload() external view returns (bool);\n\n    // @notice query if the non-reentrancy guard for receive() is on\n    // @return true if the guard is on. false otherwise\n    function isReceivingPayload() external view returns (bool);\n\n    // @notice get the configuration of the LayerZero messaging library of the specified version\n    // @param _version - messaging library version\n    // @param _chainId - the chainId for the pending config change\n    // @param _userApplication - the contract address of the user application\n    // @param _configType - type of configuration. every messaging library has its own convention.\n    function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);\n\n    // @notice get the send() LayerZero messaging library version\n    // @param _userApplication - the contract address of the user application\n    function getSendVersion(address _userApplication) external view returns (uint16);\n\n    // @notice get the lzReceive() LayerZero messaging library version\n    // @param _userApplication - the contract address of the user application\n    function getReceiveVersion(address _userApplication) external view returns (uint16);\n}\n"},"ILayerZeroMessagingLibrary.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\n\nimport \"./ILayerZeroUserApplicationConfig.sol\";\n\ninterface ILayerZeroMessagingLibrary {\n    // send(), messages will be inflight.\n    function send(address _userApplication, uint64 _lastNonce, uint16 _chainId, bytes calldata _destination, bytes calldata _payload, address payable refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;\n\n    // estimate native fee at the send side\n    function estimateFees(uint16 _chainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);\n\n    //---------------------------------------------------------------------------\n    // setConfig / getConfig are User Application (UA) functions to specify Oracle, Relayer, blockConfirmations, libraryVersion\n    function setConfig(uint16 _chainId, address _userApplication, uint _configType, bytes calldata _config) external;\n\n    function getConfig(uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);\n}\n"},"ILayerZeroMessagingLibraryV2.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\n\nimport \"./ILayerZeroUserApplicationConfig.sol\";\nimport \"./ILayerZeroMessagingLibrary.sol\";\n\ninterface ILayerZeroMessagingLibraryV2 is ILayerZeroMessagingLibrary {\n    function getOutboundNonce(uint16 _chainId, bytes calldata _path) external view returns (uint64);\n}\n"},"ILayerZeroOracleV2.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\n\ninterface ILayerZeroOracleV2 {\n    // @notice query price and assign jobs at the same time\n    // @param _dstChainId - the destination endpoint identifier\n    // @param _outboundProofType - the proof type identifier to specify proof to be relayed\n    // @param _outboundBlockConfirmation - block confirmation delay before relaying blocks\n    // @param _userApplication - the source sending contract address\n    function assignJob(uint16 _dstChainId, uint16 _outboundProofType, uint64 _outboundBlockConfirmation, address _userApplication) external returns (uint price);\n\n    // @notice query the oracle price for relaying block information to the destination chain\n    // @param _dstChainId the destination endpoint identifier\n    // @param _outboundProofType the proof type identifier to specify the data to be relayed\n    // @param _outboundBlockConfirmation - block confirmation delay before relaying blocks\n    // @param _userApplication - the source sending contract address\n    function getFee(uint16 _dstChainId, uint16 _outboundProofType, uint64 _outboundBlockConfirmation, address _userApplication) external view returns (uint price);\n\n    // @notice withdraw the accrued fee in ultra light node\n    // @param _to - the fee receiver\n    // @param _amount - the withdrawal amount\n    function withdrawFee(address payable _to, uint _amount) external;\n}\n"},"ILayerZeroReceiver.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.5.0;\n\ninterface ILayerZeroReceiver {\n    // @notice LayerZero endpoint will invoke this function to deliver the message on the destination\n    // @param _srcChainId - the source endpoint identifier\n    // @param _srcAddress - the source sending contract address from the source chain\n    // @param _nonce - the ordered message nonce\n    // @param _payload - the signed payload is the UA bytes has encoded to be sent\n    function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n}\n"},"ILayerZeroRelayerV2.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\n\ninterface ILayerZeroRelayerV2 {\n    // @notice query price and assign jobs at the same time\n    // @param _dstChainId - the destination endpoint identifier\n    // @param _outboundProofType - the proof type identifier to specify proof to be relayed\n    // @param _userApplication - the source sending contract address. relayers may apply price discrimination to user apps\n    // @param _payloadSize - the length of the payload. it is an indicator of gas usage for relaying cross-chain messages\n    // @param _adapterParams - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain\n    function assignJob(uint16 _dstChainId, uint16 _outboundProofType, address _userApplication, uint _payloadSize, bytes calldata _adapterParams) external returns (uint price);\n\n    // @notice query the relayer price for relaying the payload and its proof to the destination chain\n    // @param _dstChainId - the destination endpoint identifier\n    // @param _outboundProofType - the proof type identifier to specify proof to be relayed\n    // @param _userApplication - the source sending contract address. relayers may apply price discrimination to user apps\n    // @param _payloadSize - the length of the payload. it is an indicator of gas usage for relaying cross-chain messages\n    // @param _adapterParams - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain\n    function getFee(uint16 _dstChainId, uint16 _outboundProofType, address _userApplication, uint _payloadSize, bytes calldata _adapterParams) external view returns (uint price);\n\n    // @notice withdraw the accrued fee in ultra light node\n    // @param _to - the fee receiver\n    // @param _amount - the withdrawal amount\n    function withdrawFee(address payable _to, uint _amount) external;\n}\n"},"ILayerZeroTreasury.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.5.0;\n\ninterface ILayerZeroTreasury {\n    function getFees(bool payInZro, uint relayerFee, uint oracleFee) external view returns (uint);\n}\n"},"ILayerZeroUltraLightNodeV2.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\npragma abicoder v2;\n\ninterface ILayerZeroUltraLightNodeV2 {\n    // Relayer functions\n    function validateTransactionProof(uint16 _srcChainId, address _dstAddress, uint _gasLimit, bytes32 _lookupHash, bytes32 _blockData, bytes calldata _transactionProof) external;\n\n    // an Oracle delivers the block data using updateHash()\n    function updateHash(uint16 _srcChainId, bytes32 _lookupHash, uint _confirmations, bytes32 _blockData) external;\n\n    // can only withdraw the receivable of the msg.sender\n    function withdrawNative(address payable _to, uint _amount) external;\n\n    function withdrawZRO(address _to, uint _amount) external;\n\n    // view functions\n    function getAppConfig(uint16 _remoteChainId, address _userApplicationAddress) external view returns (ApplicationConfiguration memory);\n\n    function accruedNativeFee(address _address) external view returns (uint);\n\n    struct ApplicationConfiguration {\n        uint16 inboundProofLibraryVersion;\n        uint64 inboundBlockConfirmations;\n        address relayer;\n        uint16 outboundProofType;\n        uint64 outboundBlockConfirmations;\n        address oracle;\n    }\n\n    event HashReceived(uint16 indexed srcChainId, address indexed oracle, bytes32 lookupHash, bytes32 blockData, uint confirmations);\n    event RelayerParams(bytes adapterParams, uint16 outboundProofType);\n    event Packet(bytes payload);\n    event InvalidDst(uint16 indexed srcChainId, bytes srcAddress, address indexed dstAddress, uint64 nonce, bytes32 payloadHash);\n    event PacketReceived(uint16 indexed srcChainId, bytes srcAddress, address indexed dstAddress, uint64 nonce, bytes32 payloadHash);\n    event AppConfigUpdated(address indexed userApplication, uint indexed configType, bytes newConfig);\n    event AddInboundProofLibraryForChain(uint16 indexed chainId, address lib);\n    event EnableSupportedOutboundProof(uint16 indexed chainId, uint16 proofType);\n    event SetChainAddressSize(uint16 indexed chainId, uint size);\n    event SetDefaultConfigForChainId(uint16 indexed chainId, uint16 inboundProofLib, uint64 inboundBlockConfirm, address relayer, uint16 outboundProofType, uint64 outboundBlockConfirm, address oracle);\n    event SetDefaultAdapterParamsForChainId(uint16 indexed chainId, uint16 indexed proofType, bytes adapterParams);\n    event SetLayerZeroToken(address indexed tokenAddress);\n    event SetRemoteUln(uint16 indexed chainId, bytes32 uln);\n    event SetTreasury(address indexed treasuryAddress);\n    event WithdrawZRO(address indexed msgSender, address indexed to, uint amount);\n    event WithdrawNative(address indexed msgSender, address indexed to, uint amount);\n}\n"},"ILayerZeroUserApplicationConfig.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.5.0;\n\ninterface ILayerZeroUserApplicationConfig {\n    // @notice set the configuration of the LayerZero messaging library of the specified version\n    // @param _version - messaging library version\n    // @param _chainId - the chainId for the pending config change\n    // @param _configType - type of configuration. every messaging library has its own convention.\n    // @param _config - configuration in the bytes. can encode arbitrary content.\n    function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;\n\n    // @notice set the send() LayerZero messaging library version to _version\n    // @param _version - new messaging library version\n    function setSendVersion(uint16 _version) external;\n\n    // @notice set the lzReceive() LayerZero messaging library version to _version\n    // @param _version - new messaging library version\n    function setReceiveVersion(uint16 _version) external;\n\n    // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload\n    // @param _srcChainId - the chainId of the source chain\n    // @param _srcAddress - the contract address of the source contract at the source chain\n    function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n}\n"},"ILayerZeroValidationLibrary.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity \u003e=0.7.0;\npragma abicoder v2;\n\nimport \"./LayerZeroPacket.sol\";\n\ninterface ILayerZeroValidationLibrary {\n    function validateProof(bytes32 blockData, bytes calldata _data, uint _remoteAddressSize) external returns (LayerZeroPacket.Packet memory packet);\n}\n"},"LayerZeroPacket.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.7.6;\n\nimport \"./Buffer.sol\";\nimport \"./SafeMath.sol\";\n\nlibrary LayerZeroPacket {\n    using Buffer for Buffer.buffer;\n    using SafeMath for uint;\n\n    struct Packet {\n        uint16 srcChainId;\n        uint16 dstChainId;\n        uint64 nonce;\n        address dstAddress;\n        bytes srcAddress;\n        bytes32 ulnAddress;\n        bytes payload;\n    }\n\n    function getPacket(\n        bytes memory data,\n        uint16 srcChain,\n        uint sizeOfSrcAddress,\n        bytes32 ulnAddress\n    ) internal pure returns (LayerZeroPacket.Packet memory) {\n        uint16 dstChainId;\n        address dstAddress;\n        uint size;\n        uint64 nonce;\n\n        // The log consists of the destination chain id and then a bytes payload\n        //      0--------------------------------------------31\n        // 0   |  total bytes size\n        // 32  |  destination chain id\n        // 64  |  bytes offset\n        // 96  |  bytes array size\n        // 128 |  payload\n        assembly {\n            dstChainId := mload(add(data, 32))\n            size := mload(add(data, 96)) /// size of the byte array\n            nonce := mload(add(data, 104)) // offset to convert to uint64  128  is index -24\n            dstAddress := mload(add(data, sub(add(128, sizeOfSrcAddress), 4))) // offset to convert to address 12 -8\n        }\n\n        Buffer.buffer memory srcAddressBuffer;\n        srcAddressBuffer.init(sizeOfSrcAddress);\n        srcAddressBuffer.writeRawBytes(0, data, 136, sizeOfSrcAddress); // 128 + 8\n\n        uint payloadSize = size.sub(28).sub(sizeOfSrcAddress);\n        Buffer.buffer memory payloadBuffer;\n        payloadBuffer.init(payloadSize);\n        payloadBuffer.writeRawBytes(0, data, sizeOfSrcAddress.add(156), payloadSize); // 148 + 8\n        return LayerZeroPacket.Packet(srcChain, dstChainId, nonce, dstAddress, srcAddressBuffer.buf, ulnAddress, payloadBuffer.buf);\n    }\n\n    function getPacketV2(\n        bytes memory data,\n        uint sizeOfSrcAddress,\n        bytes32 ulnAddress\n    ) internal pure returns (LayerZeroPacket.Packet memory) {\n        // packet def: abi.encodePacked(nonce, srcChain, srcAddress, dstChain, dstAddress, payload);\n        // data def: abi.encode(packet) = offset(32) + length(32) + packet\n        //              if from EVM\n        // 0 - 31       0 - 31          |  total bytes size\n        // 32 - 63      32 - 63         |  location\n        // 64 - 95      64 - 95         |  size of the packet\n        // 96 - 103     96 - 103        |  nonce\n        // 104 - 105    104 - 105       |  srcChainId\n        // 106 - P      106 - 125       |  srcAddress, where P = 106 + sizeOfSrcAddress - 1,\n        // P+1 - P+2    126 - 127       |  dstChainId\n        // P+3 - P+22   128 - 147       |  dstAddress\n        // P+23 - END   148 - END       |  payload\n\n        // decode the packet\n        uint256 realSize;\n        uint64 nonce;\n        uint16 srcChain;\n        uint16 dstChain;\n        address dstAddress;\n        assembly {\n            realSize := mload(add(data, 64))\n            nonce := mload(add(data, 72)) // 104 - 32\n            srcChain := mload(add(data, 74)) // 106 - 32\n            dstChain := mload(add(data, add(76, sizeOfSrcAddress))) // P + 3 - 32 = 105 + size + 3 - 32 = 76 + size\n            dstAddress := mload(add(data, add(96, sizeOfSrcAddress))) // P + 23 - 32 = 105 + size + 23 - 32 = 96 + size\n        }\n\n        require(srcChain != 0, \"LayerZeroPacket: invalid packet\");\n\n        Buffer.buffer memory srcAddressBuffer;\n        srcAddressBuffer.init(sizeOfSrcAddress);\n        srcAddressBuffer.writeRawBytes(0, data, 106, sizeOfSrcAddress);\n\n        uint nonPayloadSize = sizeOfSrcAddress.add(32);// 2 + 2 + 8 + 20, 32 + 20 = 52 if sizeOfSrcAddress == 20\n        uint payloadSize = realSize.sub(nonPayloadSize);\n        Buffer.buffer memory payloadBuffer;\n        payloadBuffer.init(payloadSize);\n        payloadBuffer.writeRawBytes(0, data, nonPayloadSize.add(96), payloadSize);\n\n        return LayerZeroPacket.Packet(srcChain, dstChain, nonce, dstAddress, srcAddressBuffer.buf, ulnAddress, payloadBuffer.buf);\n    }\n\n    function getPacketV3(\n        bytes memory data,\n        uint sizeOfSrcAddress,\n        bytes32 ulnAddress\n    ) internal pure returns (LayerZeroPacket.Packet memory) {\n        // data def: abi.encodePacked(nonce, srcChain, srcAddress, dstChain, dstAddress, payload);\n        //              if from EVM\n        // 0 - 31       0 - 31          |  total bytes size\n        // 32 - 39      32 - 39         |  nonce\n        // 40 - 41      40 - 41         |  srcChainId\n        // 42 - P       42 - 61         |  srcAddress, where P = 41 + sizeOfSrcAddress,\n        // P+1 - P+2    62 - 63         |  dstChainId\n        // P+3 - P+22   64 - 83         |  dstAddress\n        // P+23 - END   84 - END        |  payload\n\n        // decode the packet\n        uint256 realSize = data.length;\n        uint nonPayloadSize = sizeOfSrcAddress.add(32);// 2 + 2 + 8 + 20, 32 + 20 = 52 if sizeOfSrcAddress == 20\n        require(realSize \u003e= nonPayloadSize, \"LayerZeroPacket: invalid packet\");\n        uint payloadSize = realSize - nonPayloadSize;\n\n        uint64 nonce;\n        uint16 srcChain;\n        uint16 dstChain;\n        address dstAddress;\n        assembly {\n            nonce := mload(add(data, 8)) // 40 - 32\n            srcChain := mload(add(data, 10)) // 42 - 32\n            dstChain := mload(add(data, add(12, sizeOfSrcAddress))) // P + 3 - 32 = 41 + size + 3 - 32 = 12 + size\n            dstAddress := mload(add(data, add(32, sizeOfSrcAddress))) // P + 23 - 32 = 41 + size + 23 - 32 = 32 + size\n        }\n\n        require(srcChain != 0, \"LayerZeroPacket: invalid packet\");\n\n        Buffer.buffer memory srcAddressBuffer;\n        srcAddressBuffer.init(sizeOfSrcAddress);\n        srcAddressBuffer.writeRawBytes(0, data, 42, sizeOfSrcAddress);\n\n        Buffer.buffer memory payloadBuffer;\n        if (payloadSize \u003e 0) {\n            payloadBuffer.init(payloadSize);\n            payloadBuffer.writeRawBytes(0, data, nonPayloadSize.add(32), payloadSize);\n        }\n\n        return LayerZeroPacket.Packet(srcChain, dstChain, nonce, dstAddress, srcAddressBuffer.buf, ulnAddress, payloadBuffer.buf);\n    }\n}\n"},"NonceContract.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.7.6;\n\nimport \"./ILayerZeroEndpoint.sol\";\n\ncontract NonceContract {\n    ILayerZeroEndpoint public immutable endpoint;\n    // outboundNonce = [dstChainId][remoteAddress + localAddress]\n    mapping(uint16 =\u003e mapping(bytes =\u003e uint64)) public outboundNonce;\n\n    constructor(address _endpoint) {\n        endpoint = ILayerZeroEndpoint(_endpoint);\n    }\n\n    function increment(uint16 _chainId, address _ua, bytes calldata _path) external returns (uint64) {\n        require(endpoint.getSendLibraryAddress(_ua) == msg.sender, \"NonceContract: msg.sender is not valid sendlibrary\");\n        return ++outboundNonce[_chainId][_path];\n    }\n}\n"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\nimport \"./Context.sol\";\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor () {\n        address msgSender = _msgSender();\n        _owner = msgSender;\n        emit OwnershipTransferred(address(0), msgSender);\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n        _;\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        emit OwnershipTransferred(_owner, address(0));\n        _owner = address(0);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        emit OwnershipTransferred(_owner, newOwner);\n        _owner = newOwner;\n    }\n}\n"},"ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot\u0027s contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler\u0027s defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction\u0027s gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor () {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and make it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"},"SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using SafeMath for uint256;\n    using Address for address;\n\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // \u0027safeIncreaseAllowance\u0027 and \u0027safeDecreaseAllowance\u0027\n        // solhint-disable-next-line max-line-length\n        require((value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).add(value);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity\u0027s return data size checking mechanism, since\n        // we\u0027re implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length \u003e 0) { // Return data is optional\n            // solhint-disable-next-line max-line-length\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"},"SafeMath.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Wrappers over Solidity\u0027s arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it\u0027s recommended to use it always.\n */\nlibrary SafeMath {\n    /**\n     * @dev Returns the addition of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        uint256 c = a + b;\n        if (c \u003c a) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b \u003e a) return (false, 0);\n        return (true, a - b);\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        // Gas optimization: this is cheaper than requiring \u0027a\u0027 not being zero, but the\n        // benefit is lost if \u0027b\u0027 is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n        if (a == 0) return (true, 0);\n        uint256 c = a * b;\n        if (c / a != b) return (false, 0);\n        return (true, c);\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a / b);\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n     *\n     * _Available since v3.4._\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n        if (b == 0) return (false, 0);\n        return (true, a % b);\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `+` operator.\n     *\n     * Requirements:\n     *\n     * - Addition cannot overflow.\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c \u003e= a, \"SafeMath: addition overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting on\n     * overflow (when the result is negative).\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b \u003c= a, \"SafeMath: subtraction overflow\");\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, reverting on\n     * overflow.\n     *\n     * Counterpart to Solidity\u0027s `*` operator.\n     *\n     * Requirements:\n     *\n     * - Multiplication cannot overflow.\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (a == 0) return 0;\n        uint256 c = a * b;\n        require(c / a == b, \"SafeMath: multiplication overflow\");\n        return c;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting on\n     * division by zero. The result is rounded towards zero.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b \u003e 0, \"SafeMath: division by zero\");\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting when dividing by zero.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b \u003e 0, \"SafeMath: modulo by zero\");\n        return a % b;\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n     * overflow (when the result is negative).\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {trySub}.\n     *\n     * Counterpart to Solidity\u0027s `-` operator.\n     *\n     * Requirements:\n     *\n     * - Subtraction cannot overflow.\n     */\n    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b \u003c= a, errorMessage);\n        return a - b;\n    }\n\n    /**\n     * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n     * division by zero. The result is rounded towards zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryDiv}.\n     *\n     * Counterpart to Solidity\u0027s `/` operator. Note: this function uses a\n     * `revert` opcode (which leaves remaining gas untouched) while Solidity\n     * uses an invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b \u003e 0, errorMessage);\n        return a / b;\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n     * reverting with custom message when dividing by zero.\n     *\n     * CAUTION: This function is deprecated because it requires allocating memory for the error\n     * message unnecessarily. For custom revert reasons use {tryMod}.\n     *\n     * Counterpart to Solidity\u0027s `%` operator. This function uses a `revert`\n     * opcode (which leaves remaining gas untouched) while Solidity uses an\n     * invalid opcode to revert (consuming all remaining gas).\n     *\n     * Requirements:\n     *\n     * - The divisor cannot be zero.\n     */\n    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n        require(b \u003e 0, errorMessage);\n        return a % b;\n    }\n}\n"},"UltraLightNodeV2.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.7.6;\npragma abicoder v2;\n\nimport \"./Ownable.sol\";\nimport \"./SafeMath.sol\";\nimport \"./ReentrancyGuard.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeERC20.sol\";\n\nimport \"./ILayerZeroValidationLibrary.sol\";\nimport \"./ILayerZeroReceiver.sol\";\nimport \"./ILayerZeroTreasury.sol\";\nimport \"./ILayerZeroEndpoint.sol\";\n// v2\nimport \"./ILayerZeroMessagingLibraryV2.sol\";\nimport \"./ILayerZeroOracleV2.sol\";\nimport \"./ILayerZeroUltraLightNodeV2.sol\";\nimport \"./ILayerZeroRelayerV2.sol\";\nimport \"./NonceContract.sol\";\n\ncontract UltraLightNodeV2 is ILayerZeroMessagingLibraryV2, ILayerZeroUltraLightNodeV2, ReentrancyGuard, Ownable {\n    using SafeERC20 for IERC20;\n    using SafeMath for uint;\n\n    // Application config\n    uint public constant CONFIG_TYPE_INBOUND_PROOF_LIBRARY_VERSION = 1;\n    uint public constant CONFIG_TYPE_INBOUND_BLOCK_CONFIRMATIONS = 2;\n    uint public constant CONFIG_TYPE_RELAYER = 3;\n    uint public constant CONFIG_TYPE_OUTBOUND_PROOF_TYPE = 4;\n    uint public constant CONFIG_TYPE_OUTBOUND_BLOCK_CONFIRMATIONS = 5;\n    uint public constant CONFIG_TYPE_ORACLE = 6;\n\n    // Token and Contracts\n    IERC20 public layerZeroToken;\n    ILayerZeroTreasury public treasuryContract;\n\n    mapping(address =\u003e uint) public nativeFees;\n    uint public treasuryZROFees;\n\n    // User Application\n    mapping(address =\u003e mapping(uint16 =\u003e ApplicationConfiguration)) public appConfig; // app address =\u003e chainId =\u003e config\n    mapping(uint16 =\u003e ApplicationConfiguration) public defaultAppConfig; // default UA settings if no version specified\n    mapping(uint16 =\u003e mapping(uint16 =\u003e bytes)) public defaultAdapterParams;\n\n    // Validation\n    mapping(uint16 =\u003e mapping(uint16 =\u003e address)) public inboundProofLibrary; // chainId =\u003e library Id =\u003e inboundProofLibrary contract\n    mapping(uint16 =\u003e uint16) public maxInboundProofLibrary; // chainId =\u003e inboundProofLibrary\n    mapping(uint16 =\u003e mapping(uint16 =\u003e bool)) public supportedOutboundProof; // chainId =\u003e outboundProofType =\u003e enabled\n    mapping(uint16 =\u003e uint) public chainAddressSizeMap;\n    mapping(address =\u003e mapping(uint16 =\u003e mapping(bytes32 =\u003e mapping(bytes32 =\u003e uint)))) public hashLookup; //[oracle][srcChainId][blockhash][datahash] -\u003e confirmation\n    mapping(uint16 =\u003e bytes32) public ulnLookup; // remote ulns\n\n    ILayerZeroEndpoint public immutable endpoint;\n    uint16 public immutable localChainId;\n    NonceContract public immutable nonceContract;\n\n    constructor(address _endpoint, address _nonceContract, uint16 _localChainId) {\n        require(_endpoint != address(0x0), \"LayerZero: endpoint cannot be zero address\");\n        require(_nonceContract != address(0x0), \"LayerZero: nonceContract cannot be zero address\");\n        ILayerZeroEndpoint lzEndpoint = ILayerZeroEndpoint(_endpoint);\n        localChainId = _localChainId;\n        endpoint = lzEndpoint;\n        nonceContract = NonceContract(_nonceContract);\n    }\n\n    // only the endpoint can call SEND() and setConfig()\n    modifier onlyEndpoint() {\n        require(address(endpoint) == msg.sender, \"LayerZero: only endpoint\");\n        _;\n    }\n\n    //----------------------------------------------------------------------------------\n    // PROTOCOL\n    function validateTransactionProof(uint16 _srcChainId, address _dstAddress, uint _gasLimit, bytes32 _lookupHash, bytes32 _blockData, bytes calldata _transactionProof) external override {\n        // retrieve UA\u0027s configuration using the _dstAddress from arguments.\n        ApplicationConfiguration memory uaConfig = _getAppConfig(_srcChainId, _dstAddress);\n\n        // assert that the caller == UA\u0027s relayer\n        require(uaConfig.relayer == msg.sender, \"LayerZero: invalid relayer\");\n\n        LayerZeroPacket.Packet memory _packet;\n        uint remoteAddressSize = chainAddressSizeMap[_srcChainId];\n        require(remoteAddressSize != 0, \"LayerZero: incorrect remote address size\");\n        {\n            // assert that the data submitted by UA\u0027s oracle have no fewer confirmations than UA\u0027s configuration\n            uint storedConfirmations = hashLookup[uaConfig.oracle][_srcChainId][_lookupHash][_blockData];\n            require(storedConfirmations \u003e 0 \u0026\u0026 storedConfirmations \u003e= uaConfig.inboundBlockConfirmations, \"LayerZero: not enough block confirmations\");\n\n            // decode\n            address inboundProofLib = inboundProofLibrary[_srcChainId][uaConfig.inboundProofLibraryVersion];\n            _packet = ILayerZeroValidationLibrary(inboundProofLib).validateProof(_blockData, _transactionProof, remoteAddressSize);\n        }\n\n        // packet content assertion\n        require(ulnLookup[_srcChainId] == _packet.ulnAddress \u0026\u0026 _packet.ulnAddress != bytes32(0), \"LayerZero: invalid _packet.ulnAddress\");\n        require(_packet.srcChainId == _srcChainId, \"LayerZero: invalid srcChain Id\");\n        // failsafe because the remoteAddress size being passed into validateProof trims the address this should not hit\n        require(_packet.srcAddress.length == remoteAddressSize, \"LayerZero: invalid srcAddress size\");\n        require(_packet.dstChainId == localChainId, \"LayerZero: invalid dstChain Id\");\n        require(_packet.dstAddress == _dstAddress, \"LayerZero: invalid dstAddress\");\n\n        // if the dst is not a contract, then emit and return early. This will break inbound nonces, but this particular\n        // path is already broken and wont ever be able to deliver anyways\n        if (!_isContract(_dstAddress)) {\n            emit InvalidDst(_packet.srcChainId, _packet.srcAddress, _packet.dstAddress, _packet.nonce, keccak256(_packet.payload));\n            return;\n        }\n\n        bytes memory pathData = abi.encodePacked(_packet.srcAddress, _packet.dstAddress);\n        emit PacketReceived(_packet.srcChainId, _packet.srcAddress, _packet.dstAddress, _packet.nonce, keccak256(_packet.payload));\n        endpoint.receivePayload(_srcChainId, pathData, _dstAddress, _packet.nonce, _gasLimit, _packet.payload);\n    }\n\n    function send(address _ua, uint64, uint16 _dstChainId, bytes calldata _path, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable override onlyEndpoint {\n        address ua = _ua;\n        uint16 dstChainId = _dstChainId;\n        require(ulnLookup[dstChainId] != bytes32(0), \"LayerZero: dstChainId does not exist\");\n\n        bytes memory dstAddress;\n        uint64 nonce;\n        // code block for solving \u0027Stack Too Deep\u0027\n        {\n            uint chainAddressSize = chainAddressSizeMap[dstChainId];\n            // path = remoteAddress + localAddress\n            require(chainAddressSize != 0 \u0026\u0026 _path.length == 20 + chainAddressSize, \"LayerZero: incorrect remote address size\");\n            address srcInPath;\n            bytes memory path = _path; // copy to memory\n            assembly {\n                srcInPath := mload(add(add(path, 20), chainAddressSize)) // chainAddressSize + 20\n            }\n            require(ua == srcInPath, \"LayerZero: wrong path data\");\n            dstAddress = _path[0:chainAddressSize];\n            nonce = nonceContract.increment(dstChainId, ua, path);\n        }\n\n        bytes memory payload = _payload;\n        ApplicationConfiguration memory uaConfig = _getAppConfig(dstChainId, ua);\n\n        // compute all the fees\n        uint relayerFee = _handleRelayer(dstChainId, uaConfig, ua, payload.length, _adapterParams);\n        uint oracleFee = _handleOracle(dstChainId, uaConfig, ua);\n        uint nativeProtocolFee = _handleProtocolFee(relayerFee, oracleFee, ua, _zroPaymentAddress);\n\n        // total native fee, does not include ZRO protocol fee\n        uint totalNativeFee = relayerFee.add(oracleFee).add(nativeProtocolFee);\n\n        // assert the user has attached enough native token for this address\n        require(totalNativeFee \u003c= msg.value, \"LayerZero: not enough native for fees\");\n        // refund if they send too much\n        uint amount = msg.value.sub(totalNativeFee);\n        if (amount \u003e 0) {\n            (bool success, ) = _refundAddress.call{value: amount}(\"\");\n            require(success, \"LayerZero: failed to refund\");\n        }\n\n        // emit the data packet\n        bytes memory encodedPayload = abi.encodePacked(nonce, localChainId, ua, dstChainId, dstAddress, payload);\n        emit Packet(encodedPayload);\n    }\n\n    function _handleRelayer(uint16 _dstChainId, ApplicationConfiguration memory _uaConfig, address _ua, uint _payloadSize, bytes memory _adapterParams) internal returns (uint relayerFee) {\n        if (_adapterParams.length == 0) {\n            _adapterParams = defaultAdapterParams[_dstChainId][_uaConfig.outboundProofType];\n        }\n        address relayerAddress = _uaConfig.relayer;\n        ILayerZeroRelayerV2 relayer = ILayerZeroRelayerV2(relayerAddress);\n        relayerFee = relayer.assignJob(_dstChainId, _uaConfig.outboundProofType, _ua, _payloadSize, _adapterParams);\n\n        _creditNativeFee(relayerAddress, relayerFee);\n\n        // emit the param events\n        emit RelayerParams(_adapterParams, _uaConfig.outboundProofType);\n    }\n\n    function _handleOracle(uint16 _dstChainId, ApplicationConfiguration memory _uaConfig, address _ua) internal returns (uint oracleFee) {\n        address oracleAddress = _uaConfig.oracle;\n        oracleFee = ILayerZeroOracleV2(oracleAddress).assignJob(_dstChainId, _uaConfig.outboundProofType, _uaConfig.outboundBlockConfirmations, _ua);\n\n        _creditNativeFee(oracleAddress, oracleFee);\n    }\n\n    function _handleProtocolFee(uint _relayerFee, uint _oracleFee, address _ua, address _zroPaymentAddress) internal returns (uint protocolNativeFee) {\n        // if no ZRO token or not specifying a payment address, pay in native token\n        bool payInNative = _zroPaymentAddress == address(0x0) || address(layerZeroToken) == address(0x0);\n        uint protocolFee = treasuryContract.getFees(!payInNative, _relayerFee, _oracleFee);\n\n        if (protocolFee \u003e 0) {\n            if (payInNative) {\n                address treasuryAddress = address(treasuryContract);\n                _creditNativeFee(treasuryAddress, protocolFee);\n                protocolNativeFee = protocolFee;\n            } else {\n                // zro payment address must equal the ua or the tx.origin otherwise the transaction reverts\n                require(_zroPaymentAddress == _ua || _zroPaymentAddress == tx.origin, \"LayerZero: must be paid by sender or origin\");\n\n                // transfer the LayerZero token to this contract from the payee\n                layerZeroToken.safeTransferFrom(_zroPaymentAddress, address(this), protocolFee);\n\n                treasuryZROFees = treasuryZROFees.add(protocolFee);\n            }\n        }\n    }\n\n    function _creditNativeFee(address _receiver, uint _amount) internal {\n        nativeFees[_receiver] = nativeFees[_receiver].add(_amount);\n    }\n\n    // Can be called by any address to update a block header\n    // can only upload new block data or the same block data with more confirmations\n    function updateHash(uint16 _srcChainId, bytes32 _lookupHash, uint _confirmations, bytes32 _blockData) external override {\n        uint storedConfirmations = hashLookup[msg.sender][_srcChainId][_lookupHash][_blockData];\n\n        // if it has a record, requires a larger confirmation.\n        require(storedConfirmations \u003c _confirmations, \"LayerZero: oracle data can only update if it has more confirmations\");\n\n        // set the new information into storage\n        hashLookup[msg.sender][_srcChainId][_lookupHash][_blockData] = _confirmations;\n\n        emit HashReceived(_srcChainId, msg.sender, _lookupHash, _blockData, _confirmations);\n    }\n\n    //----------------------------------------------------------------------------------\n    // Other Library Interfaces\n\n    // default to DEFAULT setting if ZERO value\n    function getAppConfig(uint16 _remoteChainId, address _ua) external view override returns (ApplicationConfiguration memory) {\n        return _getAppConfig(_remoteChainId, _ua);\n    }\n\n    function _getAppConfig(uint16 _remoteChainId, address _ua) internal view returns (ApplicationConfiguration memory) {\n        ApplicationConfiguration memory config = appConfig[_ua][_remoteChainId];\n        ApplicationConfiguration storage defaultConfig = defaultAppConfig[_remoteChainId];\n\n        if (config.inboundProofLibraryVersion == 0) {\n            config.inboundProofLibraryVersion = defaultConfig.inboundProofLibraryVersion;\n        }\n\n        if (config.inboundBlockConfirmations == 0) {\n            config.inboundBlockConfirmations = defaultConfig.inboundBlockConfirmations;\n        }\n\n        if (config.relayer == address(0x0)) {\n            config.relayer = defaultConfig.relayer;\n        }\n\n        if (config.outboundProofType == 0) {\n            config.outboundProofType = defaultConfig.outboundProofType;\n        }\n\n        if (config.outboundBlockConfirmations == 0) {\n            config.outboundBlockConfirmations = defaultConfig.outboundBlockConfirmations;\n        }\n\n        if (config.oracle == address(0x0)) {\n            config.oracle = defaultConfig.oracle;\n        }\n\n        return config;\n    }\n\n    function setConfig(uint16 _remoteChainId, address _ua, uint _configType, bytes calldata _config) external override onlyEndpoint {\n        ApplicationConfiguration storage uaConfig = appConfig[_ua][_remoteChainId];\n        if (_configType == CONFIG_TYPE_INBOUND_PROOF_LIBRARY_VERSION) {\n            uint16 inboundProofLibraryVersion = abi.decode(_config, (uint16));\n            require(inboundProofLibraryVersion \u003c= maxInboundProofLibrary[_remoteChainId], \"LayerZero: invalid inbound proof library version\");\n            uaConfig.inboundProofLibraryVersion = inboundProofLibraryVersion;\n        } else if (_configType == CONFIG_TYPE_INBOUND_BLOCK_CONFIRMATIONS) {\n            uint64 blockConfirmations = abi.decode(_config, (uint64));\n            uaConfig.inboundBlockConfirmations = blockConfirmations;\n        } else if (_configType == CONFIG_TYPE_RELAYER) {\n            address relayer = abi.decode(_config, (address));\n            uaConfig.relayer = relayer;\n        } else if (_configType == CONFIG_TYPE_OUTBOUND_PROOF_TYPE) {\n            uint16 outboundProofType = abi.decode(_config, (uint16));\n            require(supportedOutboundProof[_remoteChainId][outboundProofType] || outboundProofType == 0, \"LayerZero: invalid outbound proof type\");\n            uaConfig.outboundProofType = outboundProofType;\n        } else if (_configType == CONFIG_TYPE_OUTBOUND_BLOCK_CONFIRMATIONS) {\n            uint64 blockConfirmations = abi.decode(_config, (uint64));\n            uaConfig.outboundBlockConfirmations = blockConfirmations;\n        } else if (_configType == CONFIG_TYPE_ORACLE) {\n            address oracle = abi.decode(_config, (address));\n            uaConfig.oracle = oracle;\n        } else {\n            revert(\"LayerZero: Invalid config type\");\n        }\n\n        emit AppConfigUpdated(_ua, _configType, _config);\n    }\n\n    function getConfig(uint16 _remoteChainId, address _ua, uint _configType) external view override returns (bytes memory) {\n        ApplicationConfiguration storage uaConfig = appConfig[_ua][_remoteChainId];\n\n        if (_configType == CONFIG_TYPE_INBOUND_PROOF_LIBRARY_VERSION) {\n            if (uaConfig.inboundProofLibraryVersion == 0) {\n                return abi.encode(defaultAppConfig[_remoteChainId].inboundProofLibraryVersion);\n            }\n            return abi.encode(uaConfig.inboundProofLibraryVersion);\n        } else if (_configType == CONFIG_TYPE_INBOUND_BLOCK_CONFIRMATIONS) {\n            if (uaConfig.inboundBlockConfirmations == 0) {\n                return abi.encode(defaultAppConfig[_remoteChainId].inboundBlockConfirmations);\n            }\n            return abi.encode(uaConfig.inboundBlockConfirmations);\n        } else if (_configType == CONFIG_TYPE_RELAYER) {\n            if (uaConfig.relayer == address(0x0)) {\n                return abi.encode(defaultAppConfig[_remoteChainId].relayer);\n            }\n            return abi.encode(uaConfig.relayer);\n        } else if (_configType == CONFIG_TYPE_OUTBOUND_PROOF_TYPE) {\n            if (uaConfig.outboundProofType == 0) {\n                return abi.encode(defaultAppConfig[_remoteChainId].outboundProofType);\n            }\n            return abi.encode(uaConfig.outboundProofType);\n        } else if (_configType == CONFIG_TYPE_OUTBOUND_BLOCK_CONFIRMATIONS) {\n            if (uaConfig.outboundBlockConfirmations == 0) {\n                return abi.encode(defaultAppConfig[_remoteChainId].outboundBlockConfirmations);\n            }\n            return abi.encode(uaConfig.outboundBlockConfirmations);\n        } else if (_configType == CONFIG_TYPE_ORACLE) {\n            if (uaConfig.oracle == address(0x0)) {\n                return abi.encode(defaultAppConfig[_remoteChainId].oracle);\n            }\n            return abi.encode(uaConfig.oracle);\n        } else {\n            revert(\"LayerZero: Invalid config type\");\n        }\n    }\n\n    // returns the native fee the UA pays to cover fees\n    function estimateFees(uint16 _dstChainId, address _ua, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParams) external view override returns (uint nativeFee, uint zroFee) {\n        ApplicationConfiguration memory uaConfig = _getAppConfig(_dstChainId, _ua);\n\n        // Relayer Fee\n        bytes memory adapterParams;\n        if (_adapterParams.length \u003e 0) {\n            adapterParams = _adapterParams;\n        } else {\n            adapterParams = defaultAdapterParams[_dstChainId][uaConfig.outboundProofType];\n        }\n        uint relayerFee = ILayerZeroRelayerV2(uaConfig.relayer).getFee(_dstChainId, uaConfig.outboundProofType, _ua, _payload.length, adapterParams);\n\n        // Oracle Fee\n        address ua = _ua; // stack too deep\n        uint oracleFee = ILayerZeroOracleV2(uaConfig.oracle).getFee(_dstChainId, uaConfig.outboundProofType, uaConfig.outboundBlockConfirmations, ua);\n\n        // LayerZero Fee\n        uint protocolFee = treasuryContract.getFees(_payInZRO, relayerFee, oracleFee);\n        _payInZRO ? zroFee = protocolFee : nativeFee = protocolFee;\n\n        // return the sum of fees\n        nativeFee = nativeFee.add(relayerFee).add(oracleFee);\n    }\n\n    //---------------------------------------------------------------------------\n    // Claim Fees\n\n    // universal withdraw ZRO token function\n    function withdrawZRO(address _to, uint _amount) external override nonReentrant {\n        require(msg.sender == address(treasuryContract), \"LayerZero: only treasury\");\n        treasuryZROFees = treasuryZROFees.sub(_amount);\n        layerZeroToken.safeTransfer(_to, _amount);\n        emit WithdrawZRO(msg.sender, _to, _amount);\n    }\n\n    // universal withdraw native token function.\n    // the source contract should perform all the authentication control\n    function withdrawNative(address payable _to, uint _amount) external override nonReentrant {\n        require(_to != address(0x0), \"LayerZero: _to cannot be zero address\");\n        nativeFees[msg.sender] = nativeFees[msg.sender].sub(_amount);\n\n        (bool success, ) = _to.call{value: _amount}(\"\");\n        require(success, \"LayerZero: withdraw failed\");\n        emit WithdrawNative(msg.sender, _to, _amount);\n    }\n\n    //---------------------------------------------------------------------------\n    // Owner calls, configuration only.\n    function setLayerZeroToken(address _layerZeroToken) external onlyOwner {\n        require(_layerZeroToken != address(0x0), \"LayerZero: _layerZeroToken cannot be zero address\");\n        layerZeroToken = IERC20(_layerZeroToken);\n        emit SetLayerZeroToken(_layerZeroToken);\n    }\n\n    function setTreasury(address _treasury) external onlyOwner {\n        require(_treasury != address(0x0), \"LayerZero: treasury cannot be zero address\");\n        treasuryContract = ILayerZeroTreasury(_treasury);\n        emit SetTreasury(_treasury);\n    }\n\n    function addInboundProofLibraryForChain(uint16 _chainId, address _library) external onlyOwner {\n        require(_library != address(0x0), \"LayerZero: library cannot be zero address\");\n        uint16 libId = maxInboundProofLibrary[_chainId];\n        require(libId \u003c 65535, \"LayerZero: can not add new library\");\n        maxInboundProofLibrary[_chainId] = ++libId;\n        inboundProofLibrary[_chainId][libId] = _library;\n        emit AddInboundProofLibraryForChain(_chainId, _library);\n    }\n\n    function enableSupportedOutboundProof(uint16 _chainId, uint16 _proofType) external onlyOwner {\n        supportedOutboundProof[_chainId][_proofType] = true;\n        emit EnableSupportedOutboundProof(_chainId, _proofType);\n    }\n\n    function setDefaultConfigForChainId(uint16 _chainId, uint16 _inboundProofLibraryVersion, uint64 _inboundBlockConfirmations, address _relayer, uint16 _outboundProofType, uint64 _outboundBlockConfirmations, address _oracle) external onlyOwner {\n        require(_inboundProofLibraryVersion \u003c= maxInboundProofLibrary[_chainId] \u0026\u0026 _inboundProofLibraryVersion \u003e 0, \"LayerZero: invalid inbound proof library version\");\n        require(_inboundBlockConfirmations \u003e 0, \"LayerZero: invalid inbound block confirmation\");\n        require(_relayer != address(0x0), \"LayerZero: invalid relayer address\");\n        require(supportedOutboundProof[_chainId][_outboundProofType], \"LayerZero: invalid outbound proof type\");\n        require(_outboundBlockConfirmations \u003e 0, \"LayerZero: invalid outbound block confirmation\");\n        require(_oracle != address(0x0), \"LayerZero: invalid oracle address\");\n        defaultAppConfig[_chainId] = ApplicationConfiguration(_inboundProofLibraryVersion, _inboundBlockConfirmations, _relayer, _outboundProofType, _outboundBlockConfirmations, _oracle);\n        emit SetDefaultConfigForChainId(_chainId, _inboundProofLibraryVersion, _inboundBlockConfirmations, _relayer, _outboundProofType, _outboundBlockConfirmations, _oracle);\n    }\n\n    function setDefaultAdapterParamsForChainId(uint16 _chainId, uint16 _proofType, bytes calldata _adapterParams) external onlyOwner {\n        defaultAdapterParams[_chainId][_proofType] = _adapterParams;\n        emit SetDefaultAdapterParamsForChainId(_chainId, _proofType, _adapterParams);\n    }\n\n    function setRemoteUln(uint16 _remoteChainId, bytes32 _remoteUln) external onlyOwner {\n        require(ulnLookup[_remoteChainId] == bytes32(0), \"LayerZero: remote uln already set\");\n        ulnLookup[_remoteChainId] = _remoteUln;\n        emit SetRemoteUln(_remoteChainId, _remoteUln);\n    }\n\n    function setChainAddressSize(uint16 _chainId, uint _size) external onlyOwner {\n        require(chainAddressSizeMap[_chainId] == 0, \"LayerZero: remote chain address size already set\");\n        chainAddressSizeMap[_chainId] = _size;\n        emit SetChainAddressSize(_chainId, _size);\n    }\n\n    //----------------------------------------------------------------------------------\n    // view functions\n\n    function accruedNativeFee(address _address) external view override returns (uint) {\n        return nativeFees[_address];\n    }\n\n    function getOutboundNonce(uint16 _chainId, bytes calldata _path) external view override returns (uint64) {\n        return nonceContract.outboundNonce(_chainId, _path);\n    }\n\n    function _isContract(address addr) internal view returns (bool) {\n        uint size;\n        assembly {\n            size := extcodesize(addr)\n        }\n        return size != 0;\n    }\n}\n"}}

                              File 6 of 16: OptimizedTransparentUpgradeableProxy
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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 {
                                      // 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 virtual view 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 {
                                      _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 () payable external {
                                      _fallback();
                                  }
                                  /**
                                   * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                                   * is empty.
                                   */
                                  receive () payable external {
                                      _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.7.0;
                              import "./Proxy.sol";
                              import "../utils/Address.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.
                               * 
                               * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see
                               * {TransparentUpgradeableProxy}.
                               */
                              contract UpgradeableProxy is Proxy {
                                  /**
                                   * @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));
                                      _setImplementation(_logic);
                                      if(_data.length > 0) {
                                          // solhint-disable-next-line avoid-low-level-calls
                                          (bool success,) = _logic.delegatecall(_data);
                                          require(success);
                                      }
                                  }
                                  /**
                                   * @dev Emitted when the implementation is upgraded.
                                   */
                                  event Upgraded(address indexed implementation);
                                  /**
                                   * @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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                                  /**
                                   * @dev Returns the current implementation address.
                                   */
                                  function _implementation() internal override view returns (address impl) {
                                      bytes32 slot = _IMPLEMENTATION_SLOT;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          impl := sload(slot)
                                      }
                                  }
                                  /**
                                   * @dev Upgrades the proxy to a new implementation.
                                   * 
                                   * Emits an {Upgraded} event.
                                   */
                                  function _upgradeTo(address newImplementation) internal {
                                      _setImplementation(newImplementation);
                                      emit Upgraded(newImplementation);
                                  }
                                  /**
                                   * @dev Stores a new address in the EIP1967 implementation slot.
                                   */
                                  function _setImplementation(address newImplementation) private {
                                      require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract");
                                      bytes32 slot = _IMPLEMENTATION_SLOT;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          sstore(slot, newImplementation)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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) {
                                      // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                      // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                      // for accounts without code, i.e. `keccak256('')`
                                      bytes32 codehash;
                                      bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly { codehash := extcodehash(account) }
                                      return (codehash != accountHash && codehash != 0x0);
                                  }
                                  /**
                                   * @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");
                                      return _functionCallWithValue(target, data, value, errorMessage);
                                  }
                                  function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
                                      require(isContract(target), "Address: call to non-contract");
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
                                      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.7.0;
                              import "../openzeppelin/proxy/UpgradeableProxy.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 inerface of your proxy.
                               */
                              contract OptimizedTransparentUpgradeableProxy is UpgradeableProxy {
                                  address internal immutable _ADMIN;
                                  /**
                                   * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                                   * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}.
                                   */
                                  constructor(
                                      address initialLogic,
                                      address initialAdmin,
                                      bytes memory _data
                                  ) payable UpgradeableProxy(initialLogic, _data) {
                                      assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                                      bytes32 slot = _ADMIN_SLOT;
                                      _ADMIN = initialAdmin;
                                      // still store it to work with EIP-1967
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          sstore(slot, initialAdmin)
                                      }
                                  }
                                  /**
                                   * @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 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                                  /**
                                   * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                                   */
                                  modifier ifAdmin() {
                                      if (msg.sender == _admin()) {
                                          _;
                                      } 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) {
                                      return _admin();
                                  }
                                  /**
                                   * @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) {
                                      return _implementation();
                                  }
                                  /**
                                   * @dev Upgrade the implementation of the proxy.
                                   *
                                   * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                                   */
                                  function upgradeTo(address newImplementation) external ifAdmin {
                                      _upgradeTo(newImplementation);
                                  }
                                  /**
                                   * @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 {
                                      _upgradeTo(newImplementation);
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, ) = newImplementation.delegatecall(data);
                                      require(success);
                                  }
                                  /**
                                   * @dev Returns the current admin.
                                   */
                                  function _admin() internal view returns (address adm) {
                                      return _ADMIN;
                                  }
                                  /**
                                   * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                                   */
                                  function _beforeFallback() internal virtual override {
                                      require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                                      super._beforeFallback();
                                  }
                              }
                              

                              File 7 of 16: Bridge
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              import "./Router.sol";
                              // interfaces
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroReceiver.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroEndpoint.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroUserApplicationConfig.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract Bridge is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  uint8 internal constant TYPE_SWAP_REMOTE = 1;
                                  uint8 internal constant TYPE_ADD_LIQUIDITY = 2;
                                  uint8 internal constant TYPE_REDEEM_LOCAL_CALL_BACK = 3;
                                  uint8 internal constant TYPE_WITHDRAW_REMOTE = 4;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  ILayerZeroEndpoint public immutable layerZeroEndpoint;
                                  mapping(uint16 => bytes) public bridgeLookup;
                                  mapping(uint16 => mapping(uint8 => uint256)) public gasLookup;
                                  Router public immutable router;
                                  bool public useLayerZeroToken;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event SendMsg(uint8 msgType, uint64 nonce);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == address(router), "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _layerZeroEndpoint, address _router) {
                                      require(_layerZeroEndpoint != address(0x0), "Stargate: _layerZeroEndpoint cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      layerZeroEndpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
                                      router = Router(_router);
                                  }
                                  //---------------------------------------------------------------------------
                                  // EXTERNAL functions
                                  function lzReceive(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint64 _nonce,
                                      bytes memory _payload
                                  ) external override {
                                      require(msg.sender == address(layerZeroEndpoint), "Stargate: only LayerZero endpoint can call lzReceive");
                                      require(
                                          _srcAddress.length == bridgeLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(bridgeLookup[_srcChainId]),
                                          "Stargate: bridge does not match"
                                      );
                                      uint8 functionType;
                                      assembly {
                                          functionType := mload(add(_payload, 32))
                                      }
                                      if (functionType == TYPE_SWAP_REMOTE) {
                                          (
                                              ,
                                              uint256 srcPoolId,
                                              uint256 dstPoolId,
                                              uint256 dstGasForCall,
                                              Pool.CreditObj memory c,
                                              Pool.SwapObj memory s,
                                              bytes memory to,
                                              bytes memory payload
                                          ) = abi.decode(_payload, (uint8, uint256, uint256, uint256, Pool.CreditObj, Pool.SwapObj, bytes, bytes));
                                          address toAddress;
                                          assembly {
                                              toAddress := mload(add(to, 20))
                                          }
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.swapRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, dstGasForCall, toAddress, s, payload);
                                      } else if (functionType == TYPE_ADD_LIQUIDITY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c) = abi.decode(_payload, (uint8, uint256, uint256, Pool.CreditObj));
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                      } else if (functionType == TYPE_REDEEM_LOCAL_CALL_BACK) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c, uint256 amountSD, uint256 mintAmountSD, bytes memory to) = abi
                                              .decode(_payload, (uint8, uint256, uint256, Pool.CreditObj, uint256, uint256, bytes));
                                          address toAddress;
                                          assembly {
                                              toAddress := mload(add(to, 20))
                                          }
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.redeemLocalCallback(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, toAddress, amountSD, mintAmountSD);
                                      } else if (functionType == TYPE_WITHDRAW_REMOTE) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c, uint256 amountSD, bytes memory to) = abi.decode(
                                              _payload,
                                              (uint8, uint256, uint256, Pool.CreditObj, uint256, bytes)
                                          );
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.redeemLocalCheckOnRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, amountSD, to);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function swap(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      Pool.SwapObj memory _s,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes calldata _to,
                                      bytes calldata _payload
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_SWAP_REMOTE, _srcPoolId, _dstPoolId, _lzTxParams.dstGasForCall, _c, _s, _to, _payload);
                                      _call(_chainId, TYPE_SWAP_REMOTE, _refundAddress, _lzTxParams, payload);
                                  }
                                  function redeemLocalCallback(
                                      uint16 _chainId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes memory _payload
                                  ) external payable onlyRouter {
                                      bytes memory payload;
                                      {
                                          (, uint256 srcPoolId, uint256 dstPoolId, uint256 amountSD, uint256 mintAmountSD, bytes memory to) = abi.decode(
                                              _payload,
                                              (uint8, uint256, uint256, uint256, uint256, bytes)
                                          );
                                          // swap dst and src because we are headed back
                                          payload = abi.encode(TYPE_REDEEM_LOCAL_CALL_BACK, dstPoolId, srcPoolId, _c, amountSD, mintAmountSD, to);
                                      }
                                      _call(_chainId, TYPE_REDEEM_LOCAL_CALL_BACK, _refundAddress, _lzTxParams, payload);
                                  }
                                  function redeemLocal(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      uint256 _amountSD,
                                      bytes calldata _to,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_WITHDRAW_REMOTE, _srcPoolId, _dstPoolId, _c, _amountSD, _to);
                                      _call(_chainId, TYPE_WITHDRAW_REMOTE, _refundAddress, _lzTxParams, payload);
                                  }
                                  function sendCredits(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_ADD_LIQUIDITY, _srcPoolId, _dstPoolId, _c);
                                      IStargateRouter.lzTxObj memory lzTxObj = IStargateRouter.lzTxObj(0, 0, "0x");
                                      _call(_chainId, TYPE_ADD_LIQUIDITY, _refundAddress, lzTxObj, payload);
                                  }
                                  function quoteLayerZeroFee(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256) {
                                      bytes memory payload = "";
                                      Pool.CreditObj memory c = Pool.CreditObj(1, 1);
                                      if (_functionType == TYPE_SWAP_REMOTE) {
                                          Pool.SwapObj memory s = Pool.SwapObj(1, 1, 1, 1, 1, 1);
                                          payload = abi.encode(TYPE_SWAP_REMOTE, 0, 0, 0, c, s, _toAddress, _transferAndCallPayload);
                                      } else if (_functionType == TYPE_ADD_LIQUIDITY) {
                                          payload = abi.encode(TYPE_ADD_LIQUIDITY, 0, 0, c);
                                      } else if (_functionType == TYPE_REDEEM_LOCAL_CALL_BACK) {
                                          payload = abi.encode(TYPE_REDEEM_LOCAL_CALL_BACK, 0, 0, c, 0, 0, _toAddress);
                                      } else if (_functionType == TYPE_WITHDRAW_REMOTE) {
                                          payload = abi.encode(TYPE_WITHDRAW_REMOTE, 0, 0, c, 0, _toAddress);
                                      } else {
                                          revert("Stargate: unsupported function type");
                                      }
                                      bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _functionType, _lzTxParams);
                                      return layerZeroEndpoint.estimateFees(_chainId, address(this), payload, useLayerZeroToken, lzTxParamBuilt);
                                  }
                                  //---------------------------------------------------------------------------
                                  // dao functions
                                  function setBridge(uint16 _chainId, bytes calldata _bridgeAddress) external onlyOwner {
                                      require(bridgeLookup[_chainId].length == 0, "Stargate: Bridge already set!");
                                      bridgeLookup[_chainId] = _bridgeAddress;
                                  }
                                  function setGasAmount(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      uint256 _gasAmount
                                  ) external onlyOwner {
                                      require(_functionType >= 1 && _functionType <= 4, "Stargate: invalid _functionType");
                                      gasLookup[_chainId][_functionType] = _gasAmount;
                                  }
                                  function approveTokenSpender(
                                      address token,
                                      address spender,
                                      uint256 amount
                                  ) external onlyOwner {
                                      IERC20(token).approve(spender, amount);
                                  }
                                  function setUseLayerZeroToken(bool enable) external onlyOwner {
                                      useLayerZeroToken = enable;
                                  }
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                                      layerZeroEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
                                  }
                                  //---------------------------------------------------------------------------
                                  // generic config for user Application
                                  function setConfig(
                                      uint16 _version,
                                      uint16 _chainId,
                                      uint256 _configType,
                                      bytes calldata _config
                                  ) external override onlyOwner {
                                      layerZeroEndpoint.setConfig(_version, _chainId, _configType, _config);
                                  }
                                  function setSendVersion(uint16 version) external override onlyOwner {
                                      layerZeroEndpoint.setSendVersion(version);
                                  }
                                  function setReceiveVersion(uint16 version) external override onlyOwner {
                                      layerZeroEndpoint.setReceiveVersion(version);
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL functions
                                  function txParamBuilderType1(uint256 _gasAmount) internal pure returns (bytes memory) {
                                      uint16 txType = 1;
                                      return abi.encodePacked(txType, _gasAmount);
                                  }
                                  function txParamBuilderType2(
                                      uint256 _gasAmount,
                                      uint256 _dstNativeAmount,
                                      bytes memory _dstNativeAddr
                                  ) internal pure returns (bytes memory) {
                                      uint16 txType = 2;
                                      return abi.encodePacked(txType, _gasAmount, _dstNativeAmount, _dstNativeAddr);
                                  }
                                  function _txParamBuilder(
                                      uint16 _chainId,
                                      uint8 _type,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) internal view returns (bytes memory) {
                                      bytes memory lzTxParam;
                                      address dstNativeAddr;
                                      {
                                          bytes memory dstNativeAddrBytes = _lzTxParams.dstNativeAddr;
                                          assembly {
                                              dstNativeAddr := mload(add(dstNativeAddrBytes, 20))
                                          }
                                      }
                                      uint256 totalGas = gasLookup[_chainId][_type].add(_lzTxParams.dstGasForCall);
                                      if (_lzTxParams.dstNativeAmount > 0 && dstNativeAddr != address(0x0)) {
                                          lzTxParam = txParamBuilderType2(totalGas, _lzTxParams.dstNativeAmount, _lzTxParams.dstNativeAddr);
                                      } else {
                                          lzTxParam = txParamBuilderType1(totalGas);
                                      }
                                      return lzTxParam;
                                  }
                                  function _call(
                                      uint16 _chainId,
                                      uint8 _type,
                                      address payable _refundAddress,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes memory _payload
                                  ) internal {
                                      bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _type, _lzTxParams);
                                      uint64 nextNonce = layerZeroEndpoint.getOutboundNonce(_chainId, address(this)) + 1;
                                      layerZeroEndpoint.send{value: msg.value}(_chainId, bridgeLookup[_chainId], _payload, _refundAddress, address(this), lzTxParamBuilt);
                                      emit SendMsg(_type, nextNonce);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./LPTokenERC20.sol";
                              import "./interfaces/IStargateFeeLibrary.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              /// Pool contracts on other chains and managed by the Stargate protocol.
                              contract Pool is LPTokenERC20, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 public constant BP_DENOMINATOR = 10000;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct ChainPath {
                                      bool ready; // indicate if the counter chainPath has been created.
                                      uint16 dstChainId;
                                      uint256 dstPoolId;
                                      uint256 weight;
                                      uint256 balance;
                                      uint256 lkb;
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  struct SwapObj {
                                      uint256 amount;
                                      uint256 eqFee;
                                      uint256 eqReward;
                                      uint256 lpFee;
                                      uint256 protocolFee;
                                      uint256 lkbRemove;
                                  }
                                  struct CreditObj {
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // chainPath
                                  ChainPath[] public chainPaths; // list of connected chains with shared pools
                                  mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
                                  // metadata
                                  uint256 public immutable poolId; // shared id between chains to represent same pool
                                  uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
                                  uint256 public localDecimals; // the decimals for the token
                                  uint256 public immutable convertRate; // the decimals for the token
                                  address public immutable token; // the token for the pool
                                  address public immutable router; // the token for the pool
                                  bool public stopSwap; // flag to stop swapping in extreme cases
                                  // Fee and Liquidity
                                  uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
                                  uint256 public totalWeight; // total weight for pool percentages
                                  uint256 public mintFeeBP; // fee basis points for the mint/deposit
                                  uint256 public protocolFeeBalance; // fee balance created from dao fee
                                  uint256 public mintFeeBalance; // fee balance created from mint fee
                                  uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
                                  address public feeLibrary; // address for retrieving fee params for swaps
                                  // Delta related
                                  uint256 public deltaCredit; // credits accumulated from txn
                                  bool public batched; // flag to indicate if we want batch processing.
                                  bool public defaultSwapMode; // flag for the default mode for swap
                                  bool public defaultLPMode; // flag for the default mode for lp
                                  uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
                                  uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
                                  event Burn(address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
                                  event Swap(
                                      uint16 chainId,
                                      uint256 dstPoolId,
                                      address from,
                                      uint256 amountSD,
                                      uint256 eqReward,
                                      uint256 eqFee,
                                      uint256 protocolFee,
                                      uint256 lpFee
                                  );
                                  event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
                                  event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
                                  event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
                                  event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
                                  event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
                                  event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
                                  event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
                                  event FeesUpdated(uint256 mintFeeBP);
                                  event FeeLibraryUpdated(address feeLibraryAddr);
                                  event StopSwapUpdated(bool swapStop);
                                  event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
                                  event WithdrawMintFeeBalance(address to, uint256 amountSD);
                                  event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: only the router can call this method");
                                      _;
                                  }
                                  constructor(
                                      uint256 _poolId,
                                      address _router,
                                      address _token,
                                      uint256 _sharedDecimals,
                                      uint256 _localDecimals,
                                      address _feeLibrary,
                                      string memory _name,
                                      string memory _symbol
                                  ) LPTokenERC20(_name, _symbol) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      poolId = _poolId;
                                      router = _router;
                                      token = _token;
                                      sharedDecimals = _sharedDecimals;
                                      decimals = uint8(_sharedDecimals);
                                      localDecimals = _localDecimals;
                                      convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
                                      totalWeight = 0;
                                      feeLibrary = _feeLibrary;
                                      //delta algo related
                                      batched = false;
                                      defaultSwapMode = true;
                                      defaultLPMode = true;
                                  }
                                  function getChainPathsLength() public view returns (uint256) {
                                      return chainPaths.length;
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
                                      return _mintLocal(_to, _amountLD, true, true);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      bool newLiquidity
                                  ) external nonReentrant onlyRouter returns (SwapObj memory) {
                                      require(!stopSwap, "Stargate: swap func stopped");
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      uint256 amountSD = amountLDtoSD(_amountLD);
                                      uint256 minAmountSD = amountLDtoSD(_minAmountLD);
                                      // request fee params from library
                                      SwapObj memory s = IStargateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
                                      // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
                                      eqFeePool = eqFeePool.sub(s.eqReward);
                                      // update the new amount the user gets minus the fees
                                      s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
                                      // users will also get the eqReward
                                      require(s.amount.add(s.eqReward) >= minAmountSD, "Stargate: slippage too high");
                                      // behaviours
                                      //     - protocolFee: booked, stayed and withdrawn at remote.
                                      //     - eqFee: booked, stayed and withdrawn at remote.
                                      //     - lpFee: booked and stayed at remote, can be withdrawn anywhere
                                      s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
                                      // check for transfer solvency.
                                      require(cp.balance >= s.lkbRemove, "Stargate: dst balance too low");
                                      cp.balance = cp.balance.sub(s.lkbRemove);
                                      if (newLiquidity) {
                                          deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
                                      } else if (s.eqReward > 0) {
                                          deltaCredit = deltaCredit.add(s.eqReward);
                                      }
                                      // distribute credits on condition.
                                      if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultSwapMode);
                                      }
                                      emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
                                      return s;
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      cp.lkb = cp.lkb.add(cp.credits);
                                      c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
                                      c.credits = cp.credits;
                                      cp.credits = 0;
                                      emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemRemote   ->                        swapRemote
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLP
                                  ) external nonReentrant onlyRouter {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 amountSD = _burnLocal(_from, _amountLP);
                                      //run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
                                  }
                                  function instantRedeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      address _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 _deltaCredit = deltaCredit; // sload optimization.
                                      uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
                                      if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
                                      amountSD = _burnLocal(_from, _amountLP);
                                      deltaCredit = _deltaCredit.sub(amountSD);
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      bytes calldata _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      // safeguard.
                                      require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Stargate: counter chainPath is not ready");
                                      amountSD = _burnLocal(_from, _amountLP);
                                      // run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(false);
                                      }
                                      emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      CreditObj memory _c
                                  ) external nonReentrant onlyRouter {
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      cp.balance = cp.balance.add(_c.credits);
                                      if (cp.idealBalance != _c.idealBalance) {
                                          cp.idealBalance = _c.idealBalance;
                                      }
                                      emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      SwapObj memory _s
                                  ) external nonReentrant onlyRouter returns (uint256 amountLD) {
                                      // booking lpFee
                                      totalLiquidity = totalLiquidity.add(_s.lpFee);
                                      // booking eqFee
                                      eqFeePool = eqFeePool.add(_s.eqFee);
                                      // booking stargateFee
                                      protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
                                      // update LKB
                                      uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
                                      chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
                                      // user receives the amount + the srcReward
                                      amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
                                      _safeTransfer(token, _to, amountLD);
                                      emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _amountToMintSD
                                  ) external nonReentrant onlyRouter {
                                      if (_amountToMintSD > 0) {
                                          _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
                                      }
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      cp.lkb = cp.lkb.sub(_amountSD);
                                      uint256 amountLD = amountSDtoLD(_amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal(amount)   ->               redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      uint256 _amountSD
                                  ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      if (_amountSD > cp.balance) {
                                          mintAmount = _amountSD - cp.balance;
                                          swapAmount = cp.balance;
                                          cp.balance = 0;
                                      } else {
                                          cp.balance = cp.balance.sub(_amountSD);
                                          swapAmount = _amountSD;
                                          mintAmount = 0;
                                      }
                                      emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyRouter {
                                      for (uint256 i = 0; i < chainPaths.length; ++i) {
                                          ChainPath memory cp = chainPaths[i];
                                          bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
                                          require(!exists, "Stargate: cant createChainPath of existing dstChainId and _dstPoolId");
                                      }
                                      totalWeight = totalWeight.add(_weight);
                                      chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
                                      chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setWeightForChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      totalWeight = totalWeight.sub(cp.weight).add(_weight);
                                      cp.weight = _weight;
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setFee(uint256 _mintFeeBP) external onlyRouter {
                                      require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
                                      mintFeeBP = _mintFeeBP;
                                      emit FeesUpdated(mintFeeBP);
                                  }
                                  function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
                                      require(_feeLibraryAddr != address(0x0), "Stargate: fee library cant be 0x0");
                                      feeLibrary = _feeLibraryAddr;
                                      emit FeeLibraryUpdated(_feeLibraryAddr);
                                  }
                                  function setSwapStop(bool _swapStop) external onlyRouter {
                                      stopSwap = _swapStop;
                                      emit StopSwapUpdated(_swapStop);
                                  }
                                  function setDeltaParam(
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyRouter {
                                      require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Stargate: wrong Delta param");
                                      batched = _batched;
                                      swapDeltaBP = _swapDeltaBP;
                                      lpDeltaBP = _lpDeltaBP;
                                      defaultSwapMode = _defaultSwapMode;
                                      defaultLPMode = _defaultLPMode;
                                      emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(bool _fullMode) external onlyRouter {
                                      _delta(_fullMode);
                                  }
                                  function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == false, "Stargate: chainPath is already active");
                                      // this func will only be called once
                                      cp.ready = true;
                                  }
                                  function withdrawProtocolFeeBalance(address _to) external onlyRouter {
                                      if (protocolFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
                                          protocolFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawProtocolFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  function withdrawMintFeeBalance(address _to) external onlyRouter {
                                      if (mintFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
                                          mintFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawMintFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  // Conversion Helpers
                                  //---------------------------------------------------------------------------
                                  function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
                                      return amountSDtoLD(_amountLPtoSD(_amountLP));
                                  }
                                  function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant convert LPtoSD when totalSupply == 0");
                                      return _amountLP.mul(totalLiquidity).div(totalSupply);
                                  }
                                  function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
                                      require(totalLiquidity > 0, "Stargate: cant convert SDtoLP when totalLiq == 0");
                                      return _amountSD.mul(totalSupply).div(totalLiquidity);
                                  }
                                  function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.mul(convertRate);
                                  }
                                  function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.div(convertRate);
                                  }
                                  function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
                                      require(chainPaths.length > 0, "Stargate: no chainpaths exist");
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
                                      ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant burn when totalSupply == 0");
                                      uint256 amountOfLPTokens = balanceOf[_from];
                                      require(amountOfLPTokens >= _amountLP, "Stargate: not enough LP tokens to burn");
                                      uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
                                      //subtract totalLiquidity accordingly
                                      totalLiquidity = totalLiquidity.sub(amountSD);
                                      _burn(_from, _amountLP);
                                      emit Burn(_from, _amountLP, amountSD);
                                      return amountSD;
                                  }
                                  function _delta(bool fullMode) internal {
                                      if (deltaCredit > 0 && totalWeight > 0) {
                                          uint256 cpLength = chainPaths.length;
                                          uint256[] memory deficit = new uint256[](cpLength);
                                          uint256 totalDeficit = 0;
                                          // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
                                          for (uint256 i = 0; i < cpLength; ++i) {
                                              ChainPath storage cp = chainPaths[i];
                                              // (liquidity * (weight/totalWeight)) - (lkb+credits)
                                              uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
                                              uint256 currLiq = cp.lkb.add(cp.credits);
                                              if (balLiq > currLiq) {
                                                  // save gas since we know balLiq > currLiq and we know deficit[i] > 0
                                                  deficit[i] = balLiq - currLiq;
                                                  totalDeficit = totalDeficit.add(deficit[i]);
                                              }
                                          }
                                          // indicates how much delta credit is distributed
                                          uint256 spent;
                                          // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
                                          // run full Delta, allocate all credits
                                          if (totalDeficit == 0) {
                                              // only fullMode delta will allocate excess credits
                                              if (fullMode && deltaCredit > 0) {
                                                  // credit ChainPath by weights
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      // credits = credits + toBalanceChange + remaining allocation based on weight
                                                      uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
                                                      spent = spent.add(amtToCredit);
                                                      cp.credits = cp.credits.add(amtToCredit);
                                                  }
                                              } // else do nth
                                          } else if (totalDeficit <= deltaCredit) {
                                              if (fullMode) {
                                                  // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
                                                  uint256 excessCredit = deltaCredit - totalDeficit;
                                                  // algorithm steps 14-16: calculate credits
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          // credits = credits + deficit + remaining allocation based on weight
                                                          uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              } else {
                                                  // totalDeficit <= deltaCredit but not running fullMode
                                                  // credit chainPaths as is if any deficit, not using all deltaCredit
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          uint256 amtToCredit = deficit[i];
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              }
                                          } else {
                                              // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
                                              for (uint256 i = 0; i < cpLength; ++i) {
                                                  if (deficit[i] > 0) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
                                                      spent = spent.add(proportionalDeficit);
                                                      cp.credits = cp.credits.add(proportionalDeficit);
                                                  }
                                              }
                                          }
                                          // deduct the amount of credit sent
                                          deltaCredit = deltaCredit.sub(spent);
                                      }
                                  }
                                  function _mintLocal(
                                      address _to,
                                      uint256 _amountLD,
                                      bool _feesEnabled,
                                      bool _creditDelta
                                  ) internal returns (uint256 amountSD) {
                                      require(totalWeight > 0, "Stargate: No ChainPaths exist");
                                      amountSD = amountLDtoSD(_amountLD);
                                      uint256 mintFeeSD = 0;
                                      if (_feesEnabled) {
                                          mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
                                          amountSD = amountSD.sub(mintFeeSD);
                                          mintFeeBalance = mintFeeBalance.add(mintFeeSD);
                                      }
                                      if (_creditDelta) {
                                          deltaCredit = deltaCredit.add(amountSD);
                                      }
                                      uint256 amountLPTokens = amountSD;
                                      if (totalSupply != 0) {
                                          amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
                                      }
                                      totalLiquidity = totalLiquidity.add(amountSD);
                                      _mint(_to, amountLPTokens);
                                      emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
                                      // add to credits and call delta. short circuit to save gas
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                  }
                                  function _safeTransfer(
                                      address _token,
                                      address _to,
                                      uint256 _value
                                  ) private {
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
                                      require(success && (data.length == 0 || abi.decode(data, (bool))), "Stargate: TRANSFER_FAILED");
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./Factory.sol";
                              import "./Pool.sol";
                              import "./Bridge.sol";
                              // interfaces
                              import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              import "./interfaces/IStargateRouter.sol";
                              import "./interfaces/IStargateReceiver.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract Router is IStargateRouter, Ownable, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  uint8 internal constant TYPE_REDEEM_LOCAL_RESPONSE = 1;
                                  uint8 internal constant TYPE_REDEEM_LOCAL_CALLBACK_RETRY = 2;
                                  uint8 internal constant TYPE_SWAP_REMOTE_RETRY = 3;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct CachedSwap {
                                      address token;
                                      uint256 amountLD;
                                      address to;
                                      bytes payload;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  Factory public factory; // used for creating pools
                                  address public protocolFeeOwner; // can call methods to pull Stargate fees collected in pools
                                  address public mintFeeOwner; // can call methods to pull mint fees collected in pools
                                  Bridge public bridge;
                                  mapping(uint16 => mapping(bytes => mapping(uint256 => bytes))) public revertLookup; //[chainId][srcAddress][nonce]
                                  mapping(uint16 => mapping(bytes => mapping(uint256 => CachedSwap))) public cachedSwapLookup; //[chainId][srcAddress][nonce]
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Revert(uint8 bridgeFunctionType, uint16 chainId, bytes srcAddress, uint256 nonce);
                                  event CachedSwapSaved(uint16 chainId, bytes srcAddress, uint256 nonce, address token, uint256 amountLD, address to, bytes payload, bytes reason);
                                  event RevertRedeemLocal(uint16 srcChainId, uint256 _srcPoolId, uint256 _dstPoolId, bytes to, uint256 redeemAmountSD, uint256 mintAmountSD, uint256 indexed nonce, bytes indexed srcAddress);
                                  event RedeemLocalCallback(uint16 srcChainId, bytes indexed srcAddress, uint256 indexed nonce, uint256 srcPoolId, uint256 dstPoolId, address to, uint256 amountSD, uint256 mintAmountSD);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyBridge() {
                                      require(msg.sender == address(bridge), "Bridge: caller must be Bridge.");
                                      _;
                                  }
                                  constructor() {}
                                  function setBridgeAndFactory(Bridge _bridge, Factory _factory) external onlyOwner {
                                      require(address(bridge) == address(0x0) && address(factory) == address(0x0), "Stargate: bridge and factory already initialized"); // 1 time only
                                      require(address(_bridge) != address(0x0), "Stargate: bridge cant be 0x0");
                                      require(address(_factory) != address(0x0), "Stargate: factory cant be 0x0");
                                      bridge = _bridge;
                                      factory = _factory;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VIEWS
                                  function _getPool(uint256 _poolId) internal view returns (Pool pool) {
                                      pool = factory.getPool(_poolId);
                                      require(address(pool) != address(0x0), "Stargate: Pool does not exist");
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  function _safeTransferFrom(
                                      address token,
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      // 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))), "Stargate: TRANSFER_FROM_FAILED");
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external override nonReentrant {
                                      Pool pool = _getPool(_poolId);
                                      uint256 convertRate = pool.convertRate();
                                      _amountLD = _amountLD.div(convertRate).mul(convertRate);
                                      _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);
                                      pool.mint(_to, _amountLD);
                                  }
                                  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 override nonReentrant {
                                      require(_amountLD > 0, "Stargate: cannot swap 0");
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool.SwapObj memory s;
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(_srcPoolId);
                                          {
                                              uint256 convertRate = pool.convertRate();
                                              _amountLD = _amountLD.div(convertRate).mul(convertRate);
                                          }
                                          s = pool.swap(_dstChainId, _dstPoolId, msg.sender, _amountLD, _minAmountLD, true);
                                          _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);
                                          c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      }
                                      bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, _payload);
                                  }
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      require(_amountLP > 0, "Stargate: not enough lp to redeemRemote");
                                      Pool.SwapObj memory s;
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(_srcPoolId);
                                          uint256 amountLD = pool.amountLPtoLD(_amountLP);
                                          // perform a swap with no liquidity
                                          s = pool.swap(_dstChainId, _dstPoolId, msg.sender, amountLD, _minAmountLD, false);
                                          pool.redeemRemote(_dstChainId, _dstPoolId, msg.sender, _amountLP);
                                          c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      }
                                      // equal to a swap, with no payload ("0x") no dstGasForCall 0
                                      bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, "");
                                  }
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external override nonReentrant returns (uint256 amountSD) {
                                      require(_amountLP > 0, "Stargate: not enough lp to redeem");
                                      Pool pool = _getPool(_srcPoolId);
                                      amountSD = pool.instantRedeemLocal(msg.sender, _amountLP, _to);
                                  }
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool pool = _getPool(_srcPoolId);
                                      require(_amountLP > 0, "Stargate: not enough lp to redeem");
                                      uint256 amountSD = pool.redeemLocal(msg.sender, _amountLP, _dstChainId, _dstPoolId, _to);
                                      require(amountSD > 0, "Stargate: not enough lp to redeem with amountSD");
                                      Pool.CreditObj memory c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      bridge.redeemLocal{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, amountSD, _to, _lzTxParams);
                                  }
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool pool = _getPool(_srcPoolId);
                                      Pool.CreditObj memory c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      bridge.sendCredits{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c);
                                  }
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      Router.lzTxObj memory _lzTxParams
                                  ) external view override returns (uint256, uint256) {
                                      return bridge.quoteLayerZeroFee(_dstChainId, _functionType, _toAddress, _transferAndCallPayload, _lzTxParams);
                                  }
                                  function revertRedeemLocal(
                                      uint16 _dstChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce,
                                      address payable _refundAddress,
                                      lzTxObj memory _lzTxParams
                                  ) external payable {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      bytes memory payload = revertLookup[_dstChainId][_srcAddress][_nonce];
                                      require(payload.length > 0, "Stargate: no retry revert");
                                      {
                                          uint8 functionType;
                                          assembly {
                                              functionType := mload(add(payload, 32))
                                          }
                                          require(functionType == TYPE_REDEEM_LOCAL_RESPONSE, "Stargate: invalid function type");
                                      }
                                      // empty it
                                      revertLookup[_dstChainId][_srcAddress][_nonce] = "";
                                      uint256 srcPoolId;
                                      uint256 dstPoolId;
                                      assembly {
                                          srcPoolId := mload(add(payload, 64))
                                          dstPoolId := mload(add(payload, 96))
                                      }
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(dstPoolId);
                                          c = pool.sendCredits(_dstChainId, srcPoolId);
                                      }
                                      bridge.redeemLocalCallback{value: msg.value}(_dstChainId, _refundAddress, c, _lzTxParams, payload);
                                  }
                                  function retryRevert(
                                      uint16 _srcChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce
                                  ) external payable {
                                      bytes memory payload = revertLookup[_srcChainId][_srcAddress][_nonce];
                                      require(payload.length > 0, "Stargate: no retry revert");
                                      // empty it
                                      revertLookup[_srcChainId][_srcAddress][_nonce] = "";
                                      uint8 functionType;
                                      assembly {
                                          functionType := mload(add(payload, 32))
                                      }
                                      if (functionType == TYPE_REDEEM_LOCAL_CALLBACK_RETRY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, address to, uint256 amountSD, uint256 mintAmountSD) = abi.decode(
                                              payload,
                                              (uint8, uint256, uint256, address, uint256, uint256)
                                          );
                                          _redeemLocalCallback(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, to, amountSD, mintAmountSD);
                                      }
                                      // for retrying the swapRemote. if it fails again, retry
                                      else if (functionType == TYPE_SWAP_REMOTE_RETRY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, uint256 dstGasForCall, address to, Pool.SwapObj memory s, bytes memory p) = abi.decode(
                                              payload,
                                              (uint8, uint256, uint256, uint256, address, Pool.SwapObj, bytes)
                                          );
                                          _swapRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, dstGasForCall, to, s, p);
                                      } else {
                                          revert("Stargate: invalid function type");
                                      }
                                  }
                                  function clearCachedSwap(
                                      uint16 _srcChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce
                                  ) external {
                                      CachedSwap memory cs = cachedSwapLookup[_srcChainId][_srcAddress][_nonce];
                                      require(cs.to != address(0x0), "Stargate: cache already cleared");
                                      // clear the data
                                      cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(address(0x0), 0, address(0x0), "");
                                      IStargateReceiver(cs.to).sgReceive(_srcChainId, _srcAddress, _nonce, cs.token, cs.amountLD, cs.payload);
                                  }
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _srcPoolId,
                                      Pool.CreditObj memory _c
                                  ) external onlyBridge {
                                      Pool pool = _getPool(_srcPoolId);
                                      pool.creditChainPath(_dstChainId, _dstPoolId, _c);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _amountSD,
                                      bytes calldata _to
                                  ) external onlyBridge {
                                      Pool pool = _getPool(_dstPoolId);
                                      try pool.redeemLocalCheckOnRemote(_srcChainId, _srcPoolId, _amountSD) returns (uint256 redeemAmountSD, uint256 mintAmountSD) {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_REDEEM_LOCAL_RESPONSE,
                                              _srcPoolId,
                                              _dstPoolId,
                                              redeemAmountSD,
                                              mintAmountSD,
                                              _to
                                          );
                                          emit RevertRedeemLocal(_srcChainId, _srcPoolId, _dstPoolId, _to, redeemAmountSD, mintAmountSD, _nonce, _srcAddress);
                                      } catch {
                                          // if the func fail, return [swapAmount: 0, mintAMount: _amountSD]
                                          // swapAmount represents the amount of chainPath balance deducted on the remote side, which because the above tx failed, should be 0
                                          // mintAmount is the full amount of tokens the user attempted to redeem on the src side, which gets converted back into the lp amount
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(TYPE_REDEEM_LOCAL_RESPONSE, _srcPoolId, _dstPoolId, 0, _amountSD, _to);
                                          emit Revert(TYPE_REDEEM_LOCAL_RESPONSE, _srcChainId, _srcAddress, _nonce);
                                      }
                                  }
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _mintAmountSD
                                  ) external onlyBridge {
                                      _redeemLocalCallback(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _to, _amountSD, _mintAmountSD);
                                  }
                                  function _redeemLocalCallback(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _mintAmountSD
                                  ) internal {
                                      Pool pool = _getPool(_dstPoolId);
                                      try pool.redeemLocalCallback(_srcChainId, _srcPoolId, _to, _amountSD, _mintAmountSD) {} catch {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_REDEEM_LOCAL_CALLBACK_RETRY,
                                              _srcPoolId,
                                              _dstPoolId,
                                              _to,
                                              _amountSD,
                                              _mintAmountSD
                                          );
                                          emit Revert(TYPE_REDEEM_LOCAL_CALLBACK_RETRY, _srcChainId, _srcAddress, _nonce);
                                      }
                                      emit RedeemLocalCallback(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _to, _amountSD, _mintAmountSD);
                                  }
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _dstGasForCall,
                                      address _to,
                                      Pool.SwapObj memory _s,
                                      bytes memory _payload
                                  ) external onlyBridge {
                                      _swapRemote(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _dstGasForCall, _to, _s, _payload);
                                  }
                                  function _swapRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _dstGasForCall,
                                      address _to,
                                      Pool.SwapObj memory _s,
                                      bytes memory _payload
                                  ) internal {
                                      Pool pool = _getPool(_dstPoolId);
                                      // first try catch the swap remote
                                      try pool.swapRemote(_srcChainId, _srcPoolId, _to, _s) returns (uint256 amountLD) {
                                          if (_payload.length > 0) {
                                              // then try catch the external contract call
                                              try IStargateReceiver(_to).sgReceive{gas: _dstGasForCall}(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _payload) {
                                                  // do nothing
                                              } catch (bytes memory reason) {
                                                  cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(pool.token(), amountLD, _to, _payload);
                                                  emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _to, _payload, reason);
                                              }
                                          }
                                      } catch {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_SWAP_REMOTE_RETRY,
                                              _srcPoolId,
                                              _dstPoolId,
                                              _dstGasForCall,
                                              _to,
                                              _s,
                                              _payload
                                          );
                                          emit Revert(TYPE_SWAP_REMOTE_RETRY, _srcChainId, _srcAddress, _nonce);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) external onlyOwner returns (address) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      return factory.createPool(_poolId, _token, _sharedDecimals, _localDecimals, _name, _symbol);
                                  }
                                  function createChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.createChainPath(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function activateChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.activateChainPath(_dstChainId, _dstPoolId);
                                  }
                                  function setWeightForChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setWeightForChainPath(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setProtocolFeeOwner(address _owner) external onlyOwner {
                                      require(_owner != address(0x0), "Stargate: _owner cannot be 0x0");
                                      protocolFeeOwner = _owner;
                                  }
                                  function setMintFeeOwner(address _owner) external onlyOwner {
                                      require(_owner != address(0x0), "Stargate: _owner cannot be 0x0");
                                      mintFeeOwner = _owner;
                                  }
                                  function setFees(uint256 _poolId, uint256 _mintFeeBP) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setFee(_mintFeeBP);
                                  }
                                  function setFeeLibrary(uint256 _poolId, address _feeLibraryAddr) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setFeeLibrary(_feeLibraryAddr);
                                  }
                                  function setSwapStop(uint256 _poolId, bool _swapStop) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setSwapStop(_swapStop);
                                  }
                                  function setDeltaParam(
                                      uint256 _poolId,
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setDeltaParam(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(uint256 _poolId, bool _fullMode) external {
                                      Pool pool = _getPool(_poolId);
                                      pool.callDelta(_fullMode);
                                  }
                                  function withdrawMintFee(uint256 _poolId, address _to) external {
                                      require(mintFeeOwner == msg.sender, "Stargate: only mintFeeOwner");
                                      Pool pool = _getPool(_poolId);
                                      pool.withdrawMintFeeBalance(_to);
                                  }
                                  function withdrawProtocolFee(uint256 _poolId, address _to) external {
                                      require(protocolFeeOwner == msg.sender, "Stargate: only protocolFeeOwner");
                                      Pool pool = _getPool(_poolId);
                                      pool.withdrawProtocolFeeBalance(_to);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroReceiver {
                                  // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                                  // @param _srcChainId - the source endpoint identifier
                                  // @param _srcAddress - the source sending contract address from the source chain
                                  // @param _nonce - the ordered message nonce
                                  // @param _payload - the signed payload is the UA bytes has encoded to be sent
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. ie: pay for a specified destination gasAmount, or receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      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.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract LPTokenERC20 {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  string public name;
                                  string public symbol;
                                  bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  // set in constructor
                                  bytes32 public DOMAIN_SEPARATOR;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  uint256 public decimals;
                                  uint256 public totalSupply;
                                  mapping(address => uint256) public balanceOf;
                                  mapping(address => mapping(address => uint256)) public allowance;
                                  mapping(address => uint256) public nonces;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  constructor(string memory _name, string memory _symbol) {
                                      name = _name;
                                      symbol = _symbol;
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      DOMAIN_SEPARATOR = keccak256(
                                          abi.encode(
                                              keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                              keccak256(bytes(name)),
                                              keccak256(bytes("1")),
                                              chainId,
                                              address(this)
                                          )
                                      );
                                  }
                                  function _mint(address to, uint256 value) internal {
                                      totalSupply = totalSupply.add(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(address(0), to, value);
                                  }
                                  function _burn(address from, uint256 value) internal {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      totalSupply = totalSupply.sub(value);
                                      emit Transfer(from, address(0), value);
                                  }
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) private {
                                      allowance[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                                  function approve(address spender, uint256 value) external returns (bool) {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  function transfer(address to, uint256 value) external returns (bool) {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) external returns (bool) {
                                      if (allowance[from][msg.sender] != uint256(-1)) {
                                          allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                      }
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
                                      return true;
                                  }
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "Bridge: EXPIRED");
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\\x19\\x01",
                                              DOMAIN_SEPARATOR,
                                              keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                          )
                                      );
                                      address recoveredAddress = ecrecover(digest, v, r, s);
                                      require(recoveredAddress != address(0) && recoveredAddress == owner, "Bridge: INVALID_SIGNATURE");
                                      _approve(owner, spender, value);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              import "../Pool.sol";
                              interface IStargateFeeLibrary {
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external returns (Pool.SwapObj memory s);
                                  function getVersion() external view returns (string memory);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              contract Factory is Ownable {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  mapping(uint256 => Pool) public getPool; // poolId -> PoolInfo
                                  address[] public allPools;
                                  address public immutable router;
                                  address public defaultFeeLibrary; // address for retrieving fee params for swaps
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _router) {
                                      require(_router != address(0x0), "Stargate: _router cant be 0x0"); // 1 time only
                                      router = _router;
                                  }
                                  function setDefaultFeeLibrary(address _defaultFeeLibrary) external onlyOwner {
                                      require(_defaultFeeLibrary != address(0x0), "Stargate: fee library cant be 0x0");
                                      defaultFeeLibrary = _defaultFeeLibrary;
                                  }
                                  function allPoolsLength() external view returns (uint256) {
                                      return allPools.length;
                                  }
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) public onlyRouter returns (address poolAddress) {
                                      require(address(getPool[_poolId]) == address(0x0), "Stargate: Pool already created");
                                      Pool pool = new Pool(_poolId, router, _token, _sharedDecimals, _localDecimals, defaultFeeLibrary, _name, _symbol);
                                      getPool[_poolId] = pool;
                                      poolAddress = address(pool);
                                      allPools.push(poolAddress);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              interface IStargateRouter {
                                  struct lzTxObj {
                                      uint256 dstGasForCall;
                                      uint256 dstNativeAmount;
                                      bytes dstNativeAddr;
                                  }
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external;
                                  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;
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external returns (uint256);
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable;
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              interface IStargateReceiver {
                                  function sgReceive(
                                      uint16 _chainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      address _token,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external;
                              }
                              

                              File 8 of 16: FiatTokenV2_1
                              // File: @openzeppelin/contracts/math/SafeMath.sol
                              
                              // SPDX-License-Identifier: MIT
                              
                              pragma solidity ^0.6.0;
                              
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                              
                                      return c;
                                  }
                              
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return sub(a, b, "SafeMath: subtraction overflow");
                                  }
                              
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(
                                      uint256 a,
                                      uint256 b,
                                      string memory errorMessage
                                  ) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      uint256 c = a - b;
                              
                                      return c;
                                  }
                              
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) {
                                          return 0;
                                      }
                              
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                              
                                      return c;
                                  }
                              
                                  /**
                                   * @dev Returns the integer division of two unsigned integers. Reverts on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return div(a, b, "SafeMath: division by zero");
                                  }
                              
                                  /**
                                   * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(
                                      uint256 a,
                                      uint256 b,
                                      string memory errorMessage
                                  ) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      uint256 c = a / b;
                                      // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                              
                                      return c;
                                  }
                              
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * Reverts when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return mod(a, b, "SafeMath: modulo by zero");
                                  }
                              
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * Reverts with custom message when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(
                                      uint256 a,
                                      uint256 b,
                                      string memory errorMessage
                                  ) internal pure returns (uint256) {
                                      require(b != 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              
                              // File: @openzeppelin/contracts/token/ERC20/IERC20.sol
                              
                              pragma solidity ^0.6.0;
                              
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                              
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                              
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address recipient, uint256 amount)
                                      external
                                      returns (bool);
                              
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender)
                                      external
                                      view
                                      returns (uint256);
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Moves `amount` tokens from `sender` to `recipient` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(
                                      address sender,
                                      address recipient,
                                      uint256 amount
                                  ) external returns (bool);
                              
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                              
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(
                                      address indexed owner,
                                      address indexed spender,
                                      uint256 value
                                  );
                              }
                              
                              // File: contracts/v1/AbstractFiatTokenV1.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              abstract contract AbstractFiatTokenV1 is IERC20 {
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) internal virtual;
                              
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) internal virtual;
                              }
                              
                              // File: contracts/v1/Ownable.sol
                              
                              /**
                               * Copyright (c) 2018 zOS Global Limited.
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              pragma solidity 0.6.12;
                              
                              /**
                               * @notice The Ownable contract has an owner address, and provides basic
                               * authorization control functions
                               * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
                               * Modifications:
                               * 1. Consolidate OwnableStorage into this contract (7/13/18)
                               * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
                               * 3. Make public functions external (5/27/20)
                               */
                              contract Ownable {
                                  // Owner of the contract
                                  address private _owner;
                              
                                  /**
                                   * @dev Event to show ownership has been transferred
                                   * @param previousOwner representing the address of the previous owner
                                   * @param newOwner representing the address of the new owner
                                   */
                                  event OwnershipTransferred(address previousOwner, address newOwner);
                              
                                  /**
                                   * @dev The constructor sets the original owner of the contract to the sender account.
                                   */
                                  constructor() public {
                                      setOwner(msg.sender);
                                  }
                              
                                  /**
                                   * @dev Tells the address of the owner
                                   * @return the address of the owner
                                   */
                                  function owner() external view returns (address) {
                                      return _owner;
                                  }
                              
                                  /**
                                   * @dev Sets a new owner address
                                   */
                                  function setOwner(address newOwner) internal {
                                      _owner = newOwner;
                                  }
                              
                                  /**
                                   * @dev Throws if called by any account other than the owner.
                                   */
                                  modifier onlyOwner() {
                                      require(msg.sender == _owner, "Ownable: caller is not the owner");
                                      _;
                                  }
                              
                                  /**
                                   * @dev Allows the current owner to transfer control of the contract to a newOwner.
                                   * @param newOwner The address to transfer ownership to.
                                   */
                                  function transferOwnership(address newOwner) external onlyOwner {
                                      require(
                                          newOwner != address(0),
                                          "Ownable: new owner is the zero address"
                                      );
                                      emit OwnershipTransferred(_owner, newOwner);
                                      setOwner(newOwner);
                                  }
                              }
                              
                              // File: contracts/v1/Pausable.sol
                              
                              /**
                               * Copyright (c) 2016 Smart Contract Solutions, Inc.
                               * Copyright (c) 2018-2020 CENTRE SECZ0
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @notice Base contract which allows children to implement an emergency stop
                               * mechanism
                               * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
                               * Modifications:
                               * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
                               * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
                               * 3. Removed whenPaused (6/14/2018)
                               * 4. Switches ownable library to use ZeppelinOS (7/12/18)
                               * 5. Remove constructor (7/13/18)
                               * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
                               * 7. Make public functions external (5/27/20)
                               */
                              contract Pausable is Ownable {
                                  event Pause();
                                  event Unpause();
                                  event PauserChanged(address indexed newAddress);
                              
                                  address public pauser;
                                  bool public paused = false;
                              
                                  /**
                                   * @dev Modifier to make a function callable only when the contract is not paused.
                                   */
                                  modifier whenNotPaused() {
                                      require(!paused, "Pausable: paused");
                                      _;
                                  }
                              
                                  /**
                                   * @dev throws if called by any account other than the pauser
                                   */
                                  modifier onlyPauser() {
                                      require(msg.sender == pauser, "Pausable: caller is not the pauser");
                                      _;
                                  }
                              
                                  /**
                                   * @dev called by the owner to pause, triggers stopped state
                                   */
                                  function pause() external onlyPauser {
                                      paused = true;
                                      emit Pause();
                                  }
                              
                                  /**
                                   * @dev called by the owner to unpause, returns to normal state
                                   */
                                  function unpause() external onlyPauser {
                                      paused = false;
                                      emit Unpause();
                                  }
                              
                                  /**
                                   * @dev update the pauser role
                                   */
                                  function updatePauser(address _newPauser) external onlyOwner {
                                      require(
                                          _newPauser != address(0),
                                          "Pausable: new pauser is the zero address"
                                      );
                                      pauser = _newPauser;
                                      emit PauserChanged(pauser);
                                  }
                              }
                              
                              // File: contracts/v1/Blacklistable.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title Blacklistable Token
                               * @dev Allows accounts to be blacklisted by a "blacklister" role
                               */
                              contract Blacklistable is Ownable {
                                  address public blacklister;
                                  mapping(address => bool) internal blacklisted;
                              
                                  event Blacklisted(address indexed _account);
                                  event UnBlacklisted(address indexed _account);
                                  event BlacklisterChanged(address indexed newBlacklister);
                              
                                  /**
                                   * @dev Throws if called by any account other than the blacklister
                                   */
                                  modifier onlyBlacklister() {
                                      require(
                                          msg.sender == blacklister,
                                          "Blacklistable: caller is not the blacklister"
                                      );
                                      _;
                                  }
                              
                                  /**
                                   * @dev Throws if argument account is blacklisted
                                   * @param _account The address to check
                                   */
                                  modifier notBlacklisted(address _account) {
                                      require(
                                          !blacklisted[_account],
                                          "Blacklistable: account is blacklisted"
                                      );
                                      _;
                                  }
                              
                                  /**
                                   * @dev Checks if account is blacklisted
                                   * @param _account The address to check
                                   */
                                  function isBlacklisted(address _account) external view returns (bool) {
                                      return blacklisted[_account];
                                  }
                              
                                  /**
                                   * @dev Adds account to blacklist
                                   * @param _account The address to blacklist
                                   */
                                  function blacklist(address _account) external onlyBlacklister {
                                      blacklisted[_account] = true;
                                      emit Blacklisted(_account);
                                  }
                              
                                  /**
                                   * @dev Removes account from blacklist
                                   * @param _account The address to remove from the blacklist
                                   */
                                  function unBlacklist(address _account) external onlyBlacklister {
                                      blacklisted[_account] = false;
                                      emit UnBlacklisted(_account);
                                  }
                              
                                  function updateBlacklister(address _newBlacklister) external onlyOwner {
                                      require(
                                          _newBlacklister != address(0),
                                          "Blacklistable: new blacklister is the zero address"
                                      );
                                      blacklister = _newBlacklister;
                                      emit BlacklisterChanged(blacklister);
                                  }
                              }
                              
                              // File: contracts/v1/FiatTokenV1.sol
                              
                              /**
                               *
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title FiatToken
                               * @dev ERC20 Token backed by fiat reserves
                               */
                              contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
                                  using SafeMath for uint256;
                              
                                  string public name;
                                  string public symbol;
                                  uint8 public decimals;
                                  string public currency;
                                  address public masterMinter;
                                  bool internal initialized;
                              
                                  mapping(address => uint256) internal balances;
                                  mapping(address => mapping(address => uint256)) internal allowed;
                                  uint256 internal totalSupply_ = 0;
                                  mapping(address => bool) internal minters;
                                  mapping(address => uint256) internal minterAllowed;
                              
                                  event Mint(address indexed minter, address indexed to, uint256 amount);
                                  event Burn(address indexed burner, uint256 amount);
                                  event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
                                  event MinterRemoved(address indexed oldMinter);
                                  event MasterMinterChanged(address indexed newMasterMinter);
                              
                                  function initialize(
                                      string memory tokenName,
                                      string memory tokenSymbol,
                                      string memory tokenCurrency,
                                      uint8 tokenDecimals,
                                      address newMasterMinter,
                                      address newPauser,
                                      address newBlacklister,
                                      address newOwner
                                  ) public {
                                      require(!initialized, "FiatToken: contract is already initialized");
                                      require(
                                          newMasterMinter != address(0),
                                          "FiatToken: new masterMinter is the zero address"
                                      );
                                      require(
                                          newPauser != address(0),
                                          "FiatToken: new pauser is the zero address"
                                      );
                                      require(
                                          newBlacklister != address(0),
                                          "FiatToken: new blacklister is the zero address"
                                      );
                                      require(
                                          newOwner != address(0),
                                          "FiatToken: new owner is the zero address"
                                      );
                              
                                      name = tokenName;
                                      symbol = tokenSymbol;
                                      currency = tokenCurrency;
                                      decimals = tokenDecimals;
                                      masterMinter = newMasterMinter;
                                      pauser = newPauser;
                                      blacklister = newBlacklister;
                                      setOwner(newOwner);
                                      initialized = true;
                                  }
                              
                                  /**
                                   * @dev Throws if called by any account other than a minter
                                   */
                                  modifier onlyMinters() {
                                      require(minters[msg.sender], "FiatToken: caller is not a minter");
                                      _;
                                  }
                              
                                  /**
                                   * @dev Function to mint tokens
                                   * @param _to The address that will receive the minted tokens.
                                   * @param _amount The amount of tokens to mint. Must be less than or equal
                                   * to the minterAllowance of the caller.
                                   * @return A boolean that indicates if the operation was successful.
                                   */
                                  function mint(address _to, uint256 _amount)
                                      external
                                      whenNotPaused
                                      onlyMinters
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(_to)
                                      returns (bool)
                                  {
                                      require(_to != address(0), "FiatToken: mint to the zero address");
                                      require(_amount > 0, "FiatToken: mint amount not greater than 0");
                              
                                      uint256 mintingAllowedAmount = minterAllowed[msg.sender];
                                      require(
                                          _amount <= mintingAllowedAmount,
                                          "FiatToken: mint amount exceeds minterAllowance"
                                      );
                              
                                      totalSupply_ = totalSupply_.add(_amount);
                                      balances[_to] = balances[_to].add(_amount);
                                      minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
                                      emit Mint(msg.sender, _to, _amount);
                                      emit Transfer(address(0), _to, _amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Throws if called by any account other than the masterMinter
                                   */
                                  modifier onlyMasterMinter() {
                                      require(
                                          msg.sender == masterMinter,
                                          "FiatToken: caller is not the masterMinter"
                                      );
                                      _;
                                  }
                              
                                  /**
                                   * @dev Get minter allowance for an account
                                   * @param minter The address of the minter
                                   */
                                  function minterAllowance(address minter) external view returns (uint256) {
                                      return minterAllowed[minter];
                                  }
                              
                                  /**
                                   * @dev Checks if account is a minter
                                   * @param account The address to check
                                   */
                                  function isMinter(address account) external view returns (bool) {
                                      return minters[account];
                                  }
                              
                                  /**
                                   * @notice Amount of remaining tokens spender is allowed to transfer on
                                   * behalf of the token owner
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @return Allowance amount
                                   */
                                  function allowance(address owner, address spender)
                                      external
                                      override
                                      view
                                      returns (uint256)
                                  {
                                      return allowed[owner][spender];
                                  }
                              
                                  /**
                                   * @dev Get totalSupply of token
                                   */
                                  function totalSupply() external override view returns (uint256) {
                                      return totalSupply_;
                                  }
                              
                                  /**
                                   * @dev Get token balance of an account
                                   * @param account address The account
                                   */
                                  function balanceOf(address account)
                                      external
                                      override
                                      view
                                      returns (uint256)
                                  {
                                      return balances[account];
                                  }
                              
                                  /**
                                   * @notice Set spender's allowance over the caller's tokens to be a given
                                   * value.
                                   * @param spender   Spender's address
                                   * @param value     Allowance amount
                                   * @return True if successful
                                   */
                                  function approve(address spender, uint256 value)
                                      external
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Internal function to set allowance
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @param value     Allowance amount
                                   */
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) internal override {
                                      require(owner != address(0), "ERC20: approve from the zero address");
                                      require(spender != address(0), "ERC20: approve to the zero address");
                                      allowed[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                              
                                  /**
                                   * @notice Transfer tokens by spending allowance
                                   * @param from  Payer's address
                                   * @param to    Payee's address
                                   * @param value Transfer amount
                                   * @return True if successful
                                   */
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  )
                                      external
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(from)
                                      notBlacklisted(to)
                                      returns (bool)
                                  {
                                      require(
                                          value <= allowed[from][msg.sender],
                                          "ERC20: transfer amount exceeds allowance"
                                      );
                                      _transfer(from, to, value);
                                      allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice Transfer tokens from the caller
                                   * @param to    Payee's address
                                   * @param value Transfer amount
                                   * @return True if successful
                                   */
                                  function transfer(address to, uint256 value)
                                      external
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(to)
                                      returns (bool)
                                  {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice Internal function to process transfers
                                   * @param from  Payer's address
                                   * @param to    Payee's address
                                   * @param value Transfer amount
                                   */
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) internal override {
                                      require(from != address(0), "ERC20: transfer from the zero address");
                                      require(to != address(0), "ERC20: transfer to the zero address");
                                      require(
                                          value <= balances[from],
                                          "ERC20: transfer amount exceeds balance"
                                      );
                              
                                      balances[from] = balances[from].sub(value);
                                      balances[to] = balances[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                              
                                  /**
                                   * @dev Function to add/update a new minter
                                   * @param minter The address of the minter
                                   * @param minterAllowedAmount The minting amount allowed for the minter
                                   * @return True if the operation was successful.
                                   */
                                  function configureMinter(address minter, uint256 minterAllowedAmount)
                                      external
                                      whenNotPaused
                                      onlyMasterMinter
                                      returns (bool)
                                  {
                                      minters[minter] = true;
                                      minterAllowed[minter] = minterAllowedAmount;
                                      emit MinterConfigured(minter, minterAllowedAmount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Function to remove a minter
                                   * @param minter The address of the minter to remove
                                   * @return True if the operation was successful.
                                   */
                                  function removeMinter(address minter)
                                      external
                                      onlyMasterMinter
                                      returns (bool)
                                  {
                                      minters[minter] = false;
                                      minterAllowed[minter] = 0;
                                      emit MinterRemoved(minter);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev allows a minter to burn some of its own tokens
                                   * Validates that caller is a minter and that sender is not blacklisted
                                   * amount is less than or equal to the minter's account balance
                                   * @param _amount uint256 the amount of tokens to be burned
                                   */
                                  function burn(uint256 _amount)
                                      external
                                      whenNotPaused
                                      onlyMinters
                                      notBlacklisted(msg.sender)
                                  {
                                      uint256 balance = balances[msg.sender];
                                      require(_amount > 0, "FiatToken: burn amount not greater than 0");
                                      require(balance >= _amount, "FiatToken: burn amount exceeds balance");
                              
                                      totalSupply_ = totalSupply_.sub(_amount);
                                      balances[msg.sender] = balance.sub(_amount);
                                      emit Burn(msg.sender, _amount);
                                      emit Transfer(msg.sender, address(0), _amount);
                                  }
                              
                                  function updateMasterMinter(address _newMasterMinter) external onlyOwner {
                                      require(
                                          _newMasterMinter != address(0),
                                          "FiatToken: new masterMinter is the zero address"
                                      );
                                      masterMinter = _newMasterMinter;
                                      emit MasterMinterChanged(masterMinter);
                                  }
                              }
                              
                              // File: @openzeppelin/contracts/utils/Address.sol
                              
                              pragma solidity ^0.6.2;
                              
                              /**
                               * @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) {
                                      // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                                      // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                                      // for accounts without code, i.e. `keccak256('')`
                                      bytes32 codehash;
                              
                                          bytes32 accountHash
                                       = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly {
                                          codehash := extcodehash(account)
                                      }
                                      return (codehash != accountHash && codehash != 0x0);
                                  }
                              
                                  /**
                                   * @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"
                                      );
                                      return _functionCallWithValue(target, data, value, errorMessage);
                                  }
                              
                                  function _functionCallWithValue(
                                      address target,
                                      bytes memory data,
                                      uint256 weiValue,
                                      string memory errorMessage
                                  ) private returns (bytes memory) {
                                      require(isContract(target), "Address: call to non-contract");
                              
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.call{
                                          value: weiValue
                                      }(data);
                                      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);
                                          }
                                      }
                                  }
                              }
                              
                              // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
                              
                              pragma solidity ^0.6.0;
                              
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using SafeMath for uint256;
                                  using Address for address;
                              
                                  function safeTransfer(
                                      IERC20 token,
                                      address to,
                                      uint256 value
                                  ) internal {
                                      _callOptionalReturn(
                                          token,
                                          abi.encodeWithSelector(token.transfer.selector, to, value)
                                      );
                                  }
                              
                                  function safeTransferFrom(
                                      IERC20 token,
                                      address from,
                                      address to,
                                      uint256 value
                                  ) internal {
                                      _callOptionalReturn(
                                          token,
                                          abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
                                      );
                                  }
                              
                                  /**
                                   * @dev Deprecated. This function has issues similar to the ones found in
                                   * {IERC20-approve}, and its usage is discouraged.
                                   *
                                   * Whenever possible, use {safeIncreaseAllowance} and
                                   * {safeDecreaseAllowance} instead.
                                   */
                                  function safeApprove(
                                      IERC20 token,
                                      address spender,
                                      uint256 value
                                  ) internal {
                                      // safeApprove should only be called when setting an initial allowance,
                                      // or when resetting it to zero. To increase and decrease it, use
                                      // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                      // solhint-disable-next-line max-line-length
                                      require(
                                          (value == 0) || (token.allowance(address(this), spender) == 0),
                                          "SafeERC20: approve from non-zero to non-zero allowance"
                                      );
                                      _callOptionalReturn(
                                          token,
                                          abi.encodeWithSelector(token.approve.selector, spender, value)
                                      );
                                  }
                              
                                  function safeIncreaseAllowance(
                                      IERC20 token,
                                      address spender,
                                      uint256 value
                                  ) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).add(
                                          value
                                      );
                                      _callOptionalReturn(
                                          token,
                                          abi.encodeWithSelector(
                                              token.approve.selector,
                                              spender,
                                              newAllowance
                                          )
                                      );
                                  }
                              
                                  function safeDecreaseAllowance(
                                      IERC20 token,
                                      address spender,
                                      uint256 value
                                  ) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).sub(
                                          value,
                                          "SafeERC20: decreased allowance below zero"
                                      );
                                      _callOptionalReturn(
                                          token,
                                          abi.encodeWithSelector(
                                              token.approve.selector,
                                              spender,
                                              newAllowance
                                          )
                                      );
                                  }
                              
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                              
                                      bytes memory returndata = address(token).functionCall(
                                          data,
                                          "SafeERC20: low-level call failed"
                                      );
                                      if (returndata.length > 0) {
                                          // Return data is optional
                                          // solhint-disable-next-line max-line-length
                                          require(
                                              abi.decode(returndata, (bool)),
                                              "SafeERC20: ERC20 operation did not succeed"
                                          );
                                      }
                                  }
                              }
                              
                              // File: contracts/v1.1/Rescuable.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              contract Rescuable is Ownable {
                                  using SafeERC20 for IERC20;
                              
                                  address private _rescuer;
                              
                                  event RescuerChanged(address indexed newRescuer);
                              
                                  /**
                                   * @notice Returns current rescuer
                                   * @return Rescuer's address
                                   */
                                  function rescuer() external view returns (address) {
                                      return _rescuer;
                                  }
                              
                                  /**
                                   * @notice Revert if called by any account other than the rescuer.
                                   */
                                  modifier onlyRescuer() {
                                      require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
                                      _;
                                  }
                              
                                  /**
                                   * @notice Rescue ERC20 tokens locked up in this contract.
                                   * @param tokenContract ERC20 token contract address
                                   * @param to        Recipient address
                                   * @param amount    Amount to withdraw
                                   */
                                  function rescueERC20(
                                      IERC20 tokenContract,
                                      address to,
                                      uint256 amount
                                  ) external onlyRescuer {
                                      tokenContract.safeTransfer(to, amount);
                                  }
                              
                                  /**
                                   * @notice Assign the rescuer role to a given address.
                                   * @param newRescuer New rescuer's address
                                   */
                                  function updateRescuer(address newRescuer) external onlyOwner {
                                      require(
                                          newRescuer != address(0),
                                          "Rescuable: new rescuer is the zero address"
                                      );
                                      _rescuer = newRescuer;
                                      emit RescuerChanged(newRescuer);
                                  }
                              }
                              
                              // File: contracts/v1.1/FiatTokenV1_1.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title FiatTokenV1_1
                               * @dev ERC20 Token backed by fiat reserves
                               */
                              contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
                              
                              }
                              
                              // File: contracts/v2/AbstractFiatTokenV2.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
                                  function _increaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 increment
                                  ) internal virtual;
                              
                                  function _decreaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 decrement
                                  ) internal virtual;
                              }
                              
                              // File: contracts/util/ECRecover.sol
                              
                              /**
                               * Copyright (c) 2016-2019 zOS Global Limited
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title ECRecover
                               * @notice A library that provides a safe ECDSA recovery function
                               */
                              library ECRecover {
                                  /**
                                   * @notice Recover signer's address from a signed message
                                   * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
                                   * Modifications: Accept v, r, and s as separate arguments
                                   * @param digest    Keccak-256 hash digest of the signed message
                                   * @param v         v of the signature
                                   * @param r         r of the signature
                                   * @param s         s of the signature
                                   * @return Signer address
                                   */
                                  function recover(
                                      bytes32 digest,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal pure returns (address) {
                                      // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                                      // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                                      // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                                      // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                                      //
                                      // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                                      // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                                      // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                                      // these malleable signatures as well.
                                      if (
                                          uint256(s) >
                                          0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                                      ) {
                                          revert("ECRecover: invalid signature 's' value");
                                      }
                              
                                      if (v != 27 && v != 28) {
                                          revert("ECRecover: invalid signature 'v' value");
                                      }
                              
                                      // If the signature is valid (and not malleable), return the signer address
                                      address signer = ecrecover(digest, v, r, s);
                                      require(signer != address(0), "ECRecover: invalid signature");
                              
                                      return signer;
                                  }
                              }
                              
                              // File: contracts/util/EIP712.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title EIP712
                               * @notice A library that provides EIP712 helper functions
                               */
                              library EIP712 {
                                  /**
                                   * @notice Make EIP712 domain separator
                                   * @param name      Contract name
                                   * @param version   Contract version
                                   * @return Domain separator
                                   */
                                  function makeDomainSeparator(string memory name, string memory version)
                                      internal
                                      view
                                      returns (bytes32)
                                  {
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      return
                                          keccak256(
                                              abi.encode(
                                                  // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
                                                  0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                                  keccak256(bytes(name)),
                                                  keccak256(bytes(version)),
                                                  chainId,
                                                  address(this)
                                              )
                                          );
                                  }
                              
                                  /**
                                   * @notice Recover signer's address from a EIP712 signature
                                   * @param domainSeparator   Domain separator
                                   * @param v                 v of the signature
                                   * @param r                 r of the signature
                                   * @param s                 s of the signature
                                   * @param typeHashAndData   Type hash concatenated with data
                                   * @return Signer's address
                                   */
                                  function recover(
                                      bytes32 domainSeparator,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s,
                                      bytes memory typeHashAndData
                                  ) internal pure returns (address) {
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\x19\x01",
                                              domainSeparator,
                                              keccak256(typeHashAndData)
                                          )
                                      );
                                      return ECRecover.recover(digest, v, r, s);
                                  }
                              }
                              
                              // File: contracts/v2/EIP712Domain.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title EIP712 Domain
                               */
                              contract EIP712Domain {
                                  /**
                                   * @dev EIP712 Domain Separator
                                   */
                                  bytes32 public DOMAIN_SEPARATOR;
                              }
                              
                              // File: contracts/v2/EIP3009.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title EIP-3009
                               * @notice Provide internal implementation for gas-abstracted transfers
                               * @dev Contracts that inherit from this must wrap these with publicly
                               * accessible functions, optionally adding modifiers where necessary
                               */
                              abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
                                  // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                  bytes32
                                      public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
                              
                                  // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                  bytes32
                                      public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
                              
                                  // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
                                  bytes32
                                      public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
                              
                                  /**
                                   * @dev authorizer address => nonce => bool (true if nonce is used)
                                   */
                                  mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
                              
                                  event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
                                  event AuthorizationCanceled(
                                      address indexed authorizer,
                                      bytes32 indexed nonce
                                  );
                              
                                  /**
                                   * @notice Returns the state of an authorization
                                   * @dev Nonces are randomly generated 32-byte data unique to the
                                   * authorizer's address
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @return True if the nonce is used
                                   */
                                  function authorizationState(address authorizer, bytes32 nonce)
                                      external
                                      view
                                      returns (bool)
                                  {
                                      return _authorizationStates[authorizer][nonce];
                                  }
                              
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _requireValidAuthorization(from, nonce, validAfter, validBefore);
                              
                                      bytes memory data = abi.encode(
                                          TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce
                                      );
                                      require(
                                          EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
                                          "FiatTokenV2: invalid signature"
                                      );
                              
                                      _markAuthorizationAsUsed(from, nonce);
                                      _transfer(from, to, value);
                                  }
                              
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      require(to == msg.sender, "FiatTokenV2: caller must be the payee");
                                      _requireValidAuthorization(from, nonce, validAfter, validBefore);
                              
                                      bytes memory data = abi.encode(
                                          RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce
                                      );
                                      require(
                                          EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
                                          "FiatTokenV2: invalid signature"
                                      );
                              
                                      _markAuthorizationAsUsed(from, nonce);
                                      _transfer(from, to, value);
                                  }
                              
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _requireUnusedAuthorization(authorizer, nonce);
                              
                                      bytes memory data = abi.encode(
                                          CANCEL_AUTHORIZATION_TYPEHASH,
                                          authorizer,
                                          nonce
                                      );
                                      require(
                                          EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer,
                                          "FiatTokenV2: invalid signature"
                                      );
                              
                                      _authorizationStates[authorizer][nonce] = true;
                                      emit AuthorizationCanceled(authorizer, nonce);
                                  }
                              
                                  /**
                                   * @notice Check that an authorization is unused
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   */
                                  function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
                                      private
                                      view
                                  {
                                      require(
                                          !_authorizationStates[authorizer][nonce],
                                          "FiatTokenV2: authorization is used or canceled"
                                      );
                                  }
                              
                                  /**
                                   * @notice Check that authorization is valid
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   */
                                  function _requireValidAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint256 validAfter,
                                      uint256 validBefore
                                  ) private view {
                                      require(
                                          now > validAfter,
                                          "FiatTokenV2: authorization is not yet valid"
                                      );
                                      require(now < validBefore, "FiatTokenV2: authorization is expired");
                                      _requireUnusedAuthorization(authorizer, nonce);
                                  }
                              
                                  /**
                                   * @notice Mark an authorization as used
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   */
                                  function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
                                      private
                                  {
                                      _authorizationStates[authorizer][nonce] = true;
                                      emit AuthorizationUsed(authorizer, nonce);
                                  }
                              }
                              
                              // File: contracts/v2/EIP2612.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title EIP-2612
                               * @notice Provide internal implementation for gas-abstracted approvals
                               */
                              abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
                                  // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                                  bytes32
                                      public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                              
                                  mapping(address => uint256) private _permitNonces;
                              
                                  /**
                                   * @notice Nonces for permit
                                   * @param owner Token owner's address (Authorizer)
                                   * @return Next nonce
                                   */
                                  function nonces(address owner) external view returns (uint256) {
                                      return _permitNonces[owner];
                                  }
                              
                                  /**
                                   * @notice Verify a signed approval permit and execute if valid
                                   * @param owner     Token owner's address (Authorizer)
                                   * @param spender   Spender's address
                                   * @param value     Amount of allowance
                                   * @param deadline  The time at which this expires (unix time)
                                   * @param v         v of the signature
                                   * @param r         r of the signature
                                   * @param s         s of the signature
                                   */
                                  function _permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      require(deadline >= now, "FiatTokenV2: permit is expired");
                              
                                      bytes memory data = abi.encode(
                                          PERMIT_TYPEHASH,
                                          owner,
                                          spender,
                                          value,
                                          _permitNonces[owner]++,
                                          deadline
                                      );
                                      require(
                                          EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
                                          "EIP2612: invalid signature"
                                      );
                              
                                      _approve(owner, spender, value);
                                  }
                              }
                              
                              // File: contracts/v2/FiatTokenV2.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              /**
                               * @title FiatToken V2
                               * @notice ERC20 Token backed by fiat reserves, version 2
                               */
                              contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
                                  uint8 internal _initializedVersion;
                              
                                  /**
                                   * @notice Initialize v2
                                   * @param newName   New token name
                                   */
                                  function initializeV2(string calldata newName) external {
                                      // solhint-disable-next-line reason-string
                                      require(initialized && _initializedVersion == 0);
                                      name = newName;
                                      DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2");
                                      _initializedVersion = 1;
                                  }
                              
                                  /**
                                   * @notice Increase the allowance by a given increment
                                   * @param spender   Spender's address
                                   * @param increment Amount of increase in allowance
                                   * @return True if successful
                                   */
                                  function increaseAllowance(address spender, uint256 increment)
                                      external
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _increaseAllowance(msg.sender, spender, increment);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice Decrease the allowance by a given decrement
                                   * @param spender   Spender's address
                                   * @param decrement Amount of decrease in allowance
                                   * @return True if successful
                                   */
                                  function decreaseAllowance(address spender, uint256 decrement)
                                      external
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _decreaseAllowance(msg.sender, spender, decrement);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _transferWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          v,
                                          r,
                                          s
                                      );
                                  }
                              
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _receiveWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          v,
                                          r,
                                          s
                                      );
                                  }
                              
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @dev Works only if the authorization is not yet used.
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused {
                                      _cancelAuthorization(authorizer, nonce, v, r, s);
                                  }
                              
                                  /**
                                   * @notice Update allowance with a signed permit
                                   * @param owner       Token owner's address (Authorizer)
                                   * @param spender     Spender's address
                                   * @param value       Amount of allowance
                                   * @param deadline    Expiration time, seconds since the epoch
                                   * @param v           v of the signature
                                   * @param r           r of the signature
                                   * @param s           s of the signature
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
                                      _permit(owner, spender, value, deadline, v, r, s);
                                  }
                              
                                  /**
                                   * @notice Internal function to increase the allowance by a given increment
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @param increment Amount of increase
                                   */
                                  function _increaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 increment
                                  ) internal override {
                                      _approve(owner, spender, allowed[owner][spender].add(increment));
                                  }
                              
                                  /**
                                   * @notice Internal function to decrease the allowance by a given decrement
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @param decrement Amount of decrease
                                   */
                                  function _decreaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 decrement
                                  ) internal override {
                                      _approve(
                                          owner,
                                          spender,
                                          allowed[owner][spender].sub(
                                              decrement,
                                              "ERC20: decreased allowance below zero"
                                          )
                                      );
                                  }
                              }
                              
                              // File: contracts/v2/FiatTokenV2_1.sol
                              
                              /**
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              
                              pragma solidity 0.6.12;
                              
                              // solhint-disable func-name-mixedcase
                              
                              /**
                               * @title FiatToken V2.1
                               * @notice ERC20 Token backed by fiat reserves, version 2.1
                               */
                              contract FiatTokenV2_1 is FiatTokenV2 {
                                  /**
                                   * @notice Initialize v2.1
                                   * @param lostAndFound  The address to which the locked funds are sent
                                   */
                                  function initializeV2_1(address lostAndFound) external {
                                      // solhint-disable-next-line reason-string
                                      require(_initializedVersion == 1);
                              
                                      uint256 lockedAmount = balances[address(this)];
                                      if (lockedAmount > 0) {
                                          _transfer(address(this), lostAndFound, lockedAmount);
                                      }
                                      blacklisted[address(this)] = true;
                              
                                      _initializedVersion = 2;
                                  }
                              
                                  /**
                                   * @notice Version string for the EIP712 domain separator
                                   * @return Version string
                                   */
                                  function version() external view returns (string memory) {
                                      return "2";
                                  }
                              }

                              File 9 of 16: StargateComposer
                              // SPDX-License-Identifier: UNLICENSED
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/Address.sol";
                              import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "./interfaces/IStargateRouter.sol";
                              import "./interfaces/IStargateReceiver.sol";
                              import "./interfaces/IStargateEthVault.sol";
                              import "./util/BytesLib.sol";
                              import "./util/SafeCall.sol";
                              interface IStargateBridge {
                                  function quoteLayerZeroFee(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256);
                              }
                              interface IPool {
                                  function token() external view returns (address);
                                  function convertRate() external view returns (uint256);
                              }
                              interface IStargateFactory {
                                  function getPool(uint256 _poolId) external view returns (address);
                              }
                              contract StargateComposer is IStargateRouter, IStargateReceiver, Ownable, ReentrancyGuard {
                                  using BytesLib for bytes;
                                  using SafeCall for address;
                                  using Address for address;
                                  using SafeERC20 for IERC20;
                                  using SafeMath for uint256;
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private dstGasReserve = 40000;
                                  uint256 private transferOverhead = 20000;
                                  uint256 private _swapStatus = _NOT_ENTERED;
                                  IStargateBridge public immutable stargateBridge;
                                  IStargateRouter public immutable stargateRouter;
                                  address public immutable factory;
                                  uint256 public wethPoolId;
                                  struct PoolInfo {
                                      address token;
                                      address poolAddress;
                                      uint256 convertRate;
                                  }
                                  mapping(uint16 => address) public peers;
                                  mapping(uint256 => address) public stargateEthVaults;
                                  mapping(uint16 => mapping(bytes => mapping(uint256 => bytes32))) public payloadHashes;
                                  mapping(uint256 => PoolInfo) public poolIdToInfo; // cache pool info
                                  modifier nonSwapReentrant() {
                                      require(_swapStatus != _ENTERED, "Stargate: reentrant call");
                                      _swapStatus = _ENTERED;
                                      _;
                                      _swapStatus = _NOT_ENTERED;
                                  }
                                  event CachedSwapSaved(
                                      uint16 chainId,
                                      bytes srcAddress,
                                      uint256 nonce,
                                      bytes reason
                                  );
                                  event ComposedTokenTransferFailed(
                                      address token,
                                      address intendedReceiver,
                                      uint amountLD
                                  );
                                  struct SwapAmount {
                                      uint256 amountLD; // the amount, in Local Decimals, to be swapped
                                      uint256 minAmountLD; // the minimum amount accepted out on destination
                                  }
                                  constructor(address _stargateBridge, address _stargateRouter, address _stargateEthVault, uint256 _wethPoolId) {
                                      stargateBridge = IStargateBridge(_stargateBridge);
                                      stargateRouter = IStargateRouter(_stargateRouter);
                                      wethPoolId = _wethPoolId;
                                      setStargateEthVaults(_wethPoolId, _stargateEthVault);
                                      (bool success, bytes memory data) = _stargateRouter.staticcall(abi.encodeWithSignature("factory()"));
                                      require(success, "Stargate: invalid factory address");
                                      factory = abi.decode(data, (address));
                                  }
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external override {
                                      PoolInfo memory poolInfo = _getPoolInfo(_poolId);
                                      // remove dust
                                      if (poolInfo.convertRate > 1) _amountLD = _amountLD.div(poolInfo.convertRate).mul(poolInfo.convertRate);
                                      // transfer tokens into this contract
                                      IERC20(poolInfo.token).safeTransferFrom(msg.sender, address(this), _amountLD);
                                      stargateRouter.addLiquidity(_poolId, _amountLD, _to);
                                  }
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external override payable nonReentrant {
                                      IERC20 lpToken = IERC20(_getPoolInfo(_srcPoolId).poolAddress);
                                      // transfer lp tokens into this contract
                                      lpToken.safeTransferFrom(msg.sender, address(this), _amountLP);
                                      stargateRouter.redeemRemote{value: msg.value}(
                                          _dstChainId,
                                          _srcPoolId,
                                          _dstPoolId,
                                          _refundAddress,
                                          _amountLP,
                                          _minAmountLD,
                                          _to,
                                          _lzTxParams
                                      );
                                  }
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external override payable nonReentrant {
                                      IERC20 lpToken = IERC20(_getPoolInfo(_srcPoolId).poolAddress);
                                      // transfer lp tokens into this contract
                                      lpToken.safeTransferFrom(msg.sender, address(this), _amountLP);
                                      stargateRouter.redeemLocal{value: msg.value}(
                                          _dstChainId,
                                          _srcPoolId,
                                          _dstPoolId,
                                          _refundAddress,
                                          _amountLP,
                                          _to,
                                          _lzTxParams
                                      );
                                  }
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external override nonReentrant returns (uint256 amountSD) {
                                      IERC20 lpToken = IERC20(_getPoolInfo(_srcPoolId).poolAddress);
                                      // should always be zero as this contract doesnt hold tokens
                                      uint balanceBefore = lpToken.balanceOf(address(this));
                                      // transfer lp tokens into this contract
                                      lpToken.safeTransferFrom(msg.sender, address(this), _amountLP);
                                      // redeem the tokens on behalf of user
                                      amountSD = stargateRouter.instantRedeemLocal(_srcPoolId, _amountLP, _to);
                                      // any extra lpTokens send back to the original msg.sender
                                      uint balanceAfter = lpToken.balanceOf(address(this));
                                      uint diff = balanceAfter - balanceBefore;
                                      if (diff > 0) lpToken.safeTransfer(msg.sender, diff);
                                  }
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable override nonReentrant {
                                      stargateRouter.sendCredits{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress);
                                  }
                                  function quoteLayerZeroFee(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external view override returns(uint256, uint256) {
                                      bytes memory newPayload;
                                      bytes memory peer;
                                      if(_transferAndCallPayload.length > 0) {
                                          newPayload = _buildPayload(_toAddress, _transferAndCallPayload);
                                          peer = _getPeer(_chainId);
                                          // overhead for calling composer's sgReceive()
                                          _lzTxParams.dstGasForCall += dstGasReserve + transferOverhead;
                                      } else {
                                          newPayload = "";
                                          peer = _toAddress;
                                      }
                                      return stargateBridge.quoteLayerZeroFee(_chainId, _functionType, peer, newPayload, _lzTxParams);
                                  }
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes calldata _to,
                                      bytes calldata _payload
                                  ) external override payable nonSwapReentrant {
                                      bytes memory newPayload;
                                      bytes memory peer;
                                      if(_payload.length > 0) {
                                          newPayload = _buildPayload(_to, _payload);
                                          peer = _getPeer(_dstChainId);
                                          // overhead for calling composer's sgReceive()
                                          _lzTxParams.dstGasForCall += dstGasReserve + transferOverhead;
                                      } else {
                                          newPayload = "";
                                          peer = _to;
                                      }
                                      if(isEthPool(_srcPoolId)) {
                                          require(msg.value > _amountLD, "Stargate: msg.value must be > _swapAmount.amountLD");
                                          IStargateEthVault(stargateEthVaults[_srcPoolId]).deposit{value: _amountLD}();
                                          IStargateEthVault(stargateEthVaults[_srcPoolId]).approve(address(stargateRouter), _amountLD);
                                      } else {
                                          PoolInfo memory poolInfo = _getPoolInfo(_srcPoolId);
                                          // remove dust
                                          if (poolInfo.convertRate > 1) _amountLD = _amountLD.div(poolInfo.convertRate).mul(poolInfo.convertRate);
                                          // transfer token to this contract
                                          IERC20(poolInfo.token).safeTransferFrom(msg.sender, address(this), _amountLD);
                                      }
                                      stargateRouter.swap{value: isEthPool(_srcPoolId) ? msg.value - _amountLD : msg.value}(
                                          _dstChainId,
                                          _srcPoolId,
                                          _dstPoolId,
                                          _refundAddress,
                                          _amountLD,
                                          _minAmountLD,
                                          _lzTxParams,
                                          peer, // swap the to address with the peer address
                                          newPayload
                                      );
                                  }
                                  // @notice compose stargate to swap ETH on the source to ETH on the destination and arbitrary call
                                  function swapETHAndCall(
                                      uint16 _dstChainId, // destination Stargate chainId
                                      address payable _refundAddress, // refund additional messageFee to this address
                                      bytes calldata _to, // the receiver of the destination ETH
                                      SwapAmount memory _swapAmount, // the amount and the minimum swap amount
                                      IStargateRouter.lzTxObj memory _lzTxParams, // the LZ tx params
                                      bytes calldata _payload // the payload to send to the destination
                                  ) external payable nonSwapReentrant {
                                      bytes memory newPayload;
                                      bytes memory peer;
                                      if(_payload.length > 0) {
                                          newPayload = _buildPayload(_to, _payload);
                                          peer = _getPeer(_dstChainId);
                                          // overhead for calling composer's sgReceive()
                                          _lzTxParams.dstGasForCall += dstGasReserve + transferOverhead;
                                      } else {
                                          newPayload = "";
                                          peer = _to;
                                      }
                                      {
                                          require(msg.value > _swapAmount.amountLD, "Stargate: msg.value must be > _swapAmount.amountLD");
                                          require(stargateEthVaults[wethPoolId] != address(0), "Stargate: Pool does not exist");
                                          IStargateEthVault(stargateEthVaults[wethPoolId]).deposit{value: _swapAmount.amountLD}();
                                          IStargateEthVault(stargateEthVaults[wethPoolId]).approve(address(stargateRouter), _swapAmount.amountLD);
                                      }
                                      stargateRouter.swap{value: (msg.value - _swapAmount.amountLD)}(
                                          _dstChainId, // destination Stargate chainId
                                          wethPoolId, // WETH Stargate poolId on source
                                          wethPoolId, // WETH Stargate poolId on destination
                                          _refundAddress, // message refund address if overpaid
                                          _swapAmount.amountLD, // the amount in Local Decimals to swap()
                                          _swapAmount.minAmountLD, // the minimum amount swap()er would allow to get out (ie: slippage)
                                          _lzTxParams, // the LZ tx params
                                          peer, // address on destination to send to
                                          newPayload // payload to send to the destination
                                      );
                                  }
                                  function _buildPayload(
                                      bytes calldata _to,
                                      bytes calldata _payload
                                  ) internal view returns (bytes memory) {
                                      require(_to.length == 20, "Stargate: invalid to address");
                                      // new payload = to(20) + sender(20) + payload
                                      // encoding the sender allows the receiver to know who called the Stargate
                                      return abi.encodePacked(_to, msg.sender, _payload);
                                  }
                                  function _getPeer(uint16 _dstChainId) internal view returns(bytes memory) {
                                      address peerAddr = peers[_dstChainId];
                                      require(peerAddr != address(0), "Stargate: peer not found");
                                      return abi.encodePacked(peerAddr);
                                  }
                                  function addLiquidityETH() external payable {
                                      require(msg.value > 0, "Stargate: msg.value is 0");
                                      // wrap the ETH into WETH
                                      uint256 amountLD = msg.value;
                                      require(stargateEthVaults[wethPoolId] != address(0), "Stargate: Pool does not exist");
                                      IStargateEthVault(stargateEthVaults[wethPoolId]).deposit{value: amountLD}();
                                      IStargateEthVault(stargateEthVaults[wethPoolId]).approve(address(stargateRouter), amountLD);
                                      // addLiquidity using the WETH that was just wrapped,
                                      // and mint the LP token to the msg.sender
                                      stargateRouter.addLiquidity(wethPoolId, amountLD, msg.sender);
                                  }
                                  function sgReceive(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      address _token,
                                      uint256 _amountLD,
                                      bytes memory _payload
                                  ) external override {
                                      require(msg.sender == address(stargateRouter), "Stargate: only router");
                                      // will just ignore the payload in some invalid configuration
                                      if (_payload.length <= 40) return; // 20 + 20 + payload
                                      address intendedReceiver = _payload.toAddress(0);
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, intendedReceiver, _amountLD));
                                      if (success && (data.length == 0 || abi.decode(data, (bool)))) {
                                          if (!intendedReceiver.isContract()) return; // ignore
                                          bytes memory callData = abi.encodeWithSelector(
                                              IStargateReceiver.sgReceive.selector,
                                              _srcChainId,
                                              abi.encodePacked(_payload.toAddress(20)), // use the caller as the srcAddress (the msg.sender caller the StargateComposer at the source)
                                              _nonce,
                                              _token,
                                              _amountLD,
                                              _payload.slice(40, _payload.length - 40)
                                          );
                                          // no point in requires, because it will revert regardless
                                          uint256 externalGas = gasleft() - dstGasReserve;
                                          (bool safeCallSuccess, bytes memory reason) = intendedReceiver.safeCall(externalGas, 0, 150, callData); // only return 150 bytes of data
                                          if (!safeCallSuccess) {
                                              payloadHashes[_srcChainId][_srcAddress][_nonce] = keccak256(abi.encodePacked(intendedReceiver, callData));
                                              emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, reason);
                                          }
                                      } else {
                                          // do nothing, token swap failed and can't be delivered, tokens are held inside this contract
                                          emit ComposedTokenTransferFailed(_token, intendedReceiver, _amountLD);
                                      }
                                  }
                                  function clearCachedSwap(
                                      uint16 _srcChainId,
                                      bytes calldata _srcAddress,
                                      uint64 _nonce,
                                      address _receiver,
                                      bytes calldata _sgReceiveCallData
                                  ) external nonReentrant {
                                      bytes32 hash = keccak256(abi.encodePacked(_receiver, _sgReceiveCallData));
                                      require(payloadHashes[_srcChainId][_srcAddress][_nonce] == hash, "Stargate: invalid hash");
                                      delete payloadHashes[_srcChainId][_srcAddress][_nonce];
                                      (bool success, bytes memory reason) = _receiver.safeCall(gasleft(), 0, 150, _sgReceiveCallData);
                                      if (!success) {
                                          assembly {
                                              revert(add(32, reason), mload(reason))
                                          }
                                      }
                                  }
                                  function setDstGasReserve(uint256 _dstGasReserve) onlyOwner external {
                                      dstGasReserve = _dstGasReserve;
                                  }
                                  function setTransferOverhead(uint256 _transferOverhead) onlyOwner external {
                                      transferOverhead = _transferOverhead;
                                  }
                                  function setStargateEthVaults(uint256 _poolId, address _stargateEthVault) onlyOwner public {
                                      stargateEthVaults[_poolId] = _stargateEthVault;
                                  }
                                  function setWethPoolId(uint256 _wethPoolId) onlyOwner external {
                                      wethPoolId = _wethPoolId;
                                  }
                                  function setPeer(uint16 _chainId, address _peer) onlyOwner external {
                                      require(peers[_chainId] == address(0), "Stargate: peer already set");
                                      peers[_chainId] = _peer;
                                  }
                                  function recoverToken(address _token, address _to, uint256 _amount) external onlyOwner {
                                      IERC20(_token).safeTransfer(_to, _amount);
                                  }
                                  function isSending() external view returns (bool) {
                                      return _swapStatus == _ENTERED;
                                  }
                                  function isEthPool(uint256 _srcPoolId) internal view returns (bool) {
                                      return stargateEthVaults[_srcPoolId] != address(0);
                                  }
                                  function getPoolInfo(uint256 _poolId) external returns (PoolInfo memory poolInfo) {
                                      return _getPoolInfo(_poolId);
                                  }
                                  function _getPoolInfo(uint256 _poolId) internal returns (PoolInfo memory poolInfo) {
                                      // return early if its already been called
                                      if (poolIdToInfo[_poolId].poolAddress != address(0)) {
                                          return poolIdToInfo[_poolId];
                                      }
                                      address pool = IStargateFactory(factory).getPool(_poolId);
                                      require(address(pool) != address(0), "Stargate: pool does not exist");
                                      IERC20(pool).safeApprove(address(stargateRouter), type(uint256).max);
                                      address token = IPool(pool).token();
                                      require(address(token) != address(0), "Stargate: token does not exist");
                                      IERC20(token).safeApprove(address(stargateRouter), type(uint256).max);
                                      uint256 convertRate = IPool(pool).convertRate();
                                      poolInfo = PoolInfo({token: token, poolAddress: pool, convertRate: convertRate});
                                      poolIdToInfo[_poolId] = poolInfo;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      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.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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.7.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.7.0;
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Moves `amount` tokens from `sender` to `recipient` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              import "./IERC20.sol";
                              import "../../math/SafeMath.sol";
                              import "../../utils/Address.sol";
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using SafeMath for uint256;
                                  using Address for address;
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                                  }
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                                  }
                                  /**
                                   * @dev Deprecated. This function has issues similar to the ones found in
                                   * {IERC20-approve}, and its usage is discouraged.
                                   *
                                   * Whenever possible, use {safeIncreaseAllowance} and
                                   * {safeDecreaseAllowance} instead.
                                   */
                                  function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                      // safeApprove should only be called when setting an initial allowance,
                                      // or when resetting it to zero. To increase and decrease it, use
                                      // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                      // solhint-disable-next-line max-line-length
                                      require((value == 0) || (token.allowance(address(this), spender) == 0),
                                          "SafeERC20: approve from non-zero to non-zero allowance"
                                      );
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                                  }
                                  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                                      bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                      if (returndata.length > 0) { // Return data is optional
                                          // solhint-disable-next-line max-line-length
                                          require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.7.6 <=0.8.4;
                              pragma abicoder v2;
                              interface IStargateRouter {
                                  struct lzTxObj {
                                      uint256 dstGasForCall;
                                      uint256 dstNativeAmount;
                                      bytes dstNativeAddr;
                                  }
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external;
                                  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;
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external returns (uint256);
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable;
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              interface IStargateReceiver {
                                  function sgReceive(
                                      uint16 _chainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      address _token,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              interface IStargateEthVault {
                                  function deposit() external payable;
                                  function transfer(address to, uint value) external returns (bool);
                                  function withdraw(uint) external;
                                  function approve(address guy, uint wad) external returns (bool);
                                  function transferFrom(
                                      address src,
                                      address dst,
                                      uint wad
                                  ) external returns (bool);
                              }
                              // SPDX-License-Identifier: Unlicense
                              /*
                               * @title Solidity Bytes Arrays Utils
                               * @author Gonçalo Sá <[email protected]>
                               *
                               * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
                               *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
                               */
                              pragma solidity >=0.7.0 <0.8.0;
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              library BytesLib {
                                  using SafeMath for uint256;
                                  function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
                                      require(_length.add(31) >= _length, "slice_overflow");
                                      require(_bytes.length >= _start.add(_length), "slice_outOfBounds");
                                      bytes memory tempBytes;
                                      assembly {
                                          switch iszero(_length)
                                          case 0 {
                                              // Get a location of some free memory and store it in tempBytes as
                                              // Solidity does for memory variables.
                                              tempBytes := mload(0x40)
                                              // The first word of the slice result is potentially a partial
                                              // word read from the original array. To read it, we calculate
                                              // the length of that partial word and start copying that many
                                              // bytes into the array. The first word we copy will start with
                                              // data we don't care about, but the last `lengthmod` bytes will
                                              // land at the beginning of the contents of the new array. When
                                              // we're done copying, we overwrite the full first word with
                                              // the actual length of the slice.
                                              let lengthmod := and(_length, 31)
                                              // The multiplication in the next line is necessary
                                              // because when slicing multiples of 32 bytes (lengthmod == 0)
                                              // the following copy loop was copying the origin's length
                                              // and then ending prematurely not copying everything it should.
                                              let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                                              let end := add(mc, _length)
                                              for {
                                                  // The multiplication in the next line has the same exact purpose
                                                  // as the one above.
                                                  let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                                              } lt(mc, end) {
                                                  mc := add(mc, 0x20)
                                                  cc := add(cc, 0x20)
                                              } {
                                                  mstore(mc, mload(cc))
                                              }
                                              mstore(tempBytes, _length)
                                              //update free-memory pointer
                                              //allocating the array padded to 32 bytes like the compiler does now
                                              mstore(0x40, and(add(mc, 31), not(31)))
                                          }
                                          //if we want a zero-length slice let's just return a zero-length array
                                          default {
                                              tempBytes := mload(0x40)
                                              //zero out the 32 bytes slice we are about to return
                                              //we need to do it because Solidity does not garbage collect
                                              mstore(tempBytes, 0)
                                              mstore(0x40, add(tempBytes, 0x20))
                                          }
                                      }
                                      return tempBytes;
                                  }
                                  function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                                      require(_bytes.length >= _start.add(2), "toUint16_outOfBounds");
                                      uint16 tempUint;
                                      assembly {
                                          tempUint := mload(add(add(_bytes, 0x2), _start))
                                      }
                                      return tempUint;
                                  }
                                  function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                                      require(_bytes.length >= _start.add(32), "toBytes32_outOfBounds");
                                      bytes32 tempBytes32;
                                      assembly {
                                          tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                                      }
                                      return tempBytes32;
                                  }
                                  function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
                                      require(_bytes.length >= _start.add(20), "toAddress_outOfBounds");
                                      address tempAddress;
                                      assembly {
                                          tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                                      }
                                      return tempAddress;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              library SafeCall {
                                  /// @notice calls a contract with a specified gas limit and value and captures the return data
                                  /// @dev copied from https://github.com/nomad-xyz/ExcessivelySafeCall/blob/main/src/ExcessivelySafeCall.sol.
                                  /// @param _target The address to call
                                  /// @param _gas The amount of gas to forward to the remote contract
                                  /// @param _value The value in wei to send to the remote contract
                                  /// @param _maxCopy The maximum number of bytes of returndata to copy
                                  /// to memory.
                                  /// @param _calldata The data to send to the remote contract
                                  /// @return success and returndata, as `.call()`. Returndata is capped to
                                  /// `_maxCopy` bytes.
                                  function safeCall(
                                      address _target,
                                      uint256 _gas,
                                      uint256 _value,
                                      uint16 _maxCopy,
                                      bytes memory _calldata
                                  ) internal returns (bool, bytes memory) {
                                      // set up for assembly call
                                      uint256 _toCopy;
                                      bool _success;
                                      bytes memory _returnData = new bytes(_maxCopy);
                                      // dispatch message to recipient
                                      // by assembly calling "handle" function
                                      // we call via assembly to avoid memcopying a very large returndata
                                      // returned by a malicious contract
                                      assembly {
                                          _success := call(
                                              _gas, // gas
                                              _target, // recipient
                                              _value, // ether value
                                              add(_calldata, 0x20), // inloc
                                              mload(_calldata), // inlen
                                              0, // outloc
                                              0 // outlen
                                          )
                                          // limit our copy to 256 bytes
                                          _toCopy := returndatasize()
                                          if gt(_toCopy, _maxCopy) {
                                              _toCopy := _maxCopy
                                          }
                                          // Store the length of the copied bytes
                                          mstore(_returnData, _toCopy)
                                          // copy the bytes from returndata[0:_toCopy]
                                          returndatacopy(add(_returnData, 0x20), 0, _toCopy)
                                      }
                                      return (_success, _returnData);
                                  }
                              }
                              

                              File 10 of 16: Router
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./Factory.sol";
                              import "./Pool.sol";
                              import "./Bridge.sol";
                              // interfaces
                              import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              import "./interfaces/IStargateRouter.sol";
                              import "./interfaces/IStargateReceiver.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract Router is IStargateRouter, Ownable, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  uint8 internal constant TYPE_REDEEM_LOCAL_RESPONSE = 1;
                                  uint8 internal constant TYPE_REDEEM_LOCAL_CALLBACK_RETRY = 2;
                                  uint8 internal constant TYPE_SWAP_REMOTE_RETRY = 3;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct CachedSwap {
                                      address token;
                                      uint256 amountLD;
                                      address to;
                                      bytes payload;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  Factory public factory; // used for creating pools
                                  address public protocolFeeOwner; // can call methods to pull Stargate fees collected in pools
                                  address public mintFeeOwner; // can call methods to pull mint fees collected in pools
                                  Bridge public bridge;
                                  mapping(uint16 => mapping(bytes => mapping(uint256 => bytes))) public revertLookup; //[chainId][srcAddress][nonce]
                                  mapping(uint16 => mapping(bytes => mapping(uint256 => CachedSwap))) public cachedSwapLookup; //[chainId][srcAddress][nonce]
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Revert(uint8 bridgeFunctionType, uint16 chainId, bytes srcAddress, uint256 nonce);
                                  event CachedSwapSaved(uint16 chainId, bytes srcAddress, uint256 nonce, address token, uint256 amountLD, address to, bytes payload, bytes reason);
                                  event RevertRedeemLocal(uint16 srcChainId, uint256 _srcPoolId, uint256 _dstPoolId, bytes to, uint256 redeemAmountSD, uint256 mintAmountSD, uint256 indexed nonce, bytes indexed srcAddress);
                                  event RedeemLocalCallback(uint16 srcChainId, bytes indexed srcAddress, uint256 indexed nonce, uint256 srcPoolId, uint256 dstPoolId, address to, uint256 amountSD, uint256 mintAmountSD);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyBridge() {
                                      require(msg.sender == address(bridge), "Bridge: caller must be Bridge.");
                                      _;
                                  }
                                  constructor() {}
                                  function setBridgeAndFactory(Bridge _bridge, Factory _factory) external onlyOwner {
                                      require(address(bridge) == address(0x0) && address(factory) == address(0x0), "Stargate: bridge and factory already initialized"); // 1 time only
                                      require(address(_bridge) != address(0x0), "Stargate: bridge cant be 0x0");
                                      require(address(_factory) != address(0x0), "Stargate: factory cant be 0x0");
                                      bridge = _bridge;
                                      factory = _factory;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VIEWS
                                  function _getPool(uint256 _poolId) internal view returns (Pool pool) {
                                      pool = factory.getPool(_poolId);
                                      require(address(pool) != address(0x0), "Stargate: Pool does not exist");
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  function _safeTransferFrom(
                                      address token,
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      // 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))), "Stargate: TRANSFER_FROM_FAILED");
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external override nonReentrant {
                                      Pool pool = _getPool(_poolId);
                                      uint256 convertRate = pool.convertRate();
                                      _amountLD = _amountLD.div(convertRate).mul(convertRate);
                                      _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);
                                      pool.mint(_to, _amountLD);
                                  }
                                  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 override nonReentrant {
                                      require(_amountLD > 0, "Stargate: cannot swap 0");
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool.SwapObj memory s;
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(_srcPoolId);
                                          {
                                              uint256 convertRate = pool.convertRate();
                                              _amountLD = _amountLD.div(convertRate).mul(convertRate);
                                          }
                                          s = pool.swap(_dstChainId, _dstPoolId, msg.sender, _amountLD, _minAmountLD, true);
                                          _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);
                                          c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      }
                                      bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, _payload);
                                  }
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      require(_amountLP > 0, "Stargate: not enough lp to redeemRemote");
                                      Pool.SwapObj memory s;
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(_srcPoolId);
                                          uint256 amountLD = pool.amountLPtoLD(_amountLP);
                                          // perform a swap with no liquidity
                                          s = pool.swap(_dstChainId, _dstPoolId, msg.sender, amountLD, _minAmountLD, false);
                                          pool.redeemRemote(_dstChainId, _dstPoolId, msg.sender, _amountLP);
                                          c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      }
                                      // equal to a swap, with no payload ("0x") no dstGasForCall 0
                                      bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, "");
                                  }
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external override nonReentrant returns (uint256 amountSD) {
                                      require(_amountLP > 0, "Stargate: not enough lp to redeem");
                                      Pool pool = _getPool(_srcPoolId);
                                      amountSD = pool.instantRedeemLocal(msg.sender, _amountLP, _to);
                                  }
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool pool = _getPool(_srcPoolId);
                                      require(_amountLP > 0, "Stargate: not enough lp to redeem");
                                      uint256 amountSD = pool.redeemLocal(msg.sender, _amountLP, _dstChainId, _dstPoolId, _to);
                                      require(amountSD > 0, "Stargate: not enough lp to redeem with amountSD");
                                      Pool.CreditObj memory c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      bridge.redeemLocal{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, amountSD, _to, _lzTxParams);
                                  }
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable override nonReentrant {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      Pool pool = _getPool(_srcPoolId);
                                      Pool.CreditObj memory c = pool.sendCredits(_dstChainId, _dstPoolId);
                                      bridge.sendCredits{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c);
                                  }
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      Router.lzTxObj memory _lzTxParams
                                  ) external view override returns (uint256, uint256) {
                                      return bridge.quoteLayerZeroFee(_dstChainId, _functionType, _toAddress, _transferAndCallPayload, _lzTxParams);
                                  }
                                  function revertRedeemLocal(
                                      uint16 _dstChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce,
                                      address payable _refundAddress,
                                      lzTxObj memory _lzTxParams
                                  ) external payable {
                                      require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");
                                      bytes memory payload = revertLookup[_dstChainId][_srcAddress][_nonce];
                                      require(payload.length > 0, "Stargate: no retry revert");
                                      {
                                          uint8 functionType;
                                          assembly {
                                              functionType := mload(add(payload, 32))
                                          }
                                          require(functionType == TYPE_REDEEM_LOCAL_RESPONSE, "Stargate: invalid function type");
                                      }
                                      // empty it
                                      revertLookup[_dstChainId][_srcAddress][_nonce] = "";
                                      uint256 srcPoolId;
                                      uint256 dstPoolId;
                                      assembly {
                                          srcPoolId := mload(add(payload, 64))
                                          dstPoolId := mload(add(payload, 96))
                                      }
                                      Pool.CreditObj memory c;
                                      {
                                          Pool pool = _getPool(dstPoolId);
                                          c = pool.sendCredits(_dstChainId, srcPoolId);
                                      }
                                      bridge.redeemLocalCallback{value: msg.value}(_dstChainId, _refundAddress, c, _lzTxParams, payload);
                                  }
                                  function retryRevert(
                                      uint16 _srcChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce
                                  ) external payable {
                                      bytes memory payload = revertLookup[_srcChainId][_srcAddress][_nonce];
                                      require(payload.length > 0, "Stargate: no retry revert");
                                      // empty it
                                      revertLookup[_srcChainId][_srcAddress][_nonce] = "";
                                      uint8 functionType;
                                      assembly {
                                          functionType := mload(add(payload, 32))
                                      }
                                      if (functionType == TYPE_REDEEM_LOCAL_CALLBACK_RETRY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, address to, uint256 amountSD, uint256 mintAmountSD) = abi.decode(
                                              payload,
                                              (uint8, uint256, uint256, address, uint256, uint256)
                                          );
                                          _redeemLocalCallback(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, to, amountSD, mintAmountSD);
                                      }
                                      // for retrying the swapRemote. if it fails again, retry
                                      else if (functionType == TYPE_SWAP_REMOTE_RETRY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, uint256 dstGasForCall, address to, Pool.SwapObj memory s, bytes memory p) = abi.decode(
                                              payload,
                                              (uint8, uint256, uint256, uint256, address, Pool.SwapObj, bytes)
                                          );
                                          _swapRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, dstGasForCall, to, s, p);
                                      } else {
                                          revert("Stargate: invalid function type");
                                      }
                                  }
                                  function clearCachedSwap(
                                      uint16 _srcChainId,
                                      bytes calldata _srcAddress,
                                      uint256 _nonce
                                  ) external {
                                      CachedSwap memory cs = cachedSwapLookup[_srcChainId][_srcAddress][_nonce];
                                      require(cs.to != address(0x0), "Stargate: cache already cleared");
                                      // clear the data
                                      cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(address(0x0), 0, address(0x0), "");
                                      IStargateReceiver(cs.to).sgReceive(_srcChainId, _srcAddress, _nonce, cs.token, cs.amountLD, cs.payload);
                                  }
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _srcPoolId,
                                      Pool.CreditObj memory _c
                                  ) external onlyBridge {
                                      Pool pool = _getPool(_srcPoolId);
                                      pool.creditChainPath(_dstChainId, _dstPoolId, _c);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _amountSD,
                                      bytes calldata _to
                                  ) external onlyBridge {
                                      Pool pool = _getPool(_dstPoolId);
                                      try pool.redeemLocalCheckOnRemote(_srcChainId, _srcPoolId, _amountSD) returns (uint256 redeemAmountSD, uint256 mintAmountSD) {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_REDEEM_LOCAL_RESPONSE,
                                              _srcPoolId,
                                              _dstPoolId,
                                              redeemAmountSD,
                                              mintAmountSD,
                                              _to
                                          );
                                          emit RevertRedeemLocal(_srcChainId, _srcPoolId, _dstPoolId, _to, redeemAmountSD, mintAmountSD, _nonce, _srcAddress);
                                      } catch {
                                          // if the func fail, return [swapAmount: 0, mintAMount: _amountSD]
                                          // swapAmount represents the amount of chainPath balance deducted on the remote side, which because the above tx failed, should be 0
                                          // mintAmount is the full amount of tokens the user attempted to redeem on the src side, which gets converted back into the lp amount
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(TYPE_REDEEM_LOCAL_RESPONSE, _srcPoolId, _dstPoolId, 0, _amountSD, _to);
                                          emit Revert(TYPE_REDEEM_LOCAL_RESPONSE, _srcChainId, _srcAddress, _nonce);
                                      }
                                  }
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _mintAmountSD
                                  ) external onlyBridge {
                                      _redeemLocalCallback(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _to, _amountSD, _mintAmountSD);
                                  }
                                  function _redeemLocalCallback(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _mintAmountSD
                                  ) internal {
                                      Pool pool = _getPool(_dstPoolId);
                                      try pool.redeemLocalCallback(_srcChainId, _srcPoolId, _to, _amountSD, _mintAmountSD) {} catch {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_REDEEM_LOCAL_CALLBACK_RETRY,
                                              _srcPoolId,
                                              _dstPoolId,
                                              _to,
                                              _amountSD,
                                              _mintAmountSD
                                          );
                                          emit Revert(TYPE_REDEEM_LOCAL_CALLBACK_RETRY, _srcChainId, _srcAddress, _nonce);
                                      }
                                      emit RedeemLocalCallback(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _to, _amountSD, _mintAmountSD);
                                  }
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _dstGasForCall,
                                      address _to,
                                      Pool.SwapObj memory _s,
                                      bytes memory _payload
                                  ) external onlyBridge {
                                      _swapRemote(_srcChainId, _srcAddress, _nonce, _srcPoolId, _dstPoolId, _dstGasForCall, _to, _s, _payload);
                                  }
                                  function _swapRemote(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _dstGasForCall,
                                      address _to,
                                      Pool.SwapObj memory _s,
                                      bytes memory _payload
                                  ) internal {
                                      Pool pool = _getPool(_dstPoolId);
                                      // first try catch the swap remote
                                      try pool.swapRemote(_srcChainId, _srcPoolId, _to, _s) returns (uint256 amountLD) {
                                          if (_payload.length > 0) {
                                              // then try catch the external contract call
                                              try IStargateReceiver(_to).sgReceive{gas: _dstGasForCall}(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _payload) {
                                                  // do nothing
                                              } catch (bytes memory reason) {
                                                  cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(pool.token(), amountLD, _to, _payload);
                                                  emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _to, _payload, reason);
                                              }
                                          }
                                      } catch {
                                          revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(
                                              TYPE_SWAP_REMOTE_RETRY,
                                              _srcPoolId,
                                              _dstPoolId,
                                              _dstGasForCall,
                                              _to,
                                              _s,
                                              _payload
                                          );
                                          emit Revert(TYPE_SWAP_REMOTE_RETRY, _srcChainId, _srcAddress, _nonce);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) external onlyOwner returns (address) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      return factory.createPool(_poolId, _token, _sharedDecimals, _localDecimals, _name, _symbol);
                                  }
                                  function createChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.createChainPath(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function activateChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.activateChainPath(_dstChainId, _dstPoolId);
                                  }
                                  function setWeightForChainPath(
                                      uint256 _poolId,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setWeightForChainPath(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setProtocolFeeOwner(address _owner) external onlyOwner {
                                      require(_owner != address(0x0), "Stargate: _owner cannot be 0x0");
                                      protocolFeeOwner = _owner;
                                  }
                                  function setMintFeeOwner(address _owner) external onlyOwner {
                                      require(_owner != address(0x0), "Stargate: _owner cannot be 0x0");
                                      mintFeeOwner = _owner;
                                  }
                                  function setFees(uint256 _poolId, uint256 _mintFeeBP) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setFee(_mintFeeBP);
                                  }
                                  function setFeeLibrary(uint256 _poolId, address _feeLibraryAddr) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setFeeLibrary(_feeLibraryAddr);
                                  }
                                  function setSwapStop(uint256 _poolId, bool _swapStop) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setSwapStop(_swapStop);
                                  }
                                  function setDeltaParam(
                                      uint256 _poolId,
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyOwner {
                                      Pool pool = _getPool(_poolId);
                                      pool.setDeltaParam(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(uint256 _poolId, bool _fullMode) external {
                                      Pool pool = _getPool(_poolId);
                                      pool.callDelta(_fullMode);
                                  }
                                  function withdrawMintFee(uint256 _poolId, address _to) external {
                                      require(mintFeeOwner == msg.sender, "Stargate: only mintFeeOwner");
                                      Pool pool = _getPool(_poolId);
                                      pool.withdrawMintFeeBalance(_to);
                                  }
                                  function withdrawProtocolFee(uint256 _poolId, address _to) external {
                                      require(protocolFeeOwner == msg.sender, "Stargate: only protocolFeeOwner");
                                      Pool pool = _getPool(_poolId);
                                      pool.withdrawProtocolFeeBalance(_to);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              contract Factory is Ownable {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  mapping(uint256 => Pool) public getPool; // poolId -> PoolInfo
                                  address[] public allPools;
                                  address public immutable router;
                                  address public defaultFeeLibrary; // address for retrieving fee params for swaps
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _router) {
                                      require(_router != address(0x0), "Stargate: _router cant be 0x0"); // 1 time only
                                      router = _router;
                                  }
                                  function setDefaultFeeLibrary(address _defaultFeeLibrary) external onlyOwner {
                                      require(_defaultFeeLibrary != address(0x0), "Stargate: fee library cant be 0x0");
                                      defaultFeeLibrary = _defaultFeeLibrary;
                                  }
                                  function allPoolsLength() external view returns (uint256) {
                                      return allPools.length;
                                  }
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) public onlyRouter returns (address poolAddress) {
                                      require(address(getPool[_poolId]) == address(0x0), "Stargate: Pool already created");
                                      Pool pool = new Pool(_poolId, router, _token, _sharedDecimals, _localDecimals, defaultFeeLibrary, _name, _symbol);
                                      getPool[_poolId] = pool;
                                      poolAddress = address(pool);
                                      allPools.push(poolAddress);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./LPTokenERC20.sol";
                              import "./interfaces/IStargateFeeLibrary.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              /// Pool contracts on other chains and managed by the Stargate protocol.
                              contract Pool is LPTokenERC20, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 public constant BP_DENOMINATOR = 10000;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct ChainPath {
                                      bool ready; // indicate if the counter chainPath has been created.
                                      uint16 dstChainId;
                                      uint256 dstPoolId;
                                      uint256 weight;
                                      uint256 balance;
                                      uint256 lkb;
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  struct SwapObj {
                                      uint256 amount;
                                      uint256 eqFee;
                                      uint256 eqReward;
                                      uint256 lpFee;
                                      uint256 protocolFee;
                                      uint256 lkbRemove;
                                  }
                                  struct CreditObj {
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // chainPath
                                  ChainPath[] public chainPaths; // list of connected chains with shared pools
                                  mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
                                  // metadata
                                  uint256 public immutable poolId; // shared id between chains to represent same pool
                                  uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
                                  uint256 public localDecimals; // the decimals for the token
                                  uint256 public immutable convertRate; // the decimals for the token
                                  address public immutable token; // the token for the pool
                                  address public immutable router; // the token for the pool
                                  bool public stopSwap; // flag to stop swapping in extreme cases
                                  // Fee and Liquidity
                                  uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
                                  uint256 public totalWeight; // total weight for pool percentages
                                  uint256 public mintFeeBP; // fee basis points for the mint/deposit
                                  uint256 public protocolFeeBalance; // fee balance created from dao fee
                                  uint256 public mintFeeBalance; // fee balance created from mint fee
                                  uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
                                  address public feeLibrary; // address for retrieving fee params for swaps
                                  // Delta related
                                  uint256 public deltaCredit; // credits accumulated from txn
                                  bool public batched; // flag to indicate if we want batch processing.
                                  bool public defaultSwapMode; // flag for the default mode for swap
                                  bool public defaultLPMode; // flag for the default mode for lp
                                  uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
                                  uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
                                  event Burn(address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
                                  event Swap(
                                      uint16 chainId,
                                      uint256 dstPoolId,
                                      address from,
                                      uint256 amountSD,
                                      uint256 eqReward,
                                      uint256 eqFee,
                                      uint256 protocolFee,
                                      uint256 lpFee
                                  );
                                  event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
                                  event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
                                  event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
                                  event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
                                  event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
                                  event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
                                  event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
                                  event FeesUpdated(uint256 mintFeeBP);
                                  event FeeLibraryUpdated(address feeLibraryAddr);
                                  event StopSwapUpdated(bool swapStop);
                                  event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
                                  event WithdrawMintFeeBalance(address to, uint256 amountSD);
                                  event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: only the router can call this method");
                                      _;
                                  }
                                  constructor(
                                      uint256 _poolId,
                                      address _router,
                                      address _token,
                                      uint256 _sharedDecimals,
                                      uint256 _localDecimals,
                                      address _feeLibrary,
                                      string memory _name,
                                      string memory _symbol
                                  ) LPTokenERC20(_name, _symbol) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      poolId = _poolId;
                                      router = _router;
                                      token = _token;
                                      sharedDecimals = _sharedDecimals;
                                      decimals = uint8(_sharedDecimals);
                                      localDecimals = _localDecimals;
                                      convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
                                      totalWeight = 0;
                                      feeLibrary = _feeLibrary;
                                      //delta algo related
                                      batched = false;
                                      defaultSwapMode = true;
                                      defaultLPMode = true;
                                  }
                                  function getChainPathsLength() public view returns (uint256) {
                                      return chainPaths.length;
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
                                      return _mintLocal(_to, _amountLD, true, true);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      bool newLiquidity
                                  ) external nonReentrant onlyRouter returns (SwapObj memory) {
                                      require(!stopSwap, "Stargate: swap func stopped");
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      uint256 amountSD = amountLDtoSD(_amountLD);
                                      uint256 minAmountSD = amountLDtoSD(_minAmountLD);
                                      // request fee params from library
                                      SwapObj memory s = IStargateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
                                      // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
                                      eqFeePool = eqFeePool.sub(s.eqReward);
                                      // update the new amount the user gets minus the fees
                                      s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
                                      // users will also get the eqReward
                                      require(s.amount.add(s.eqReward) >= minAmountSD, "Stargate: slippage too high");
                                      // behaviours
                                      //     - protocolFee: booked, stayed and withdrawn at remote.
                                      //     - eqFee: booked, stayed and withdrawn at remote.
                                      //     - lpFee: booked and stayed at remote, can be withdrawn anywhere
                                      s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
                                      // check for transfer solvency.
                                      require(cp.balance >= s.lkbRemove, "Stargate: dst balance too low");
                                      cp.balance = cp.balance.sub(s.lkbRemove);
                                      if (newLiquidity) {
                                          deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
                                      } else if (s.eqReward > 0) {
                                          deltaCredit = deltaCredit.add(s.eqReward);
                                      }
                                      // distribute credits on condition.
                                      if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultSwapMode);
                                      }
                                      emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
                                      return s;
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      cp.lkb = cp.lkb.add(cp.credits);
                                      c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
                                      c.credits = cp.credits;
                                      cp.credits = 0;
                                      emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemRemote   ->                        swapRemote
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLP
                                  ) external nonReentrant onlyRouter {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 amountSD = _burnLocal(_from, _amountLP);
                                      //run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
                                  }
                                  function instantRedeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      address _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 _deltaCredit = deltaCredit; // sload optimization.
                                      uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
                                      if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
                                      amountSD = _burnLocal(_from, _amountLP);
                                      deltaCredit = _deltaCredit.sub(amountSD);
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      bytes calldata _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      // safeguard.
                                      require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Stargate: counter chainPath is not ready");
                                      amountSD = _burnLocal(_from, _amountLP);
                                      // run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(false);
                                      }
                                      emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      CreditObj memory _c
                                  ) external nonReentrant onlyRouter {
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      cp.balance = cp.balance.add(_c.credits);
                                      if (cp.idealBalance != _c.idealBalance) {
                                          cp.idealBalance = _c.idealBalance;
                                      }
                                      emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      SwapObj memory _s
                                  ) external nonReentrant onlyRouter returns (uint256 amountLD) {
                                      // booking lpFee
                                      totalLiquidity = totalLiquidity.add(_s.lpFee);
                                      // booking eqFee
                                      eqFeePool = eqFeePool.add(_s.eqFee);
                                      // booking stargateFee
                                      protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
                                      // update LKB
                                      uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
                                      chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
                                      // user receives the amount + the srcReward
                                      amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
                                      _safeTransfer(token, _to, amountLD);
                                      emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _amountToMintSD
                                  ) external nonReentrant onlyRouter {
                                      if (_amountToMintSD > 0) {
                                          _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
                                      }
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      cp.lkb = cp.lkb.sub(_amountSD);
                                      uint256 amountLD = amountSDtoLD(_amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal(amount)   ->               redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      uint256 _amountSD
                                  ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      if (_amountSD > cp.balance) {
                                          mintAmount = _amountSD - cp.balance;
                                          swapAmount = cp.balance;
                                          cp.balance = 0;
                                      } else {
                                          cp.balance = cp.balance.sub(_amountSD);
                                          swapAmount = _amountSD;
                                          mintAmount = 0;
                                      }
                                      emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyRouter {
                                      for (uint256 i = 0; i < chainPaths.length; ++i) {
                                          ChainPath memory cp = chainPaths[i];
                                          bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
                                          require(!exists, "Stargate: cant createChainPath of existing dstChainId and _dstPoolId");
                                      }
                                      totalWeight = totalWeight.add(_weight);
                                      chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
                                      chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setWeightForChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      totalWeight = totalWeight.sub(cp.weight).add(_weight);
                                      cp.weight = _weight;
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setFee(uint256 _mintFeeBP) external onlyRouter {
                                      require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
                                      mintFeeBP = _mintFeeBP;
                                      emit FeesUpdated(mintFeeBP);
                                  }
                                  function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
                                      require(_feeLibraryAddr != address(0x0), "Stargate: fee library cant be 0x0");
                                      feeLibrary = _feeLibraryAddr;
                                      emit FeeLibraryUpdated(_feeLibraryAddr);
                                  }
                                  function setSwapStop(bool _swapStop) external onlyRouter {
                                      stopSwap = _swapStop;
                                      emit StopSwapUpdated(_swapStop);
                                  }
                                  function setDeltaParam(
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyRouter {
                                      require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Stargate: wrong Delta param");
                                      batched = _batched;
                                      swapDeltaBP = _swapDeltaBP;
                                      lpDeltaBP = _lpDeltaBP;
                                      defaultSwapMode = _defaultSwapMode;
                                      defaultLPMode = _defaultLPMode;
                                      emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(bool _fullMode) external onlyRouter {
                                      _delta(_fullMode);
                                  }
                                  function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == false, "Stargate: chainPath is already active");
                                      // this func will only be called once
                                      cp.ready = true;
                                  }
                                  function withdrawProtocolFeeBalance(address _to) external onlyRouter {
                                      if (protocolFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
                                          protocolFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawProtocolFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  function withdrawMintFeeBalance(address _to) external onlyRouter {
                                      if (mintFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
                                          mintFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawMintFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  // Conversion Helpers
                                  //---------------------------------------------------------------------------
                                  function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
                                      return amountSDtoLD(_amountLPtoSD(_amountLP));
                                  }
                                  function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant convert LPtoSD when totalSupply == 0");
                                      return _amountLP.mul(totalLiquidity).div(totalSupply);
                                  }
                                  function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
                                      require(totalLiquidity > 0, "Stargate: cant convert SDtoLP when totalLiq == 0");
                                      return _amountSD.mul(totalSupply).div(totalLiquidity);
                                  }
                                  function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.mul(convertRate);
                                  }
                                  function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.div(convertRate);
                                  }
                                  function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
                                      require(chainPaths.length > 0, "Stargate: no chainpaths exist");
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
                                      ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant burn when totalSupply == 0");
                                      uint256 amountOfLPTokens = balanceOf[_from];
                                      require(amountOfLPTokens >= _amountLP, "Stargate: not enough LP tokens to burn");
                                      uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
                                      //subtract totalLiquidity accordingly
                                      totalLiquidity = totalLiquidity.sub(amountSD);
                                      _burn(_from, _amountLP);
                                      emit Burn(_from, _amountLP, amountSD);
                                      return amountSD;
                                  }
                                  function _delta(bool fullMode) internal {
                                      if (deltaCredit > 0 && totalWeight > 0) {
                                          uint256 cpLength = chainPaths.length;
                                          uint256[] memory deficit = new uint256[](cpLength);
                                          uint256 totalDeficit = 0;
                                          // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
                                          for (uint256 i = 0; i < cpLength; ++i) {
                                              ChainPath storage cp = chainPaths[i];
                                              // (liquidity * (weight/totalWeight)) - (lkb+credits)
                                              uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
                                              uint256 currLiq = cp.lkb.add(cp.credits);
                                              if (balLiq > currLiq) {
                                                  // save gas since we know balLiq > currLiq and we know deficit[i] > 0
                                                  deficit[i] = balLiq - currLiq;
                                                  totalDeficit = totalDeficit.add(deficit[i]);
                                              }
                                          }
                                          // indicates how much delta credit is distributed
                                          uint256 spent;
                                          // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
                                          // run full Delta, allocate all credits
                                          if (totalDeficit == 0) {
                                              // only fullMode delta will allocate excess credits
                                              if (fullMode && deltaCredit > 0) {
                                                  // credit ChainPath by weights
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      // credits = credits + toBalanceChange + remaining allocation based on weight
                                                      uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
                                                      spent = spent.add(amtToCredit);
                                                      cp.credits = cp.credits.add(amtToCredit);
                                                  }
                                              } // else do nth
                                          } else if (totalDeficit <= deltaCredit) {
                                              if (fullMode) {
                                                  // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
                                                  uint256 excessCredit = deltaCredit - totalDeficit;
                                                  // algorithm steps 14-16: calculate credits
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          // credits = credits + deficit + remaining allocation based on weight
                                                          uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              } else {
                                                  // totalDeficit <= deltaCredit but not running fullMode
                                                  // credit chainPaths as is if any deficit, not using all deltaCredit
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          uint256 amtToCredit = deficit[i];
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              }
                                          } else {
                                              // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
                                              for (uint256 i = 0; i < cpLength; ++i) {
                                                  if (deficit[i] > 0) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
                                                      spent = spent.add(proportionalDeficit);
                                                      cp.credits = cp.credits.add(proportionalDeficit);
                                                  }
                                              }
                                          }
                                          // deduct the amount of credit sent
                                          deltaCredit = deltaCredit.sub(spent);
                                      }
                                  }
                                  function _mintLocal(
                                      address _to,
                                      uint256 _amountLD,
                                      bool _feesEnabled,
                                      bool _creditDelta
                                  ) internal returns (uint256 amountSD) {
                                      require(totalWeight > 0, "Stargate: No ChainPaths exist");
                                      amountSD = amountLDtoSD(_amountLD);
                                      uint256 mintFeeSD = 0;
                                      if (_feesEnabled) {
                                          mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
                                          amountSD = amountSD.sub(mintFeeSD);
                                          mintFeeBalance = mintFeeBalance.add(mintFeeSD);
                                      }
                                      if (_creditDelta) {
                                          deltaCredit = deltaCredit.add(amountSD);
                                      }
                                      uint256 amountLPTokens = amountSD;
                                      if (totalSupply != 0) {
                                          amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
                                      }
                                      totalLiquidity = totalLiquidity.add(amountSD);
                                      _mint(_to, amountLPTokens);
                                      emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
                                      // add to credits and call delta. short circuit to save gas
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                  }
                                  function _safeTransfer(
                                      address _token,
                                      address _to,
                                      uint256 _value
                                  ) private {
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
                                      require(success && (data.length == 0 || abi.decode(data, (bool))), "Stargate: TRANSFER_FAILED");
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              import "./Router.sol";
                              // interfaces
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroReceiver.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroEndpoint.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroUserApplicationConfig.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract Bridge is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  uint8 internal constant TYPE_SWAP_REMOTE = 1;
                                  uint8 internal constant TYPE_ADD_LIQUIDITY = 2;
                                  uint8 internal constant TYPE_REDEEM_LOCAL_CALL_BACK = 3;
                                  uint8 internal constant TYPE_WITHDRAW_REMOTE = 4;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  ILayerZeroEndpoint public immutable layerZeroEndpoint;
                                  mapping(uint16 => bytes) public bridgeLookup;
                                  mapping(uint16 => mapping(uint8 => uint256)) public gasLookup;
                                  Router public immutable router;
                                  bool public useLayerZeroToken;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event SendMsg(uint8 msgType, uint64 nonce);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == address(router), "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _layerZeroEndpoint, address _router) {
                                      require(_layerZeroEndpoint != address(0x0), "Stargate: _layerZeroEndpoint cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      layerZeroEndpoint = ILayerZeroEndpoint(_layerZeroEndpoint);
                                      router = Router(_router);
                                  }
                                  //---------------------------------------------------------------------------
                                  // EXTERNAL functions
                                  function lzReceive(
                                      uint16 _srcChainId,
                                      bytes memory _srcAddress,
                                      uint64 _nonce,
                                      bytes memory _payload
                                  ) external override {
                                      require(msg.sender == address(layerZeroEndpoint), "Stargate: only LayerZero endpoint can call lzReceive");
                                      require(
                                          _srcAddress.length == bridgeLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(bridgeLookup[_srcChainId]),
                                          "Stargate: bridge does not match"
                                      );
                                      uint8 functionType;
                                      assembly {
                                          functionType := mload(add(_payload, 32))
                                      }
                                      if (functionType == TYPE_SWAP_REMOTE) {
                                          (
                                              ,
                                              uint256 srcPoolId,
                                              uint256 dstPoolId,
                                              uint256 dstGasForCall,
                                              Pool.CreditObj memory c,
                                              Pool.SwapObj memory s,
                                              bytes memory to,
                                              bytes memory payload
                                          ) = abi.decode(_payload, (uint8, uint256, uint256, uint256, Pool.CreditObj, Pool.SwapObj, bytes, bytes));
                                          address toAddress;
                                          assembly {
                                              toAddress := mload(add(to, 20))
                                          }
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.swapRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, dstGasForCall, toAddress, s, payload);
                                      } else if (functionType == TYPE_ADD_LIQUIDITY) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c) = abi.decode(_payload, (uint8, uint256, uint256, Pool.CreditObj));
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                      } else if (functionType == TYPE_REDEEM_LOCAL_CALL_BACK) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c, uint256 amountSD, uint256 mintAmountSD, bytes memory to) = abi
                                              .decode(_payload, (uint8, uint256, uint256, Pool.CreditObj, uint256, uint256, bytes));
                                          address toAddress;
                                          assembly {
                                              toAddress := mload(add(to, 20))
                                          }
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.redeemLocalCallback(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, toAddress, amountSD, mintAmountSD);
                                      } else if (functionType == TYPE_WITHDRAW_REMOTE) {
                                          (, uint256 srcPoolId, uint256 dstPoolId, Pool.CreditObj memory c, uint256 amountSD, bytes memory to) = abi.decode(
                                              _payload,
                                              (uint8, uint256, uint256, Pool.CreditObj, uint256, bytes)
                                          );
                                          router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);
                                          router.redeemLocalCheckOnRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, amountSD, to);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function swap(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      Pool.SwapObj memory _s,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes calldata _to,
                                      bytes calldata _payload
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_SWAP_REMOTE, _srcPoolId, _dstPoolId, _lzTxParams.dstGasForCall, _c, _s, _to, _payload);
                                      _call(_chainId, TYPE_SWAP_REMOTE, _refundAddress, _lzTxParams, payload);
                                  }
                                  function redeemLocalCallback(
                                      uint16 _chainId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes memory _payload
                                  ) external payable onlyRouter {
                                      bytes memory payload;
                                      {
                                          (, uint256 srcPoolId, uint256 dstPoolId, uint256 amountSD, uint256 mintAmountSD, bytes memory to) = abi.decode(
                                              _payload,
                                              (uint8, uint256, uint256, uint256, uint256, bytes)
                                          );
                                          // swap dst and src because we are headed back
                                          payload = abi.encode(TYPE_REDEEM_LOCAL_CALL_BACK, dstPoolId, srcPoolId, _c, amountSD, mintAmountSD, to);
                                      }
                                      _call(_chainId, TYPE_REDEEM_LOCAL_CALL_BACK, _refundAddress, _lzTxParams, payload);
                                  }
                                  function redeemLocal(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c,
                                      uint256 _amountSD,
                                      bytes calldata _to,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_WITHDRAW_REMOTE, _srcPoolId, _dstPoolId, _c, _amountSD, _to);
                                      _call(_chainId, TYPE_WITHDRAW_REMOTE, _refundAddress, _lzTxParams, payload);
                                  }
                                  function sendCredits(
                                      uint16 _chainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      Pool.CreditObj memory _c
                                  ) external payable onlyRouter {
                                      bytes memory payload = abi.encode(TYPE_ADD_LIQUIDITY, _srcPoolId, _dstPoolId, _c);
                                      IStargateRouter.lzTxObj memory lzTxObj = IStargateRouter.lzTxObj(0, 0, "0x");
                                      _call(_chainId, TYPE_ADD_LIQUIDITY, _refundAddress, lzTxObj, payload);
                                  }
                                  function quoteLayerZeroFee(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256) {
                                      bytes memory payload = "";
                                      Pool.CreditObj memory c = Pool.CreditObj(1, 1);
                                      if (_functionType == TYPE_SWAP_REMOTE) {
                                          Pool.SwapObj memory s = Pool.SwapObj(1, 1, 1, 1, 1, 1);
                                          payload = abi.encode(TYPE_SWAP_REMOTE, 0, 0, 0, c, s, _toAddress, _transferAndCallPayload);
                                      } else if (_functionType == TYPE_ADD_LIQUIDITY) {
                                          payload = abi.encode(TYPE_ADD_LIQUIDITY, 0, 0, c);
                                      } else if (_functionType == TYPE_REDEEM_LOCAL_CALL_BACK) {
                                          payload = abi.encode(TYPE_REDEEM_LOCAL_CALL_BACK, 0, 0, c, 0, 0, _toAddress);
                                      } else if (_functionType == TYPE_WITHDRAW_REMOTE) {
                                          payload = abi.encode(TYPE_WITHDRAW_REMOTE, 0, 0, c, 0, _toAddress);
                                      } else {
                                          revert("Stargate: unsupported function type");
                                      }
                                      bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _functionType, _lzTxParams);
                                      return layerZeroEndpoint.estimateFees(_chainId, address(this), payload, useLayerZeroToken, lzTxParamBuilt);
                                  }
                                  //---------------------------------------------------------------------------
                                  // dao functions
                                  function setBridge(uint16 _chainId, bytes calldata _bridgeAddress) external onlyOwner {
                                      require(bridgeLookup[_chainId].length == 0, "Stargate: Bridge already set!");
                                      bridgeLookup[_chainId] = _bridgeAddress;
                                  }
                                  function setGasAmount(
                                      uint16 _chainId,
                                      uint8 _functionType,
                                      uint256 _gasAmount
                                  ) external onlyOwner {
                                      require(_functionType >= 1 && _functionType <= 4, "Stargate: invalid _functionType");
                                      gasLookup[_chainId][_functionType] = _gasAmount;
                                  }
                                  function approveTokenSpender(
                                      address token,
                                      address spender,
                                      uint256 amount
                                  ) external onlyOwner {
                                      IERC20(token).approve(spender, amount);
                                  }
                                  function setUseLayerZeroToken(bool enable) external onlyOwner {
                                      useLayerZeroToken = enable;
                                  }
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                                      layerZeroEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
                                  }
                                  //---------------------------------------------------------------------------
                                  // generic config for user Application
                                  function setConfig(
                                      uint16 _version,
                                      uint16 _chainId,
                                      uint256 _configType,
                                      bytes calldata _config
                                  ) external override onlyOwner {
                                      layerZeroEndpoint.setConfig(_version, _chainId, _configType, _config);
                                  }
                                  function setSendVersion(uint16 version) external override onlyOwner {
                                      layerZeroEndpoint.setSendVersion(version);
                                  }
                                  function setReceiveVersion(uint16 version) external override onlyOwner {
                                      layerZeroEndpoint.setReceiveVersion(version);
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL functions
                                  function txParamBuilderType1(uint256 _gasAmount) internal pure returns (bytes memory) {
                                      uint16 txType = 1;
                                      return abi.encodePacked(txType, _gasAmount);
                                  }
                                  function txParamBuilderType2(
                                      uint256 _gasAmount,
                                      uint256 _dstNativeAmount,
                                      bytes memory _dstNativeAddr
                                  ) internal pure returns (bytes memory) {
                                      uint16 txType = 2;
                                      return abi.encodePacked(txType, _gasAmount, _dstNativeAmount, _dstNativeAddr);
                                  }
                                  function _txParamBuilder(
                                      uint16 _chainId,
                                      uint8 _type,
                                      IStargateRouter.lzTxObj memory _lzTxParams
                                  ) internal view returns (bytes memory) {
                                      bytes memory lzTxParam;
                                      address dstNativeAddr;
                                      {
                                          bytes memory dstNativeAddrBytes = _lzTxParams.dstNativeAddr;
                                          assembly {
                                              dstNativeAddr := mload(add(dstNativeAddrBytes, 20))
                                          }
                                      }
                                      uint256 totalGas = gasLookup[_chainId][_type].add(_lzTxParams.dstGasForCall);
                                      if (_lzTxParams.dstNativeAmount > 0 && dstNativeAddr != address(0x0)) {
                                          lzTxParam = txParamBuilderType2(totalGas, _lzTxParams.dstNativeAmount, _lzTxParams.dstNativeAddr);
                                      } else {
                                          lzTxParam = txParamBuilderType1(totalGas);
                                      }
                                      return lzTxParam;
                                  }
                                  function _call(
                                      uint16 _chainId,
                                      uint8 _type,
                                      address payable _refundAddress,
                                      IStargateRouter.lzTxObj memory _lzTxParams,
                                      bytes memory _payload
                                  ) internal {
                                      bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _type, _lzTxParams);
                                      uint64 nextNonce = layerZeroEndpoint.getOutboundNonce(_chainId, address(this)) + 1;
                                      layerZeroEndpoint.send{value: msg.value}(_chainId, bridgeLookup[_chainId], _payload, _refundAddress, address(this), lzTxParamBuilt);
                                      emit SendMsg(_type, nextNonce);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              interface IStargateRouter {
                                  struct lzTxObj {
                                      uint256 dstGasForCall;
                                      uint256 dstNativeAmount;
                                      bytes dstNativeAddr;
                                  }
                                  function addLiquidity(
                                      uint256 _poolId,
                                      uint256 _amountLD,
                                      address _to
                                  ) external;
                                  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;
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      uint256 _minAmountLD,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function instantRedeemLocal(
                                      uint16 _srcPoolId,
                                      uint256 _amountLP,
                                      address _to
                                  ) external returns (uint256);
                                  function redeemLocal(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress,
                                      uint256 _amountLP,
                                      bytes calldata _to,
                                      lzTxObj memory _lzTxParams
                                  ) external payable;
                                  function sendCredits(
                                      uint16 _dstChainId,
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      address payable _refundAddress
                                  ) external payable;
                                  function quoteLayerZeroFee(
                                      uint16 _dstChainId,
                                      uint8 _functionType,
                                      bytes calldata _toAddress,
                                      bytes calldata _transferAndCallPayload,
                                      lzTxObj memory _lzTxParams
                                  ) external view returns (uint256, uint256);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              interface IStargateReceiver {
                                  function sgReceive(
                                      uint16 _chainId,
                                      bytes memory _srcAddress,
                                      uint256 _nonce,
                                      address _token,
                                      uint256 amountLD,
                                      bytes memory payload
                                  ) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                      return msg.data;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract LPTokenERC20 {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  string public name;
                                  string public symbol;
                                  bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  // set in constructor
                                  bytes32 public DOMAIN_SEPARATOR;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  uint256 public decimals;
                                  uint256 public totalSupply;
                                  mapping(address => uint256) public balanceOf;
                                  mapping(address => mapping(address => uint256)) public allowance;
                                  mapping(address => uint256) public nonces;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  constructor(string memory _name, string memory _symbol) {
                                      name = _name;
                                      symbol = _symbol;
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      DOMAIN_SEPARATOR = keccak256(
                                          abi.encode(
                                              keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                              keccak256(bytes(name)),
                                              keccak256(bytes("1")),
                                              chainId,
                                              address(this)
                                          )
                                      );
                                  }
                                  function _mint(address to, uint256 value) internal {
                                      totalSupply = totalSupply.add(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(address(0), to, value);
                                  }
                                  function _burn(address from, uint256 value) internal {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      totalSupply = totalSupply.sub(value);
                                      emit Transfer(from, address(0), value);
                                  }
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) private {
                                      allowance[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                                  function approve(address spender, uint256 value) external returns (bool) {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  function transfer(address to, uint256 value) external returns (bool) {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) external returns (bool) {
                                      if (allowance[from][msg.sender] != uint256(-1)) {
                                          allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                      }
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
                                      return true;
                                  }
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "Bridge: EXPIRED");
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\\x19\\x01",
                                              DOMAIN_SEPARATOR,
                                              keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                          )
                                      );
                                      address recoveredAddress = ecrecover(digest, v, r, s);
                                      require(recoveredAddress != address(0) && recoveredAddress == owner, "Bridge: INVALID_SIGNATURE");
                                      _approve(owner, spender, value);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              import "../Pool.sol";
                              interface IStargateFeeLibrary {
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external returns (Pool.SwapObj memory s);
                                  function getVersion() external view returns (string memory);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroReceiver {
                                  // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                                  // @param _srcChainId - the source endpoint identifier
                                  // @param _srcAddress - the source sending contract address from the source chain
                                  // @param _nonce - the ordered message nonce
                                  // @param _payload - the signed payload is the UA bytes has encoded to be sent
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. ie: pay for a specified destination gasAmount, or receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              

                              File 11 of 16: Factory
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              contract Factory is Ownable {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  mapping(uint256 => Pool) public getPool; // poolId -> PoolInfo
                                  address[] public allPools;
                                  address public immutable router;
                                  address public defaultFeeLibrary; // address for retrieving fee params for swaps
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _router) {
                                      require(_router != address(0x0), "Stargate: _router cant be 0x0"); // 1 time only
                                      router = _router;
                                  }
                                  function setDefaultFeeLibrary(address _defaultFeeLibrary) external onlyOwner {
                                      require(_defaultFeeLibrary != address(0x0), "Stargate: fee library cant be 0x0");
                                      defaultFeeLibrary = _defaultFeeLibrary;
                                  }
                                  function allPoolsLength() external view returns (uint256) {
                                      return allPools.length;
                                  }
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) public onlyRouter returns (address poolAddress) {
                                      require(address(getPool[_poolId]) == address(0x0), "Stargate: Pool already created");
                                      Pool pool = new Pool(_poolId, router, _token, _sharedDecimals, _localDecimals, defaultFeeLibrary, _name, _symbol);
                                      getPool[_poolId] = pool;
                                      poolAddress = address(pool);
                                      allPools.push(poolAddress);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./LPTokenERC20.sol";
                              import "./interfaces/IStargateFeeLibrary.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              /// Pool contracts on other chains and managed by the Stargate protocol.
                              contract Pool is LPTokenERC20, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 public constant BP_DENOMINATOR = 10000;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct ChainPath {
                                      bool ready; // indicate if the counter chainPath has been created.
                                      uint16 dstChainId;
                                      uint256 dstPoolId;
                                      uint256 weight;
                                      uint256 balance;
                                      uint256 lkb;
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  struct SwapObj {
                                      uint256 amount;
                                      uint256 eqFee;
                                      uint256 eqReward;
                                      uint256 lpFee;
                                      uint256 protocolFee;
                                      uint256 lkbRemove;
                                  }
                                  struct CreditObj {
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // chainPath
                                  ChainPath[] public chainPaths; // list of connected chains with shared pools
                                  mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
                                  // metadata
                                  uint256 public immutable poolId; // shared id between chains to represent same pool
                                  uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
                                  uint256 public localDecimals; // the decimals for the token
                                  uint256 public immutable convertRate; // the decimals for the token
                                  address public immutable token; // the token for the pool
                                  address public immutable router; // the token for the pool
                                  bool public stopSwap; // flag to stop swapping in extreme cases
                                  // Fee and Liquidity
                                  uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
                                  uint256 public totalWeight; // total weight for pool percentages
                                  uint256 public mintFeeBP; // fee basis points for the mint/deposit
                                  uint256 public protocolFeeBalance; // fee balance created from dao fee
                                  uint256 public mintFeeBalance; // fee balance created from mint fee
                                  uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
                                  address public feeLibrary; // address for retrieving fee params for swaps
                                  // Delta related
                                  uint256 public deltaCredit; // credits accumulated from txn
                                  bool public batched; // flag to indicate if we want batch processing.
                                  bool public defaultSwapMode; // flag for the default mode for swap
                                  bool public defaultLPMode; // flag for the default mode for lp
                                  uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
                                  uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
                                  event Burn(address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
                                  event Swap(
                                      uint16 chainId,
                                      uint256 dstPoolId,
                                      address from,
                                      uint256 amountSD,
                                      uint256 eqReward,
                                      uint256 eqFee,
                                      uint256 protocolFee,
                                      uint256 lpFee
                                  );
                                  event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
                                  event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
                                  event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
                                  event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
                                  event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
                                  event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
                                  event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
                                  event FeesUpdated(uint256 mintFeeBP);
                                  event FeeLibraryUpdated(address feeLibraryAddr);
                                  event StopSwapUpdated(bool swapStop);
                                  event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
                                  event WithdrawMintFeeBalance(address to, uint256 amountSD);
                                  event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: only the router can call this method");
                                      _;
                                  }
                                  constructor(
                                      uint256 _poolId,
                                      address _router,
                                      address _token,
                                      uint256 _sharedDecimals,
                                      uint256 _localDecimals,
                                      address _feeLibrary,
                                      string memory _name,
                                      string memory _symbol
                                  ) LPTokenERC20(_name, _symbol) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      poolId = _poolId;
                                      router = _router;
                                      token = _token;
                                      sharedDecimals = _sharedDecimals;
                                      decimals = uint8(_sharedDecimals);
                                      localDecimals = _localDecimals;
                                      convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
                                      totalWeight = 0;
                                      feeLibrary = _feeLibrary;
                                      //delta algo related
                                      batched = false;
                                      defaultSwapMode = true;
                                      defaultLPMode = true;
                                  }
                                  function getChainPathsLength() public view returns (uint256) {
                                      return chainPaths.length;
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
                                      return _mintLocal(_to, _amountLD, true, true);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      bool newLiquidity
                                  ) external nonReentrant onlyRouter returns (SwapObj memory) {
                                      require(!stopSwap, "Stargate: swap func stopped");
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      uint256 amountSD = amountLDtoSD(_amountLD);
                                      uint256 minAmountSD = amountLDtoSD(_minAmountLD);
                                      // request fee params from library
                                      SwapObj memory s = IStargateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
                                      // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
                                      eqFeePool = eqFeePool.sub(s.eqReward);
                                      // update the new amount the user gets minus the fees
                                      s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
                                      // users will also get the eqReward
                                      require(s.amount.add(s.eqReward) >= minAmountSD, "Stargate: slippage too high");
                                      // behaviours
                                      //     - protocolFee: booked, stayed and withdrawn at remote.
                                      //     - eqFee: booked, stayed and withdrawn at remote.
                                      //     - lpFee: booked and stayed at remote, can be withdrawn anywhere
                                      s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
                                      // check for transfer solvency.
                                      require(cp.balance >= s.lkbRemove, "Stargate: dst balance too low");
                                      cp.balance = cp.balance.sub(s.lkbRemove);
                                      if (newLiquidity) {
                                          deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
                                      } else if (s.eqReward > 0) {
                                          deltaCredit = deltaCredit.add(s.eqReward);
                                      }
                                      // distribute credits on condition.
                                      if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultSwapMode);
                                      }
                                      emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
                                      return s;
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      cp.lkb = cp.lkb.add(cp.credits);
                                      c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
                                      c.credits = cp.credits;
                                      cp.credits = 0;
                                      emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemRemote   ->                        swapRemote
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLP
                                  ) external nonReentrant onlyRouter {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 amountSD = _burnLocal(_from, _amountLP);
                                      //run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
                                  }
                                  function instantRedeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      address _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 _deltaCredit = deltaCredit; // sload optimization.
                                      uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
                                      if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
                                      amountSD = _burnLocal(_from, _amountLP);
                                      deltaCredit = _deltaCredit.sub(amountSD);
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      bytes calldata _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      // safeguard.
                                      require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Stargate: counter chainPath is not ready");
                                      amountSD = _burnLocal(_from, _amountLP);
                                      // run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(false);
                                      }
                                      emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      CreditObj memory _c
                                  ) external nonReentrant onlyRouter {
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      cp.balance = cp.balance.add(_c.credits);
                                      if (cp.idealBalance != _c.idealBalance) {
                                          cp.idealBalance = _c.idealBalance;
                                      }
                                      emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      SwapObj memory _s
                                  ) external nonReentrant onlyRouter returns (uint256 amountLD) {
                                      // booking lpFee
                                      totalLiquidity = totalLiquidity.add(_s.lpFee);
                                      // booking eqFee
                                      eqFeePool = eqFeePool.add(_s.eqFee);
                                      // booking stargateFee
                                      protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
                                      // update LKB
                                      uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
                                      chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
                                      // user receives the amount + the srcReward
                                      amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
                                      _safeTransfer(token, _to, amountLD);
                                      emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _amountToMintSD
                                  ) external nonReentrant onlyRouter {
                                      if (_amountToMintSD > 0) {
                                          _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
                                      }
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      cp.lkb = cp.lkb.sub(_amountSD);
                                      uint256 amountLD = amountSDtoLD(_amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal(amount)   ->               redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      uint256 _amountSD
                                  ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      if (_amountSD > cp.balance) {
                                          mintAmount = _amountSD - cp.balance;
                                          swapAmount = cp.balance;
                                          cp.balance = 0;
                                      } else {
                                          cp.balance = cp.balance.sub(_amountSD);
                                          swapAmount = _amountSD;
                                          mintAmount = 0;
                                      }
                                      emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyRouter {
                                      for (uint256 i = 0; i < chainPaths.length; ++i) {
                                          ChainPath memory cp = chainPaths[i];
                                          bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
                                          require(!exists, "Stargate: cant createChainPath of existing dstChainId and _dstPoolId");
                                      }
                                      totalWeight = totalWeight.add(_weight);
                                      chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
                                      chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setWeightForChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      totalWeight = totalWeight.sub(cp.weight).add(_weight);
                                      cp.weight = _weight;
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setFee(uint256 _mintFeeBP) external onlyRouter {
                                      require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
                                      mintFeeBP = _mintFeeBP;
                                      emit FeesUpdated(mintFeeBP);
                                  }
                                  function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
                                      require(_feeLibraryAddr != address(0x0), "Stargate: fee library cant be 0x0");
                                      feeLibrary = _feeLibraryAddr;
                                      emit FeeLibraryUpdated(_feeLibraryAddr);
                                  }
                                  function setSwapStop(bool _swapStop) external onlyRouter {
                                      stopSwap = _swapStop;
                                      emit StopSwapUpdated(_swapStop);
                                  }
                                  function setDeltaParam(
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyRouter {
                                      require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Stargate: wrong Delta param");
                                      batched = _batched;
                                      swapDeltaBP = _swapDeltaBP;
                                      lpDeltaBP = _lpDeltaBP;
                                      defaultSwapMode = _defaultSwapMode;
                                      defaultLPMode = _defaultLPMode;
                                      emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(bool _fullMode) external onlyRouter {
                                      _delta(_fullMode);
                                  }
                                  function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == false, "Stargate: chainPath is already active");
                                      // this func will only be called once
                                      cp.ready = true;
                                  }
                                  function withdrawProtocolFeeBalance(address _to) external onlyRouter {
                                      if (protocolFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
                                          protocolFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawProtocolFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  function withdrawMintFeeBalance(address _to) external onlyRouter {
                                      if (mintFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
                                          mintFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawMintFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  // Conversion Helpers
                                  //---------------------------------------------------------------------------
                                  function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
                                      return amountSDtoLD(_amountLPtoSD(_amountLP));
                                  }
                                  function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant convert LPtoSD when totalSupply == 0");
                                      return _amountLP.mul(totalLiquidity).div(totalSupply);
                                  }
                                  function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
                                      require(totalLiquidity > 0, "Stargate: cant convert SDtoLP when totalLiq == 0");
                                      return _amountSD.mul(totalSupply).div(totalLiquidity);
                                  }
                                  function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.mul(convertRate);
                                  }
                                  function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.div(convertRate);
                                  }
                                  function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
                                      require(chainPaths.length > 0, "Stargate: no chainpaths exist");
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
                                      ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant burn when totalSupply == 0");
                                      uint256 amountOfLPTokens = balanceOf[_from];
                                      require(amountOfLPTokens >= _amountLP, "Stargate: not enough LP tokens to burn");
                                      uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
                                      //subtract totalLiquidity accordingly
                                      totalLiquidity = totalLiquidity.sub(amountSD);
                                      _burn(_from, _amountLP);
                                      emit Burn(_from, _amountLP, amountSD);
                                      return amountSD;
                                  }
                                  function _delta(bool fullMode) internal {
                                      if (deltaCredit > 0 && totalWeight > 0) {
                                          uint256 cpLength = chainPaths.length;
                                          uint256[] memory deficit = new uint256[](cpLength);
                                          uint256 totalDeficit = 0;
                                          // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
                                          for (uint256 i = 0; i < cpLength; ++i) {
                                              ChainPath storage cp = chainPaths[i];
                                              // (liquidity * (weight/totalWeight)) - (lkb+credits)
                                              uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
                                              uint256 currLiq = cp.lkb.add(cp.credits);
                                              if (balLiq > currLiq) {
                                                  // save gas since we know balLiq > currLiq and we know deficit[i] > 0
                                                  deficit[i] = balLiq - currLiq;
                                                  totalDeficit = totalDeficit.add(deficit[i]);
                                              }
                                          }
                                          // indicates how much delta credit is distributed
                                          uint256 spent;
                                          // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
                                          // run full Delta, allocate all credits
                                          if (totalDeficit == 0) {
                                              // only fullMode delta will allocate excess credits
                                              if (fullMode && deltaCredit > 0) {
                                                  // credit ChainPath by weights
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      // credits = credits + toBalanceChange + remaining allocation based on weight
                                                      uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
                                                      spent = spent.add(amtToCredit);
                                                      cp.credits = cp.credits.add(amtToCredit);
                                                  }
                                              } // else do nth
                                          } else if (totalDeficit <= deltaCredit) {
                                              if (fullMode) {
                                                  // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
                                                  uint256 excessCredit = deltaCredit - totalDeficit;
                                                  // algorithm steps 14-16: calculate credits
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          // credits = credits + deficit + remaining allocation based on weight
                                                          uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              } else {
                                                  // totalDeficit <= deltaCredit but not running fullMode
                                                  // credit chainPaths as is if any deficit, not using all deltaCredit
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          uint256 amtToCredit = deficit[i];
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              }
                                          } else {
                                              // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
                                              for (uint256 i = 0; i < cpLength; ++i) {
                                                  if (deficit[i] > 0) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
                                                      spent = spent.add(proportionalDeficit);
                                                      cp.credits = cp.credits.add(proportionalDeficit);
                                                  }
                                              }
                                          }
                                          // deduct the amount of credit sent
                                          deltaCredit = deltaCredit.sub(spent);
                                      }
                                  }
                                  function _mintLocal(
                                      address _to,
                                      uint256 _amountLD,
                                      bool _feesEnabled,
                                      bool _creditDelta
                                  ) internal returns (uint256 amountSD) {
                                      require(totalWeight > 0, "Stargate: No ChainPaths exist");
                                      amountSD = amountLDtoSD(_amountLD);
                                      uint256 mintFeeSD = 0;
                                      if (_feesEnabled) {
                                          mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
                                          amountSD = amountSD.sub(mintFeeSD);
                                          mintFeeBalance = mintFeeBalance.add(mintFeeSD);
                                      }
                                      if (_creditDelta) {
                                          deltaCredit = deltaCredit.add(amountSD);
                                      }
                                      uint256 amountLPTokens = amountSD;
                                      if (totalSupply != 0) {
                                          amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
                                      }
                                      totalLiquidity = totalLiquidity.add(amountSD);
                                      _mint(_to, amountLPTokens);
                                      emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
                                      // add to credits and call delta. short circuit to save gas
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                  }
                                  function _safeTransfer(
                                      address _token,
                                      address _to,
                                      uint256 _value
                                  ) private {
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
                                      require(success && (data.length == 0 || abi.decode(data, (bool))), "Stargate: TRANSFER_FAILED");
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      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.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract LPTokenERC20 {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  string public name;
                                  string public symbol;
                                  bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  // set in constructor
                                  bytes32 public DOMAIN_SEPARATOR;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  uint256 public decimals;
                                  uint256 public totalSupply;
                                  mapping(address => uint256) public balanceOf;
                                  mapping(address => mapping(address => uint256)) public allowance;
                                  mapping(address => uint256) public nonces;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  constructor(string memory _name, string memory _symbol) {
                                      name = _name;
                                      symbol = _symbol;
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      DOMAIN_SEPARATOR = keccak256(
                                          abi.encode(
                                              keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                              keccak256(bytes(name)),
                                              keccak256(bytes("1")),
                                              chainId,
                                              address(this)
                                          )
                                      );
                                  }
                                  function _mint(address to, uint256 value) internal {
                                      totalSupply = totalSupply.add(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(address(0), to, value);
                                  }
                                  function _burn(address from, uint256 value) internal {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      totalSupply = totalSupply.sub(value);
                                      emit Transfer(from, address(0), value);
                                  }
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) private {
                                      allowance[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                                  function approve(address spender, uint256 value) external returns (bool) {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  function transfer(address to, uint256 value) external returns (bool) {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) external returns (bool) {
                                      if (allowance[from][msg.sender] != uint256(-1)) {
                                          allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                      }
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
                                      return true;
                                  }
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "Bridge: EXPIRED");
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\\x19\\x01",
                                              DOMAIN_SEPARATOR,
                                              keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                          )
                                      );
                                      address recoveredAddress = ecrecover(digest, v, r, s);
                                      require(recoveredAddress != address(0) && recoveredAddress == owner, "Bridge: INVALID_SIGNATURE");
                                      _approve(owner, spender, value);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              import "../Pool.sol";
                              interface IStargateFeeLibrary {
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external returns (Pool.SwapObj memory s);
                                  function getVersion() external view returns (string memory);
                              }
                              

                              File 12 of 16: StargateFeeLibraryV07
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "../interfaces/IStargateFeeLibrary.sol";
                              import "../Pool.sol";
                              import "../Factory.sol";
                              import "../interfaces/IStargateLPStaking.sol";
                              import "../chainlink/interfaces/AggregatorV3Interface.sol";
                              import "../lzApp/LzApp.sol";
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              ///@notice Stargate fee library maintains the fees it costs to go from one pool to another across chains
                              /// The price feeds are eagerly updated by off-chain actors who watch the shouldCallUpdateTokenPrices() and call updateTokenPrices() if required
                              contract StargateFeeLibraryV07 is LzApp, IStargateFeeLibrary {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // equilibrium func params. all in BPs * 10 ^ 2, i.e. 1 % = 10 ^ 6 units
                                  uint256 public constant DENOMINATOR = 1e18;
                                  uint256 public constant DELTA_1 = 6000 * 1e14;
                                  uint256 public constant DELTA_2 = 500 * 1e14;
                                  uint256 public constant LAMBDA_1 = 40 * 1e14;
                                  uint256 public constant LAMBDA_2 = 9960 * 1e14;
                                  // fee/reward bps
                                  uint256 public constant LP_FEE = 1 * 1e14;
                                  uint256 public constant PROTOCOL_FEE = 9 * 1e14;
                                  uint256 public constant PROTOCOL_FEE_FOR_SAME_TOKEN = 5 * 1e14;
                                  uint256 public constant EQ_REWARD_THRESHOLD = 6 * 1e14;
                                  uint256 public constant PROTOCOL_SUBSIDY = 3 * 1e13;
                                  // price and state thresholds, may be configurable in the future
                                  uint8 public constant PRICE_SHARED_DECIMALS = 8; // for price normalization
                                  uint256 public constant ONE_BPS_PRICE_CHANGE_THRESHOLD = 1 * 1e14;
                                  uint256 public constant PRICE_DRIFT_THRESHOLD = 10 * 1e14; // 10 bps
                                  uint256 public constant PRICE_DEPEG_THRESHOLD = 150 * 1e14; // 150 bps
                                  mapping(address => bool) public whitelist;
                                  mapping(uint256 => uint256) public poolIdToLpId; // poolId -> index of the pool in the lpStaking contract
                                  Factory public immutable factory;
                                  mapping(uint256 => address) public poolIdToPriceFeed; // poolId -> priceFeed
                                  // poolId1 -> poolId2 -> remoteChainIds, poolId1 < poolId2
                                  mapping(uint256 => mapping(uint256 => uint16[])) internal poolPairToRemoteChainIds;
                                  mapping(uint256 => uint256) public poolIdToPriceSD; // poolId -> price in shared decimals
                                  mapping(uint16 => bytes) public defaultAdapterParams; // for price sync, chainId -> params
                                  mapping(uint256 => address) public stargatePoolIdToLPStaking;
                                  enum PriceDeviationState {
                                      Normal,
                                      Drift,
                                      Depeg
                                  }
                                  event PriceUpdated(uint256 indexed poolId, uint256 priceSD);
                                  modifier notSamePool(uint256 _poolId1, uint256 _poolId2) {
                                      require(_poolId1 != _poolId2, "FeeLibrary: _poolId1 == _poolId2");
                                      _;
                                  }
                                  constructor(
                                      address _factory,
                                      address _endpoint
                                  ) LzApp(_endpoint) {
                                      require(_factory != address(0x0), "FeeLibrary: Factory cannot be 0x0");
                                      require(_endpoint != address(0x0), "FeeLibrary: Endpoint cannot be 0x0");
                                      factory = Factory(_factory);
                                  }
                                  // --------------------- ONLY OWNER ---------------------
                                  function whiteList(address _from, bool _whiteListed) external onlyOwner {
                                      whitelist[_from] = _whiteListed;
                                  }
                                  function setPoolToLpId(uint256 _poolId, uint256 _lpId) external onlyOwner {
                                      poolIdToLpId[_poolId] = _lpId;
                                  }
                                  // for those chains where to get the price from oracle and sync to other chains
                                  function setTokenPriceFeed(uint256 _poolId, address _priceFeedAddress) external onlyOwner {
                                      poolIdToPriceFeed[_poolId] = _priceFeedAddress;
                                  }
                                  function setStargatePoolIdToLPStakingAddress(uint256 _poolId, address _lpStaking) external onlyOwner {
                                      stargatePoolIdToLPStaking[_poolId] = _lpStaking;
                                  }
                                  function initTokenPrice(uint256 _poolId, uint256 _priceSD) external onlyOwner {
                                      poolIdToPriceSD[_poolId] = _priceSD;
                                      emit PriceUpdated(_poolId, _priceSD);
                                  }
                                  function setRemoteChains(
                                      uint256 _poolId1,
                                      uint256 _poolId2,
                                      uint16[] calldata _remoteChainIds
                                  ) external onlyOwner notSamePool(_poolId1, _poolId2) {
                                      if (_poolId1 < _poolId2) {
                                          poolPairToRemoteChainIds[_poolId1][_poolId2] = _remoteChainIds;
                                      } else {
                                          poolPairToRemoteChainIds[_poolId2][_poolId1] = _remoteChainIds;
                                      }
                                  }
                                  function setDefaultAdapterParams(uint16 _remoteChainId, bytes calldata _adapterParams) external onlyOwner {
                                      defaultAdapterParams[_remoteChainId] = _adapterParams;
                                  }
                                  // Override the renounce ownership inherited by zeppelin ownable
                                  function renounceOwnership() public override onlyOwner {}
                                  // --------------------- PUBLIC FUNCTIONS ---------------------
                                  ///@notice update the stored token price pair for the associated pool pair
                                  ///@dev anyone can update and sync price at any time even though the price is not changed
                                  ///@param _poolId1 one pool id of the pool pair
                                  ///@param _poolId2 the other pool id of the pool pair
                                  function updateTokenPrices(uint256 _poolId1, uint256 _poolId2) external payable notSamePool(_poolId1, _poolId2) {
                                      // get new prices from price feed
                                      uint256 newPrice1 = _getLatestPriceSDFromPriceFeed(_poolId1);
                                      uint256 newPrice2 = _getLatestPriceSDFromPriceFeed(_poolId2);
                                      // store the new prices
                                      poolIdToPriceSD[_poolId1] = newPrice1;
                                      poolIdToPriceSD[_poolId2] = newPrice2;
                                      emit PriceUpdated(_poolId1, newPrice1);
                                      emit PriceUpdated(_poolId2, newPrice2);
                                      // sync the prices to remote pools
                                      uint16[] memory remoteChainIds = getRemoteChains(_poolId1, _poolId2);
                                      require(remoteChainIds.length > 0, "FeeLibrary: invalid pool pair");
                                      bytes memory payload = abi.encode(_poolId1, newPrice1, _poolId2, newPrice2);
                                      for (uint256 i = 0; i < remoteChainIds.length; i++) {
                                          uint16 remoteChainId = remoteChainIds[i];
                                          address refundAddress = i == remoteChainIds.length - 1? msg.sender : address(this); // refund to msg.sender only for the last call
                                          _lzSend(remoteChainId, payload, payable(refundAddress), address(0), defaultAdapterParams[remoteChainId], address(this).balance);
                                      }
                                  }
                                  // --------------------- VIEW FUNCTIONS ---------------------
                                  ///@notice get the fees for a swap. typically called from the router via the pool
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external view override returns (Pool.SwapObj memory s) {
                                      // calculate the equilibrium reward
                                      bool whitelisted = whitelist[_from];
                                      s.eqReward = getEqReward(_srcPoolId, _amountSD, whitelisted); // protocol fee is 0 if whitelisted
                                      // calculate the equilibrium fee
                                      bool hasEqReward = s.eqReward > 0;
                                      uint256 protocolSubsidy;
                                      (s.eqFee, protocolSubsidy) = getEquilibriumFee(_srcPoolId, _dstPoolId, _dstChainId, _amountSD, whitelisted, hasEqReward);
                                      // calculate protocol and lp fee
                                      (s.protocolFee, s.lpFee) = getProtocolAndLpFee(_srcPoolId, _dstPoolId, _dstChainId, _amountSD, protocolSubsidy, whitelisted);
                                      // cap the reward at the sum of protocol fee and lp fee by increasing the protocol fee
                                      if (!whitelisted) {
                                          uint256 rewardCap = s.protocolFee.add(s.lpFee);
                                          if (s.eqReward > rewardCap) {
                                              uint256 diff = s.eqReward.sub(rewardCap);
                                              s.protocolFee = s.protocolFee.add(diff);
                                          }
                                      }
                                      // calculate drift fee
                                      uint256 driftFee = getDriftFee(_srcPoolId, _dstPoolId, _amountSD, whitelisted);
                                      s.protocolFee = s.protocolFee.add(driftFee);
                                      if (_amountSD < s.lpFee.add(s.eqFee).add(s.protocolFee)) {
                                          s.protocolFee = _amountSD.sub(s.lpFee).sub(s.eqFee);
                                      }
                                      return s;
                                  }
                                  ///@notice quote fee for price update and sync to remote chains
                                  ///@dev call this for value to attach to call to update token prices
                                  function quoteFeeForPriceUpdate(uint256 _poolId1, uint256 _poolId2) external view notSamePool(_poolId1, _poolId2) returns (uint256) {
                                      uint256 total = 0;
                                      uint16[] memory remoteChainIds = getRemoteChains(_poolId1, _poolId2);
                                      require(remoteChainIds.length > 0, "FeeLibrary: invalid pool pair");
                                      bytes memory payload = abi.encode(_poolId1, uint256(0), _poolId2, uint256(0)); // mock the payload
                                      for (uint256 i = 0; i < remoteChainIds.length; i++) {
                                          uint16 remoteChainId = remoteChainIds[i];
                                          (uint256 fee, ) = lzEndpoint.estimateFees(remoteChainId, address(this), payload, false, defaultAdapterParams[remoteChainId]);
                                          total = total.add(fee);
                                      }
                                      return total;
                                  }
                                  ///@notice function to check if update token prices should be called
                                  ///@dev typically called by an off-chain watcher and if returns true updateTokenPrices is called
                                  ///@param _poolId1 one pool id of the pool pair
                                  ///@param _poolId2 the other pool id of the pool pair
                                  ///@return bool true if updateTokenPrice should be called, false otherwise
                                  function shouldCallUpdateTokenPrices(uint256 _poolId1, uint256 _poolId2) external view notSamePool(_poolId1, _poolId2) returns (bool) {
                                      // current price and state
                                      uint256 currentPriceSD1 = poolIdToPriceSD[_poolId1];
                                      uint256 currentPriceSD2 = poolIdToPriceSD[_poolId2];
                                      (PriceDeviationState currentState, uint256 currentDiff, bool currentLt) = _getPriceDiffAndDeviationState(currentPriceSD1, currentPriceSD2);
                                      // new price and state
                                      uint256 newPriceSD1 = _getLatestPriceSDFromPriceFeed(_poolId1);
                                      uint256 newPriceSD2 = _getLatestPriceSDFromPriceFeed(_poolId2);
                                      (PriceDeviationState newState, uint256 newDiff, bool newLt) = _getPriceDiffAndDeviationState(newPriceSD1, newPriceSD2);
                                      // if state has changed then price update is required
                                      if (currentState != newState) {
                                          return true;
                                      }
                                      // 1. if state keeps normal, then no need to update
                                      // 2. if state is drift or depeg, but the token with higher price has changed, then update is required
                                      // 3. if state is depeg and the token with higher price has not changed, then no need to update
                                      if (newState == PriceDeviationState.Normal) {
                                          return false;
                                      } else if (currentLt != newLt) {
                                          return true;
                                      } else if (newState == PriceDeviationState.Depeg) {
                                          return false;
                                      }
                                      // if state is drift and the difference is not less than 1bps, then update is required
                                      uint256 diffDelta = newDiff > currentDiff ? newDiff.sub(currentDiff) : currentDiff.sub(newDiff);
                                      return diffDelta >= ONE_BPS_PRICE_CHANGE_THRESHOLD;
                                  }
                                  function getEqReward(
                                      uint256 _srcPoolId,
                                      uint256 _amountSD,
                                      bool _whitelisted
                                  ) public view returns (uint256) {
                                      Pool pool = factory.getPool(_srcPoolId);
                                      uint256 currentAssetSD = _getPoolBalanceSD(pool);
                                      uint256 lpAsset = pool.totalLiquidity();
                                      uint256 rewardPoolSize = pool.eqFeePool();
                                      if (lpAsset <= currentAssetSD) {
                                          return 0;
                                      }
                                      uint256 poolDeficit = lpAsset.sub(currentAssetSD);
                                      uint256 rate = rewardPoolSize.mul(DENOMINATOR).div(poolDeficit);
                                      if (rate <= EQ_REWARD_THRESHOLD && !_whitelisted) {
                                          return 0;
                                      }
                                      uint256 eqReward = _amountSD.mul(rate).div(DENOMINATOR);
                                      eqReward = eqReward > rewardPoolSize ? rewardPoolSize : eqReward;
                                      return eqReward;
                                  }
                                  function getEquilibriumFee(
                                      uint256 srcPoolId,
                                      uint256 dstPoolId,
                                      uint16 dstChainId,
                                      uint256 amountSD,
                                      bool whitelisted,
                                      bool hasEqReward
                                  ) public view returns (uint256, uint256) {
                                      if (whitelisted) {
                                          return (0, 0);
                                      }
                                      Pool.ChainPath memory chainPath = factory.getPool(srcPoolId).getChainPath(dstChainId, dstPoolId);
                                      uint256 idealBalance = chainPath.idealBalance;
                                      uint256 beforeBalance = chainPath.balance;
                                      require(beforeBalance >= amountSD, "FeeLibrary: not enough balance");
                                      uint256 afterBalance = beforeBalance.sub(amountSD);
                                      uint256 safeZoneMax = idealBalance.mul(DELTA_1).div(DENOMINATOR);
                                      uint256 safeZoneMin = idealBalance.mul(DELTA_2).div(DENOMINATOR);
                                      uint256 eqFee = 0;
                                      uint256 protocolSubsidy = 0;
                                      uint256 amountSD_ = amountSD; // stack too deep
                                      if (afterBalance >= safeZoneMax) {
                                          // no fee zone, protocol subsidize it.
                                          eqFee = amountSD_.mul(PROTOCOL_SUBSIDY).div(DENOMINATOR);
                                          // no subsidy if has eqReward
                                          if (!hasEqReward) {
                                              protocolSubsidy = eqFee;
                                          }
                                      } else if (afterBalance >= safeZoneMin) {
                                          // safe zone
                                          uint256 proxyBeforeBalance = beforeBalance < safeZoneMax ? beforeBalance : safeZoneMax;
                                          eqFee = _getTrapezoidArea(LAMBDA_1, 0, safeZoneMax, safeZoneMin, proxyBeforeBalance, afterBalance);
                                      } else {
                                          // danger zone
                                          if (beforeBalance >= safeZoneMin) {
                                              // across 2 or 3 zones
                                              // part 1
                                              uint256 proxyBeforeBalance = beforeBalance < safeZoneMax ? beforeBalance : safeZoneMax;
                                              eqFee = eqFee.add(_getTrapezoidArea(LAMBDA_1, 0, safeZoneMax, safeZoneMin, proxyBeforeBalance, safeZoneMin));
                                              // part 2
                                              eqFee = eqFee.add(_getTrapezoidArea(LAMBDA_2, LAMBDA_1, safeZoneMin, 0, safeZoneMin, afterBalance));
                                          } else {
                                              // only in danger zone
                                              // part 2 only
                                              uint256 beforeBalance_ = beforeBalance; // Stack too deep
                                              eqFee = eqFee.add(_getTrapezoidArea(LAMBDA_2, LAMBDA_1, safeZoneMin, 0, beforeBalance_, afterBalance));
                                          }
                                      }
                                      return (eqFee, protocolSubsidy);
                                  }
                                  function getProtocolAndLpFee(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16, // _dstChainId
                                      uint256 _amountSD,
                                      uint256 _protocolSubsidy,
                                      bool _whitelisted
                                  ) public view returns (uint256, uint256) {
                                      if (_whitelisted) {
                                          return (0, 0);
                                      }
                                      uint256 protocolFeeBps = _srcPoolId == _dstPoolId ? PROTOCOL_FEE_FOR_SAME_TOKEN : PROTOCOL_FEE;
                                      uint256 amountSD = _amountSD; // Stack too deep
                                      uint256 srcPoolId = _srcPoolId;
                                      uint256 protocolFee = amountSD.mul(protocolFeeBps).div(DENOMINATOR).sub(_protocolSubsidy);
                                      uint256 lpFee = amountSD.mul(LP_FEE).div(DENOMINATOR);
                                      // when there are active emissions, give the lp fee to the protocol
                                      // lookup LPStaking[Time] address. If it
                                      address lpStakingAddr = stargatePoolIdToLPStaking[srcPoolId];
                                      if(lpStakingAddr != address(0x0)){
                                          IStargateLPStaking lpStaking = IStargateLPStaking(lpStakingAddr);
                                          (, uint256 allocPoint, , ) = lpStaking.poolInfo(poolIdToLpId[srcPoolId]);
                                          if (allocPoint > 0) {
                                              protocolFee = protocolFee.add(lpFee);
                                              lpFee = 0;
                                          }
                                      }
                                      return (protocolFee, lpFee);
                                  }
                                  function getDriftFee(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint256 _amountSD,
                                      bool _whitelisted
                                  ) public view returns (uint256) {
                                      if (_srcPoolId == _dstPoolId) {
                                          return 0;
                                      }
                                      // get current prices and state
                                      uint256 srcPriceSD = poolIdToPriceSD[_srcPoolId];
                                      uint256 dstPriceSD = poolIdToPriceSD[_dstPoolId];
                                      (PriceDeviationState state, , bool lt) = _getPriceDiffAndDeviationState(srcPriceSD, dstPriceSD);
                                      // there is no drift fee if
                                      // 1. state is normal
                                      // 2. swap from high price to low price
                                      if (!lt || state == PriceDeviationState.Normal) {
                                          return 0;
                                      }
                                      require(state != PriceDeviationState.Depeg, "FeeLibrary: _srcPoolId depeg");
                                      // if whitelisted, then no drift fee
                                      if (_whitelisted) {
                                          return 0;
                                      }
                                      uint256 amountSDAfterFee = _amountSD.mul(srcPriceSD).div(dstPriceSD);
                                      return _amountSD.sub(amountSDAfterFee);
                                  }
                                  function getRemoteChains(uint256 _poolId1, uint256 _poolId2) public view returns (uint16[] memory) {
                                      if (_poolId1 < _poolId2) {
                                          return poolPairToRemoteChainIds[_poolId1][_poolId2];
                                      } else {
                                          return poolPairToRemoteChainIds[_poolId2][_poolId1];
                                      }
                                  }
                                  function getVersion() external pure override returns (string memory) {
                                      return "7.1.0";
                                  }
                                  // --------------------- INTERNAL FUNCTIONS ---------------------
                                  function _getTrapezoidArea(
                                      uint256 lambda,
                                      uint256 yOffset,
                                      uint256 xUpperBound,
                                      uint256 xLowerBound,
                                      uint256 xStart,
                                      uint256 xEnd
                                  ) internal pure returns (uint256) {
                                      require(xEnd >= xLowerBound && xStart <= xUpperBound, "FeeLibrary: balance out of bound");
                                      uint256 xBoundWidth = xUpperBound.sub(xLowerBound);
                                      // xStartDrift = xUpperBound.sub(xStart);
                                      uint256 yStart = xUpperBound.sub(xStart).mul(lambda).div(xBoundWidth).add(yOffset);
                                      // xEndDrift = xUpperBound.sub(xEnd)
                                      uint256 yEnd = xUpperBound.sub(xEnd).mul(lambda).div(xBoundWidth).add(yOffset);
                                      // compute the area
                                      uint256 deltaX = xStart.sub(xEnd);
                                      return yStart.add(yEnd).mul(deltaX).div(2).div(DENOMINATOR);
                                  }
                                  function _blockingLzReceive(uint16, bytes memory, uint64, bytes memory _payload) internal override {
                                      (uint256 poolId1, uint256 priceSD1, uint256 poolId2, uint256 priceSD2) = abi.decode(_payload, (uint256, uint256, uint256, uint256));
                                      poolIdToPriceSD[poolId1] = priceSD1;
                                      poolIdToPriceSD[poolId2] = priceSD2;
                                      emit PriceUpdated(poolId1, priceSD1);
                                      emit PriceUpdated(poolId2, priceSD2);
                                  }
                                  ///@notice does an external call to the price feed address supplied and returns the scaled price
                                  function _getLatestPriceSDFromPriceFeed(uint256 _poolId) internal view returns (uint256) {
                                      address priceFeed = poolIdToPriceFeed[_poolId];
                                      require(priceFeed != address(0x0), "FeeLibrary: price feed not set");
                                      uint8 decimals = AggregatorV3Interface(priceFeed).decimals();
                                      (, int256 price, , ,) = AggregatorV3Interface(priceFeed).latestRoundData();
                                      require(price >= 0, "FeeLibrary: price is negative");
                                      return _scalePrice(uint256(price), decimals);
                                  }
                                  ///@notice looks at the two prices and determines if the state of the pair is normal, depeg or drift
                                  function _getPriceDiffAndDeviationState(uint256 _priceSD1, uint256 _priceSD2) internal pure returns (PriceDeviationState, uint256, bool) {
                                      // get absolute difference between the two prices
                                      (uint256 diff, bool lt) = _getAbsoluteDiffAsBps(_priceSD1, _priceSD2);
                                      PriceDeviationState state;
                                      if (diff <= PRICE_DRIFT_THRESHOLD) {
                                          state = PriceDeviationState.Normal;
                                      } else if (diff >= PRICE_DEPEG_THRESHOLD) {
                                          state = PriceDeviationState.Depeg;
                                      } else {
                                          state = PriceDeviationState.Drift;
                                      }
                                      return (state, diff, lt);
                                  }
                                  function _scalePrice(uint256 _price, uint8 _decimals) internal pure returns (uint256) {
                                      if (_decimals == PRICE_SHARED_DECIMALS) {
                                          return _price;
                                      }
                                      uint256 rate = _scaleRate(_decimals, PRICE_SHARED_DECIMALS);
                                      return _decimals < PRICE_SHARED_DECIMALS ? _price.mul(rate) : _price.div(rate);
                                  }
                                  /// @notice returns the absolute difference between two numbers as bps
                                  /// @return the absolute difference between two numbers as bps
                                  /// @return true if _a < _b, false otherwise
                                  function _getAbsoluteDiffAsBps(uint256 _a, uint256 _b) internal pure returns (uint256, bool) {
                                      if (_a > _b) {
                                          return (_a.sub(_b).mul(DENOMINATOR).div(_a), false);
                                      } else if (_a == _b) {
                                          return (0, false);
                                      } else {
                                          return (_b.sub(_a).mul(DENOMINATOR).div(_b), true);
                                      }
                                  }
                                  function _scaleRate(uint8 _decimals, uint8 _sharedDecimals) internal pure returns (uint256) {
                                      uint256 diff = _decimals > _sharedDecimals? _decimals - _sharedDecimals : _sharedDecimals - _decimals;
                                      require(diff <= 20, "FeeLibrary: diff of decimals is too large");
                                      return 10 ** diff;
                                  }
                                  function _getPoolBalanceSD(Pool _pool) internal view returns (uint256) {
                                      return IERC20(_pool.token()).balanceOf(address(_pool)).div(_pool.convertRate());
                                  }
                                  receive() external payable {} // receive ETH from lz endpoint
                              }// SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      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.7.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: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroReceiver {
                                  // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                                  // @param _srcChainId - the source endpoint identifier
                                  // @param _srcAddress - the source sending contract address from the source chain
                                  // @param _nonce - the ordered message nonce
                                  // @param _payload - the signed payload is the UA bytes has encoded to be sent
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Contract module that helps prevent reentrant calls to a function.
                               *
                               * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
                               * available, which can be applied to functions to make sure there are no nested
                               * (reentrant) calls to them.
                               *
                               * Note that because there is a single `nonReentrant` guard, functions marked as
                               * `nonReentrant` may not call one another. This can be worked around by making
                               * those functions `private`, and then adding `external` `nonReentrant` entry
                               * points to them.
                               *
                               * TIP: If you would like to learn more about reentrancy and alternative ways
                               * to protect against it, check out our blog post
                               * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
                               */
                              abstract contract ReentrancyGuard {
                                  // Booleans are more expensive than uint256 or any type that takes up a full
                                  // word because each write operation emits an extra SLOAD to first read the
                                  // slot's contents, replace the bits taken up by the boolean, and then write
                                  // back. This is the compiler's defense against contract upgrades and
                                  // pointer aliasing, and it cannot be disabled.
                                  // The values being non-zero value makes deployment a bit more expensive,
                                  // but in exchange the refund on every call to nonReentrant will be lower in
                                  // amount. Since refunds are capped to a percentage of the total
                                  // transaction's gas, it is best to keep them low in cases like this one, to
                                  // increase the likelihood of the full refund coming into effect.
                                  uint256 private constant _NOT_ENTERED = 1;
                                  uint256 private constant _ENTERED = 2;
                                  uint256 private _status;
                                  constructor () {
                                      _status = _NOT_ENTERED;
                                  }
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Calling a `nonReentrant` function from another `nonReentrant`
                                   * function is not supported. It is possible to prevent this from happening
                                   * by making the `nonReentrant` function external, and make it call a
                                   * `private` function that does the actual work.
                                   */
                                  modifier nonReentrant() {
                                      // On the first call to nonReentrant, _notEntered will be true
                                      require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                                      // Any calls to nonReentrant after this point will fail
                                      _status = _ENTERED;
                                      _;
                                      // By storing the original value once again, a refund is triggered (see
                                      // https://eips.ethereum.org/EIPS/eip-2200)
                                      _status = _NOT_ENTERED;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              contract LPTokenERC20 {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  string public name;
                                  string public symbol;
                                  bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  // set in constructor
                                  bytes32 public DOMAIN_SEPARATOR;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  uint256 public decimals;
                                  uint256 public totalSupply;
                                  mapping(address => uint256) public balanceOf;
                                  mapping(address => mapping(address => uint256)) public allowance;
                                  mapping(address => uint256) public nonces;
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  constructor(string memory _name, string memory _symbol) {
                                      name = _name;
                                      symbol = _symbol;
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      DOMAIN_SEPARATOR = keccak256(
                                          abi.encode(
                                              keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                              keccak256(bytes(name)),
                                              keccak256(bytes("1")),
                                              chainId,
                                              address(this)
                                          )
                                      );
                                  }
                                  function _mint(address to, uint256 value) internal {
                                      totalSupply = totalSupply.add(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(address(0), to, value);
                                  }
                                  function _burn(address from, uint256 value) internal {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      totalSupply = totalSupply.sub(value);
                                      emit Transfer(from, address(0), value);
                                  }
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) private {
                                      allowance[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) private {
                                      balanceOf[from] = balanceOf[from].sub(value);
                                      balanceOf[to] = balanceOf[to].add(value);
                                      emit Transfer(from, to, value);
                                  }
                                  function approve(address spender, uint256 value) external returns (bool) {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  function transfer(address to, uint256 value) external returns (bool) {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) external returns (bool) {
                                      if (allowance[from][msg.sender] != uint256(-1)) {
                                          allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                                      }
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].add(addedValue));
                                      return true;
                                  }
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      _approve(msg.sender, spender, allowance[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "Bridge: EXPIRED");
                                      bytes32 digest = keccak256(
                                          abi.encodePacked(
                                              "\\x19\\x01",
                                              DOMAIN_SEPARATOR,
                                              keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                          )
                                      );
                                      address recoveredAddress = ecrecover(digest, v, r, s);
                                      require(recoveredAddress != address(0) && recoveredAddress == owner, "Bridge: INVALID_SIGNATURE");
                                      _approve(owner, spender, value);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              import "../Pool.sol";
                              interface IStargateFeeLibrary {
                                  function getFees(
                                      uint256 _srcPoolId,
                                      uint256 _dstPoolId,
                                      uint16 _dstChainId,
                                      address _from,
                                      uint256 _amountSD
                                  ) external returns (Pool.SwapObj memory s);
                                  function getVersion() external view returns (string memory);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              // imports
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
                              import "./LPTokenERC20.sol";
                              import "./interfaces/IStargateFeeLibrary.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              /// Pool contracts on other chains and managed by the Stargate protocol.
                              contract Pool is LPTokenERC20, ReentrancyGuard {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // CONSTANTS
                                  bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                                  uint256 public constant BP_DENOMINATOR = 10000;
                                  //---------------------------------------------------------------------------
                                  // STRUCTS
                                  struct ChainPath {
                                      bool ready; // indicate if the counter chainPath has been created.
                                      uint16 dstChainId;
                                      uint256 dstPoolId;
                                      uint256 weight;
                                      uint256 balance;
                                      uint256 lkb;
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  struct SwapObj {
                                      uint256 amount;
                                      uint256 eqFee;
                                      uint256 eqReward;
                                      uint256 lpFee;
                                      uint256 protocolFee;
                                      uint256 lkbRemove;
                                  }
                                  struct CreditObj {
                                      uint256 credits;
                                      uint256 idealBalance;
                                  }
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  // chainPath
                                  ChainPath[] public chainPaths; // list of connected chains with shared pools
                                  mapping(uint16 => mapping(uint256 => uint256)) public chainPathIndexLookup; // lookup for chainPath by chainId => poolId =>index
                                  // metadata
                                  uint256 public immutable poolId; // shared id between chains to represent same pool
                                  uint256 public sharedDecimals; // the shared decimals (lowest common decimals between chains)
                                  uint256 public localDecimals; // the decimals for the token
                                  uint256 public immutable convertRate; // the decimals for the token
                                  address public immutable token; // the token for the pool
                                  address public immutable router; // the token for the pool
                                  bool public stopSwap; // flag to stop swapping in extreme cases
                                  // Fee and Liquidity
                                  uint256 public totalLiquidity; // the total amount of tokens added on this side of the chain (fees + deposits - withdrawals)
                                  uint256 public totalWeight; // total weight for pool percentages
                                  uint256 public mintFeeBP; // fee basis points for the mint/deposit
                                  uint256 public protocolFeeBalance; // fee balance created from dao fee
                                  uint256 public mintFeeBalance; // fee balance created from mint fee
                                  uint256 public eqFeePool; // pool rewards in Shared Decimal format. indicate the total budget for reverse swap incentive
                                  address public feeLibrary; // address for retrieving fee params for swaps
                                  // Delta related
                                  uint256 public deltaCredit; // credits accumulated from txn
                                  bool public batched; // flag to indicate if we want batch processing.
                                  bool public defaultSwapMode; // flag for the default mode for swap
                                  bool public defaultLPMode; // flag for the default mode for lp
                                  uint256 public swapDeltaBP; // basis points of poolCredits to activate Delta in swap
                                  uint256 public lpDeltaBP; // basis points of poolCredits to activate Delta in liquidity events
                                  //---------------------------------------------------------------------------
                                  // EVENTS
                                  event Mint(address to, uint256 amountLP, uint256 amountSD, uint256 mintFeeAmountSD);
                                  event Burn(address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocalCallback(address _to, uint256 _amountSD, uint256 _amountToMintSD);
                                  event Swap(
                                      uint16 chainId,
                                      uint256 dstPoolId,
                                      address from,
                                      uint256 amountSD,
                                      uint256 eqReward,
                                      uint256 eqFee,
                                      uint256 protocolFee,
                                      uint256 lpFee
                                  );
                                  event SendCredits(uint16 dstChainId, uint256 dstPoolId, uint256 credits, uint256 idealBalance);
                                  event RedeemRemote(uint16 chainId, uint256 dstPoolId, address from, uint256 amountLP, uint256 amountSD);
                                  event RedeemLocal(address from, uint256 amountLP, uint256 amountSD, uint16 chainId, uint256 dstPoolId, bytes to);
                                  event InstantRedeemLocal(address from, uint256 amountLP, uint256 amountSD, address to);
                                  event CreditChainPath(uint16 chainId, uint256 srcPoolId, uint256 amountSD, uint256 idealBalance);
                                  event SwapRemote(address to, uint256 amountSD, uint256 protocolFee, uint256 dstFee);
                                  event WithdrawRemote(uint16 srcChainId, uint256 srcPoolId, uint256 swapAmount, uint256 mintAmount);
                                  event ChainPathUpdate(uint16 dstChainId, uint256 dstPoolId, uint256 weight);
                                  event FeesUpdated(uint256 mintFeeBP);
                                  event FeeLibraryUpdated(address feeLibraryAddr);
                                  event StopSwapUpdated(bool swapStop);
                                  event WithdrawProtocolFeeBalance(address to, uint256 amountSD);
                                  event WithdrawMintFeeBalance(address to, uint256 amountSD);
                                  event DeltaParamUpdated(bool batched, uint256 swapDeltaBP, uint256 lpDeltaBP, bool defaultSwapMode, bool defaultLPMode);
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: only the router can call this method");
                                      _;
                                  }
                                  constructor(
                                      uint256 _poolId,
                                      address _router,
                                      address _token,
                                      uint256 _sharedDecimals,
                                      uint256 _localDecimals,
                                      address _feeLibrary,
                                      string memory _name,
                                      string memory _symbol
                                  ) LPTokenERC20(_name, _symbol) {
                                      require(_token != address(0x0), "Stargate: _token cannot be 0x0");
                                      require(_router != address(0x0), "Stargate: _router cannot be 0x0");
                                      poolId = _poolId;
                                      router = _router;
                                      token = _token;
                                      sharedDecimals = _sharedDecimals;
                                      decimals = uint8(_sharedDecimals);
                                      localDecimals = _localDecimals;
                                      convertRate = 10**(uint256(localDecimals).sub(sharedDecimals));
                                      totalWeight = 0;
                                      feeLibrary = _feeLibrary;
                                      //delta algo related
                                      batched = false;
                                      defaultSwapMode = true;
                                      defaultLPMode = true;
                                  }
                                  function getChainPathsLength() public view returns (uint256) {
                                      return chainPaths.length;
                                  }
                                  //---------------------------------------------------------------------------
                                  // LOCAL CHAIN FUNCTIONS
                                  function mint(address _to, uint256 _amountLD) external nonReentrant onlyRouter returns (uint256) {
                                      return _mintLocal(_to, _amountLD, true, true);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swap(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLD,
                                      uint256 _minAmountLD,
                                      bool newLiquidity
                                  ) external nonReentrant onlyRouter returns (SwapObj memory) {
                                      require(!stopSwap, "Stargate: swap func stopped");
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      uint256 amountSD = amountLDtoSD(_amountLD);
                                      uint256 minAmountSD = amountLDtoSD(_minAmountLD);
                                      // request fee params from library
                                      SwapObj memory s = IStargateFeeLibrary(feeLibrary).getFees(poolId, _dstPoolId, _dstChainId, _from, amountSD);
                                      // equilibrium fee and reward. note eqFee/eqReward are separated from swap liquidity
                                      eqFeePool = eqFeePool.sub(s.eqReward);
                                      // update the new amount the user gets minus the fees
                                      s.amount = amountSD.sub(s.eqFee).sub(s.protocolFee).sub(s.lpFee);
                                      // users will also get the eqReward
                                      require(s.amount.add(s.eqReward) >= minAmountSD, "Stargate: slippage too high");
                                      // behaviours
                                      //     - protocolFee: booked, stayed and withdrawn at remote.
                                      //     - eqFee: booked, stayed and withdrawn at remote.
                                      //     - lpFee: booked and stayed at remote, can be withdrawn anywhere
                                      s.lkbRemove = amountSD.sub(s.lpFee).add(s.eqReward);
                                      // check for transfer solvency.
                                      require(cp.balance >= s.lkbRemove, "Stargate: dst balance too low");
                                      cp.balance = cp.balance.sub(s.lkbRemove);
                                      if (newLiquidity) {
                                          deltaCredit = deltaCredit.add(amountSD).add(s.eqReward);
                                      } else if (s.eqReward > 0) {
                                          deltaCredit = deltaCredit.add(s.eqReward);
                                      }
                                      // distribute credits on condition.
                                      if (!batched || deltaCredit >= totalLiquidity.mul(swapDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultSwapMode);
                                      }
                                      emit Swap(_dstChainId, _dstPoolId, _from, s.amount, s.eqReward, s.eqFee, s.protocolFee, s.lpFee);
                                      return s;
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function sendCredits(uint16 _dstChainId, uint256 _dstPoolId) external nonReentrant onlyRouter returns (CreditObj memory c) {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == true, "Stargate: counter chainPath is not ready");
                                      cp.lkb = cp.lkb.add(cp.credits);
                                      c.idealBalance = totalLiquidity.mul(cp.weight).div(totalWeight);
                                      c.credits = cp.credits;
                                      cp.credits = 0;
                                      emit SendCredits(_dstChainId, _dstPoolId, c.credits, c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemRemote   ->                        swapRemote
                                  function redeemRemote(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      address _from,
                                      uint256 _amountLP
                                  ) external nonReentrant onlyRouter {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 amountSD = _burnLocal(_from, _amountLP);
                                      //run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      emit RedeemRemote(_dstChainId, _dstPoolId, _from, _amountLP, amountLD);
                                  }
                                  function instantRedeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      address _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      uint256 _deltaCredit = deltaCredit; // sload optimization.
                                      uint256 _capAmountLP = _amountSDtoLP(_deltaCredit);
                                      if (_amountLP > _capAmountLP) _amountLP = _capAmountLP;
                                      amountSD = _burnLocal(_from, _amountLP);
                                      deltaCredit = _deltaCredit.sub(amountSD);
                                      uint256 amountLD = amountSDtoLD(amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit InstantRedeemLocal(_from, _amountLP, amountSD, _to);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocal(
                                      address _from,
                                      uint256 _amountLP,
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      bytes calldata _to
                                  ) external nonReentrant onlyRouter returns (uint256 amountSD) {
                                      require(_from != address(0x0), "Stargate: _from cannot be 0x0");
                                      // safeguard.
                                      require(chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]].ready == true, "Stargate: counter chainPath is not ready");
                                      amountSD = _burnLocal(_from, _amountLP);
                                      // run Delta
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(false);
                                      }
                                      emit RedeemLocal(_from, _amountLP, amountSD, _dstChainId, _dstPoolId, _to);
                                  }
                                  //---------------------------------------------------------------------------
                                  // REMOTE CHAIN FUNCTIONS
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // sendCredits      ->                      creditChainPath
                                  function creditChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      CreditObj memory _c
                                  ) external nonReentrant onlyRouter {
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      cp.balance = cp.balance.add(_c.credits);
                                      if (cp.idealBalance != _c.idealBalance) {
                                          cp.idealBalance = _c.idealBalance;
                                      }
                                      emit CreditChainPath(_dstChainId, _dstPoolId, _c.credits, _c.idealBalance);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // swap             ->                      swapRemote
                                  function swapRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      SwapObj memory _s
                                  ) external nonReentrant onlyRouter returns (uint256 amountLD) {
                                      // booking lpFee
                                      totalLiquidity = totalLiquidity.add(_s.lpFee);
                                      // booking eqFee
                                      eqFeePool = eqFeePool.add(_s.eqFee);
                                      // booking stargateFee
                                      protocolFeeBalance = protocolFeeBalance.add(_s.protocolFee);
                                      // update LKB
                                      uint256 chainPathIndex = chainPathIndexLookup[_srcChainId][_srcPoolId];
                                      chainPaths[chainPathIndex].lkb = chainPaths[chainPathIndex].lkb.sub(_s.lkbRemove);
                                      // user receives the amount + the srcReward
                                      amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
                                      _safeTransfer(token, _to, amountLD);
                                      emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal   ->                         redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCallback(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      address _to,
                                      uint256 _amountSD,
                                      uint256 _amountToMintSD
                                  ) external nonReentrant onlyRouter {
                                      if (_amountToMintSD > 0) {
                                          _mintLocal(_to, amountSDtoLD(_amountToMintSD), false, false);
                                      }
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      cp.lkb = cp.lkb.sub(_amountSD);
                                      uint256 amountLD = amountSDtoLD(_amountSD);
                                      _safeTransfer(token, _to, amountLD);
                                      emit RedeemLocalCallback(_to, _amountSD, _amountToMintSD);
                                  }
                                  // Local                                    Remote
                                  // -------                                  ---------
                                  // redeemLocal(amount)   ->               redeemLocalCheckOnRemote
                                  // redeemLocalCallback             <-
                                  function redeemLocalCheckOnRemote(
                                      uint16 _srcChainId,
                                      uint256 _srcPoolId,
                                      uint256 _amountSD
                                  ) external nonReentrant onlyRouter returns (uint256 swapAmount, uint256 mintAmount) {
                                      ChainPath storage cp = getAndCheckCP(_srcChainId, _srcPoolId);
                                      if (_amountSD > cp.balance) {
                                          mintAmount = _amountSD - cp.balance;
                                          swapAmount = cp.balance;
                                          cp.balance = 0;
                                      } else {
                                          cp.balance = cp.balance.sub(_amountSD);
                                          swapAmount = _amountSD;
                                          mintAmount = 0;
                                      }
                                      emit WithdrawRemote(_srcChainId, _srcPoolId, swapAmount, mintAmount);
                                  }
                                  //---------------------------------------------------------------------------
                                  // DAO Calls
                                  function createChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint256 _weight
                                  ) external onlyRouter {
                                      for (uint256 i = 0; i < chainPaths.length; ++i) {
                                          ChainPath memory cp = chainPaths[i];
                                          bool exists = cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId;
                                          require(!exists, "Stargate: cant createChainPath of existing dstChainId and _dstPoolId");
                                      }
                                      totalWeight = totalWeight.add(_weight);
                                      chainPathIndexLookup[_dstChainId][_dstPoolId] = chainPaths.length;
                                      chainPaths.push(ChainPath(false, _dstChainId, _dstPoolId, _weight, 0, 0, 0, 0));
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setWeightForChainPath(
                                      uint16 _dstChainId,
                                      uint256 _dstPoolId,
                                      uint16 _weight
                                  ) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      totalWeight = totalWeight.sub(cp.weight).add(_weight);
                                      cp.weight = _weight;
                                      emit ChainPathUpdate(_dstChainId, _dstPoolId, _weight);
                                  }
                                  function setFee(uint256 _mintFeeBP) external onlyRouter {
                                      require(_mintFeeBP <= BP_DENOMINATOR, "Bridge: cum fees > 100%");
                                      mintFeeBP = _mintFeeBP;
                                      emit FeesUpdated(mintFeeBP);
                                  }
                                  function setFeeLibrary(address _feeLibraryAddr) external onlyRouter {
                                      require(_feeLibraryAddr != address(0x0), "Stargate: fee library cant be 0x0");
                                      feeLibrary = _feeLibraryAddr;
                                      emit FeeLibraryUpdated(_feeLibraryAddr);
                                  }
                                  function setSwapStop(bool _swapStop) external onlyRouter {
                                      stopSwap = _swapStop;
                                      emit StopSwapUpdated(_swapStop);
                                  }
                                  function setDeltaParam(
                                      bool _batched,
                                      uint256 _swapDeltaBP,
                                      uint256 _lpDeltaBP,
                                      bool _defaultSwapMode,
                                      bool _defaultLPMode
                                  ) external onlyRouter {
                                      require(_swapDeltaBP <= BP_DENOMINATOR && _lpDeltaBP <= BP_DENOMINATOR, "Stargate: wrong Delta param");
                                      batched = _batched;
                                      swapDeltaBP = _swapDeltaBP;
                                      lpDeltaBP = _lpDeltaBP;
                                      defaultSwapMode = _defaultSwapMode;
                                      defaultLPMode = _defaultLPMode;
                                      emit DeltaParamUpdated(_batched, _swapDeltaBP, _lpDeltaBP, _defaultSwapMode, _defaultLPMode);
                                  }
                                  function callDelta(bool _fullMode) external onlyRouter {
                                      _delta(_fullMode);
                                  }
                                  function activateChainPath(uint16 _dstChainId, uint256 _dstPoolId) external onlyRouter {
                                      ChainPath storage cp = getAndCheckCP(_dstChainId, _dstPoolId);
                                      require(cp.ready == false, "Stargate: chainPath is already active");
                                      // this func will only be called once
                                      cp.ready = true;
                                  }
                                  function withdrawProtocolFeeBalance(address _to) external onlyRouter {
                                      if (protocolFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(protocolFeeBalance);
                                          protocolFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawProtocolFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  function withdrawMintFeeBalance(address _to) external onlyRouter {
                                      if (mintFeeBalance > 0) {
                                          uint256 amountOfLD = amountSDtoLD(mintFeeBalance);
                                          mintFeeBalance = 0;
                                          _safeTransfer(token, _to, amountOfLD);
                                          emit WithdrawMintFeeBalance(_to, amountOfLD);
                                      }
                                  }
                                  //---------------------------------------------------------------------------
                                  // INTERNAL
                                  // Conversion Helpers
                                  //---------------------------------------------------------------------------
                                  function amountLPtoLD(uint256 _amountLP) external view returns (uint256) {
                                      return amountSDtoLD(_amountLPtoSD(_amountLP));
                                  }
                                  function _amountLPtoSD(uint256 _amountLP) internal view returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant convert LPtoSD when totalSupply == 0");
                                      return _amountLP.mul(totalLiquidity).div(totalSupply);
                                  }
                                  function _amountSDtoLP(uint256 _amountSD) internal view returns (uint256) {
                                      require(totalLiquidity > 0, "Stargate: cant convert SDtoLP when totalLiq == 0");
                                      return _amountSD.mul(totalSupply).div(totalLiquidity);
                                  }
                                  function amountSDtoLD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.mul(convertRate);
                                  }
                                  function amountLDtoSD(uint256 _amount) internal view returns (uint256) {
                                      return _amount.div(convertRate);
                                  }
                                  function getAndCheckCP(uint16 _dstChainId, uint256 _dstPoolId) internal view returns (ChainPath storage) {
                                      require(chainPaths.length > 0, "Stargate: no chainpaths exist");
                                      ChainPath storage cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function getChainPath(uint16 _dstChainId, uint256 _dstPoolId) external view returns (ChainPath memory) {
                                      ChainPath memory cp = chainPaths[chainPathIndexLookup[_dstChainId][_dstPoolId]];
                                      require(cp.dstChainId == _dstChainId && cp.dstPoolId == _dstPoolId, "Stargate: local chainPath does not exist");
                                      return cp;
                                  }
                                  function _burnLocal(address _from, uint256 _amountLP) internal returns (uint256) {
                                      require(totalSupply > 0, "Stargate: cant burn when totalSupply == 0");
                                      uint256 amountOfLPTokens = balanceOf[_from];
                                      require(amountOfLPTokens >= _amountLP, "Stargate: not enough LP tokens to burn");
                                      uint256 amountSD = _amountLP.mul(totalLiquidity).div(totalSupply);
                                      //subtract totalLiquidity accordingly
                                      totalLiquidity = totalLiquidity.sub(amountSD);
                                      _burn(_from, _amountLP);
                                      emit Burn(_from, _amountLP, amountSD);
                                      return amountSD;
                                  }
                                  function _delta(bool fullMode) internal {
                                      if (deltaCredit > 0 && totalWeight > 0) {
                                          uint256 cpLength = chainPaths.length;
                                          uint256[] memory deficit = new uint256[](cpLength);
                                          uint256 totalDeficit = 0;
                                          // algorithm steps 6-9: calculate the total and the amounts required to get to balance state
                                          for (uint256 i = 0; i < cpLength; ++i) {
                                              ChainPath storage cp = chainPaths[i];
                                              // (liquidity * (weight/totalWeight)) - (lkb+credits)
                                              uint256 balLiq = totalLiquidity.mul(cp.weight).div(totalWeight);
                                              uint256 currLiq = cp.lkb.add(cp.credits);
                                              if (balLiq > currLiq) {
                                                  // save gas since we know balLiq > currLiq and we know deficit[i] > 0
                                                  deficit[i] = balLiq - currLiq;
                                                  totalDeficit = totalDeficit.add(deficit[i]);
                                              }
                                          }
                                          // indicates how much delta credit is distributed
                                          uint256 spent;
                                          // handle credits with 2 tranches. the [ < totalDeficit] [excessCredit]
                                          // run full Delta, allocate all credits
                                          if (totalDeficit == 0) {
                                              // only fullMode delta will allocate excess credits
                                              if (fullMode && deltaCredit > 0) {
                                                  // credit ChainPath by weights
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      // credits = credits + toBalanceChange + remaining allocation based on weight
                                                      uint256 amtToCredit = deltaCredit.mul(cp.weight).div(totalWeight);
                                                      spent = spent.add(amtToCredit);
                                                      cp.credits = cp.credits.add(amtToCredit);
                                                  }
                                              } // else do nth
                                          } else if (totalDeficit <= deltaCredit) {
                                              if (fullMode) {
                                                  // algorithm step 13: calculate amount to disperse to bring to balance state or as close as possible
                                                  uint256 excessCredit = deltaCredit - totalDeficit;
                                                  // algorithm steps 14-16: calculate credits
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          // credits = credits + deficit + remaining allocation based on weight
                                                          uint256 amtToCredit = deficit[i].add(excessCredit.mul(cp.weight).div(totalWeight));
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              } else {
                                                  // totalDeficit <= deltaCredit but not running fullMode
                                                  // credit chainPaths as is if any deficit, not using all deltaCredit
                                                  for (uint256 i = 0; i < cpLength; ++i) {
                                                      if (deficit[i] > 0) {
                                                          ChainPath storage cp = chainPaths[i];
                                                          uint256 amtToCredit = deficit[i];
                                                          spent = spent.add(amtToCredit);
                                                          cp.credits = cp.credits.add(amtToCredit);
                                                      }
                                                  }
                                              }
                                          } else {
                                              // totalDeficit > deltaCredit, fullMode or not, normalize the deficit by deltaCredit
                                              for (uint256 i = 0; i < cpLength; ++i) {
                                                  if (deficit[i] > 0) {
                                                      ChainPath storage cp = chainPaths[i];
                                                      uint256 proportionalDeficit = deficit[i].mul(deltaCredit).div(totalDeficit);
                                                      spent = spent.add(proportionalDeficit);
                                                      cp.credits = cp.credits.add(proportionalDeficit);
                                                  }
                                              }
                                          }
                                          // deduct the amount of credit sent
                                          deltaCredit = deltaCredit.sub(spent);
                                      }
                                  }
                                  function _mintLocal(
                                      address _to,
                                      uint256 _amountLD,
                                      bool _feesEnabled,
                                      bool _creditDelta
                                  ) internal returns (uint256 amountSD) {
                                      require(totalWeight > 0, "Stargate: No ChainPaths exist");
                                      amountSD = amountLDtoSD(_amountLD);
                                      uint256 mintFeeSD = 0;
                                      if (_feesEnabled) {
                                          mintFeeSD = amountSD.mul(mintFeeBP).div(BP_DENOMINATOR);
                                          amountSD = amountSD.sub(mintFeeSD);
                                          mintFeeBalance = mintFeeBalance.add(mintFeeSD);
                                      }
                                      if (_creditDelta) {
                                          deltaCredit = deltaCredit.add(amountSD);
                                      }
                                      uint256 amountLPTokens = amountSD;
                                      if (totalSupply != 0) {
                                          amountLPTokens = amountSD.mul(totalSupply).div(totalLiquidity);
                                      }
                                      totalLiquidity = totalLiquidity.add(amountSD);
                                      _mint(_to, amountLPTokens);
                                      emit Mint(_to, amountLPTokens, amountSD, mintFeeSD);
                                      // add to credits and call delta. short circuit to save gas
                                      if (!batched || deltaCredit > totalLiquidity.mul(lpDeltaBP).div(BP_DENOMINATOR)) {
                                          _delta(defaultLPMode);
                                      }
                                  }
                                  function _safeTransfer(
                                      address _token,
                                      address _to,
                                      uint256 _value
                                  ) private {
                                      (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(SELECTOR, _to, _value));
                                      require(success && (data.length == 0 || abi.decode(data, (bool))), "Stargate: TRANSFER_FAILED");
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              pragma abicoder v2;
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./Pool.sol";
                              contract Factory is Ownable {
                                  using SafeMath for uint256;
                                  //---------------------------------------------------------------------------
                                  // VARIABLES
                                  mapping(uint256 => Pool) public getPool; // poolId -> PoolInfo
                                  address[] public allPools;
                                  address public immutable router;
                                  address public defaultFeeLibrary; // address for retrieving fee params for swaps
                                  //---------------------------------------------------------------------------
                                  // MODIFIERS
                                  modifier onlyRouter() {
                                      require(msg.sender == router, "Stargate: caller must be Router.");
                                      _;
                                  }
                                  constructor(address _router) {
                                      require(_router != address(0x0), "Stargate: _router cant be 0x0"); // 1 time only
                                      router = _router;
                                  }
                                  function setDefaultFeeLibrary(address _defaultFeeLibrary) external onlyOwner {
                                      require(_defaultFeeLibrary != address(0x0), "Stargate: fee library cant be 0x0");
                                      defaultFeeLibrary = _defaultFeeLibrary;
                                  }
                                  function allPoolsLength() external view returns (uint256) {
                                      return allPools.length;
                                  }
                                  function createPool(
                                      uint256 _poolId,
                                      address _token,
                                      uint8 _sharedDecimals,
                                      uint8 _localDecimals,
                                      string memory _name,
                                      string memory _symbol
                                  ) public onlyRouter returns (address poolAddress) {
                                      require(address(getPool[_poolId]) == address(0x0), "Stargate: Pool already created");
                                      Pool pool = new Pool(_poolId, router, _token, _sharedDecimals, _localDecimals, defaultFeeLibrary, _name, _symbol);
                                      getPool[_poolId] = pool;
                                      poolAddress = address(pool);
                                      allPools.push(poolAddress);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity ^0.7.6;
                              pragma abicoder v2;
                              interface IStargateLPStaking {
                                  function poolInfo(uint256 _poolIndex)
                                      external
                                      view
                                      returns (
                                          address,
                                          uint256,
                                          uint256,
                                          uint256
                                      );
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.6;
                              interface AggregatorV3Interface {
                                  function decimals() external view returns (uint8);
                                  function description() external view returns (string memory);
                                  function version() external view returns (uint256);
                                  // getRoundData and latestRoundData should both raise "No data present"
                                  // if they do not have data to report, instead of returning unset values
                                  // which could be misinterpreted as actual reported values.
                                  function getRoundData(uint80 _roundId)
                                  external
                                  view
                                  returns (
                                      uint80 roundId,
                                      int256 answer,
                                      uint256 startedAt,
                                      uint256 updatedAt,
                                      uint80 answeredInRound
                                  );
                                  function latestRoundData()
                                  external
                                  view
                                  returns (
                                      uint80 roundId,
                                      int256 answer,
                                      uint256 startedAt,
                                      uint256 updatedAt,
                                      uint80 answeredInRound
                                  );
                              }// SPDX-License-Identifier: MIT
                              pragma solidity 0.7.6;
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@layerzerolabs/layerzero-core/contracts/interfaces/ILayerZeroReceiver.sol";
                              import "@layerzerolabs/layerzero-core/contracts/interfaces/ILayerZeroEndpoint.sol";
                              import "@layerzerolabs/layerzero-core/contracts/interfaces/ILayerZeroUserApplicationConfig.sol";
                              /*
                               * a generic LzReceiver implementation
                               */
                              abstract contract LzApp is Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                                  ILayerZeroEndpoint public immutable lzEndpoint;
                                  mapping(uint16 => bytes) public trustedRemoteLookup;
                                  mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup;
                                  address public precrime;
                                  event SetPrecrime(address precrime);
                                  event SetTrustedRemote(uint16 _remoteChainId, bytes _path);
                                  event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);
                                  event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas);
                                  constructor(address _endpoint) {
                                      lzEndpoint = ILayerZeroEndpoint(_endpoint);
                                  }
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) public virtual override {
                                      // lzReceive must be called by the endpoint for security
                                      require(_msgSender() == address(lzEndpoint), "LzApp: invalid endpoint caller");
                                      bytes memory trustedRemote = trustedRemoteLookup[_srcChainId];
                                      // if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote.
                                      require(_srcAddress.length == trustedRemote.length && trustedRemote.length > 0 && keccak256(_srcAddress) == keccak256(trustedRemote), "LzApp: invalid source sending contract");
                                      _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload);
                                  }
                                  // abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging
                                  function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
                                  function _lzSend(uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint _nativeFee) internal virtual {
                                      bytes memory trustedRemote = trustedRemoteLookup[_dstChainId];
                                      require(trustedRemote.length != 0, "LzApp: destination chain is not a trusted source");
                                      lzEndpoint.send{value: _nativeFee}(_dstChainId, trustedRemote, _payload, _refundAddress, _zroPaymentAddress, _adapterParams);
                                  }
                                  function _checkGasLimit(uint16 _dstChainId, uint16 _type, bytes memory _adapterParams, uint _extraGas) internal view virtual {
                                      uint providedGasLimit = _getGasLimit(_adapterParams);
                                      uint minGasLimit = minDstGasLookup[_dstChainId][_type] + _extraGas;
                                      require(minGasLimit > 0, "LzApp: minGasLimit not set");
                                      require(providedGasLimit >= minGasLimit, "LzApp: gas limit is too low");
                                  }
                                  function _getGasLimit(bytes memory _adapterParams) internal pure virtual returns (uint gasLimit) {
                                      require(_adapterParams.length >= 34, "LzApp: invalid adapterParams");
                                      assembly {
                                          gasLimit := mload(add(_adapterParams, 34))
                                      }
                                  }
                                  //---------------------------UserApplication config----------------------------------------
                                  function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
                                      return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
                                  }
                                  // generic config for LayerZero user Application
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override onlyOwner {
                                      lzEndpoint.setConfig(_version, _chainId, _configType, _config);
                                  }
                                  function setSendVersion(uint16 _version) external override onlyOwner {
                                      lzEndpoint.setSendVersion(_version);
                                  }
                                  function setReceiveVersion(uint16 _version) external override onlyOwner {
                                      lzEndpoint.setReceiveVersion(_version);
                                  }
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                                      lzEndpoint.forceResumeReceive(_srcChainId, _srcAddress);
                                  }
                                  // _path = abi.encodePacked(remoteAddress, localAddress)
                                  // this function set the trusted path for the cross-chain communication
                                  function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external onlyOwner {
                                      trustedRemoteLookup[_srcChainId] = _path;
                                      emit SetTrustedRemote(_srcChainId, _path);
                                  }
                                  function setPrecrime(address _precrime) external onlyOwner {
                                      precrime = _precrime;
                                      emit SetPrecrime(_precrime);
                                  }
                                  function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint _minGas) external onlyOwner {
                                      require(_minGas > 0, "LzApp: invalid minGas");
                                      minDstGasLookup[_dstChainId][_packetType] = _minGas;
                                      emit SetMinDstGas(_dstChainId, _packetType, _minGas);
                                  }
                                  //--------------------------- VIEW FUNCTION ----------------------------------------
                                  function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool) {
                                      bytes memory trustedSource = trustedRemoteLookup[_srcChainId];
                                      return keccak256(trustedSource) == keccak256(_srcAddress);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Moves `amount` tokens from `sender` to `recipient` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              }
                              

                              File 13 of 16: LPStaking
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              // imports
                              import "@openzeppelin/contracts/utils/EnumerableSet.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "./StargateToken.sol";
                              // interfaces
                              import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              // libraries
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
                              contract LPStaking is Ownable {
                                  using SafeMath for uint256;
                                  using SafeERC20 for IERC20;
                                  // Info of each user.
                                  struct UserInfo {
                                      uint256 amount; // How many LP tokens the user has provided.
                                      uint256 rewardDebt; // Reward debt. See explanation below.
                                      //
                                      // We do some fancy math here. Basically, any point in time, the amount of STGs
                                      // entitled to a user but is pending to be distributed is:
                                      //
                                      //   pending reward = (user.amount * pool.accStargatePerShare) - user.rewardDebt
                                      //
                                      // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
                                      //   1. The pool's `accStargatePerShare` (and `lastRewardBlock`) gets updated.
                                      //   2. User receives the pending reward sent to his/her address.
                                      //   3. User's `amount` gets updated.
                                      //   4. User's `rewardDebt` gets updated.
                                  }
                                  // Info of each pool.
                                  struct PoolInfo {
                                      IERC20 lpToken; // Address of LP token contract.
                                      uint256 allocPoint; // How many allocation points assigned to this pool. STGs to distribute per block.
                                      uint256 lastRewardBlock; // Last block number that STGs distribution occurs.
                                      uint256 accStargatePerShare; // Accumulated STGs per share, times 1e12. See below.
                                  }
                                  // The STG TOKEN!
                                  StargateToken public stargate;
                                  // Block number when bonus STG period ends.
                                  uint256 public bonusEndBlock;
                                  // STG tokens created per block.
                                  uint256 public stargatePerBlock;
                                  // Bonus multiplier for early stargate makers.
                                  uint256 public constant BONUS_MULTIPLIER = 1;
                                  // Track which tokens have been added.
                                  mapping(address => bool) private addedLPTokens;
                                  mapping(uint256 => uint256) public lpBalances;
                                  // Info of each pool.
                                  PoolInfo[] public poolInfo;
                                  // Info of each user that stakes LP tokens.
                                  mapping(uint256 => mapping(address => UserInfo)) public userInfo;
                                  // Total allocation points. Must be the sum of all allocation points in all pools.
                                  uint256 public totalAllocPoint = 0;
                                  // The block number when STG mining starts.
                                  uint256 public startBlock;
                                  event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
                                  event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
                                  event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
                                  constructor(
                                      StargateToken _stargate,
                                      uint256 _stargatePerBlock,
                                      uint256 _startBlock,
                                      uint256 _bonusEndBlock
                                  ) {
                                      require(_startBlock >= block.number, "LPStaking: _startBlock must be >= current block");
                                      require(_bonusEndBlock >= _startBlock, "LPStaking: _bonusEndBlock must be > than _startBlock");
                                      require(address(_stargate) != address(0x0), "Stargate: _stargate cannot be 0x0");
                                      stargate = _stargate;
                                      stargatePerBlock = _stargatePerBlock;
                                      startBlock = _startBlock;
                                      bonusEndBlock = _bonusEndBlock;
                                  }
                                  function poolLength() external view returns (uint256) {
                                      return poolInfo.length;
                                  }
                                  /// @notice handles adding a new LP token (Can only be called by the owner)
                                  /// @param _allocPoint The alloc point is used as the weight of the pool against all other alloc points added.
                                  /// @param _lpToken The lp token address
                                  function add(uint256 _allocPoint, IERC20 _lpToken) public onlyOwner {
                                      massUpdatePools();
                                      require(address(_lpToken) != address(0x0), "StarGate: lpToken cant be 0x0");
                                      require(addedLPTokens[address(_lpToken)] == false, "StarGate: _lpToken already exists");
                                      addedLPTokens[address(_lpToken)] = true;
                                      uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
                                      totalAllocPoint = totalAllocPoint.add(_allocPoint);
                                      poolInfo.push(PoolInfo({lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accStargatePerShare: 0}));
                                  }
                                  function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
                                      massUpdatePools();
                                      totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
                                      poolInfo[_pid].allocPoint = _allocPoint;
                                  }
                                  function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
                                      if (_to <= bonusEndBlock) {
                                          return _to.sub(_from).mul(BONUS_MULTIPLIER);
                                      } else if (_from >= bonusEndBlock) {
                                          return _to.sub(_from);
                                      } else {
                                          return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
                                      }
                                  }
                                  function pendingStargate(uint256 _pid, address _user) external view returns (uint256) {
                                      PoolInfo storage pool = poolInfo[_pid];
                                      UserInfo storage user = userInfo[_pid][_user];
                                      uint256 accStargatePerShare = pool.accStargatePerShare;
                                      uint256 lpSupply = pool.lpToken.balanceOf(address(this));
                                      if (block.number > pool.lastRewardBlock && lpSupply != 0) {
                                          uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
                                          uint256 stargateReward = multiplier.mul(stargatePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
                                          accStargatePerShare = accStargatePerShare.add(stargateReward.mul(1e12).div(lpSupply));
                                      }
                                      return user.amount.mul(accStargatePerShare).div(1e12).sub(user.rewardDebt);
                                  }
                                  function massUpdatePools() public {
                                      uint256 length = poolInfo.length;
                                      for (uint256 pid = 0; pid < length; ++pid) {
                                          updatePool(pid);
                                      }
                                  }
                                  function updatePool(uint256 _pid) public {
                                      PoolInfo storage pool = poolInfo[_pid];
                                      if (block.number <= pool.lastRewardBlock) {
                                          return;
                                      }
                                      uint256 lpSupply = pool.lpToken.balanceOf(address(this));
                                      if (lpSupply == 0) {
                                          pool.lastRewardBlock = block.number;
                                          return;
                                      }
                                      uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
                                      uint256 stargateReward = multiplier.mul(stargatePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
                                      pool.accStargatePerShare = pool.accStargatePerShare.add(stargateReward.mul(1e12).div(lpSupply));
                                      pool.lastRewardBlock = block.number;
                                  }
                                  function deposit(uint256 _pid, uint256 _amount) public {
                                      PoolInfo storage pool = poolInfo[_pid];
                                      UserInfo storage user = userInfo[_pid][msg.sender];
                                      updatePool(_pid);
                                      if (user.amount > 0) {
                                          uint256 pending = user.amount.mul(pool.accStargatePerShare).div(1e12).sub(user.rewardDebt);
                                          safeStargateTransfer(msg.sender, pending);
                                      }
                                      pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
                                      user.amount = user.amount.add(_amount);
                                      user.rewardDebt = user.amount.mul(pool.accStargatePerShare).div(1e12);
                                      lpBalances[_pid] = lpBalances[_pid].add(_amount);
                                      emit Deposit(msg.sender, _pid, _amount);
                                  }
                                  function withdraw(uint256 _pid, uint256 _amount) public {
                                      PoolInfo storage pool = poolInfo[_pid];
                                      UserInfo storage user = userInfo[_pid][msg.sender];
                                      require(user.amount >= _amount, "withdraw: _amount is too large");
                                      updatePool(_pid);
                                      uint256 pending = user.amount.mul(pool.accStargatePerShare).div(1e12).sub(user.rewardDebt);
                                      safeStargateTransfer(msg.sender, pending);
                                      user.amount = user.amount.sub(_amount);
                                      user.rewardDebt = user.amount.mul(pool.accStargatePerShare).div(1e12);
                                      pool.lpToken.safeTransfer(address(msg.sender), _amount);
                                      lpBalances[_pid] = lpBalances[_pid].sub(_amount);
                                      emit Withdraw(msg.sender, _pid, _amount);
                                  }
                                  /// @notice Withdraw without caring about rewards.
                                  /// @param _pid The pid specifies the pool
                                  function emergencyWithdraw(uint256 _pid) public {
                                      PoolInfo storage pool = poolInfo[_pid];
                                      UserInfo storage user = userInfo[_pid][msg.sender];
                                      uint256 userAmount = user.amount;
                                      user.amount = 0;
                                      user.rewardDebt = 0;
                                      pool.lpToken.safeTransfer(address(msg.sender), userAmount);
                                      lpBalances[_pid] = lpBalances[_pid].sub(userAmount);
                                      emit EmergencyWithdraw(msg.sender, _pid, userAmount);
                                  }
                                  /// @notice Safe transfer function, just in case if rounding error causes pool to not have enough STGs.
                                  /// @param _to The address to transfer tokens to
                                  /// @param _amount The quantity to transfer
                                  function safeStargateTransfer(address _to, uint256 _amount) internal {
                                      uint256 stargateBal = stargate.balanceOf(address(this));
                                      if (_amount > stargateBal) {
                                          IERC20(stargate).safeTransfer(_to, stargateBal);
                                      } else {
                                          IERC20(stargate).safeTransfer(_to, _amount);
                                      }
                                  }
                                  function setStargatePerBlock(uint256 _stargatePerBlock) external onlyOwner {
                                      massUpdatePools();
                                      stargatePerBlock = _stargatePerBlock;
                                  }
                                  // Override the renounce ownership inherited by zeppelin ownable
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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.
                               */
                              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;
                                          // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                          // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                                          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] = toDeleteIndex + 1; // All indexes are 1-based
                                          // 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) {
                                      require(set._values.length > index, "EnumerableSet: index out of bounds");
                                      return set._values[index];
                                  }
                                  // 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);
                                  }
                                  // 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))));
                                  }
                                  // 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));
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity 0.7.6;
                              import "./OmnichainFungibleToken.sol";
                              contract StargateToken is OmnichainFungibleToken {
                                  constructor(
                                      string memory _name,
                                      string memory _symbol,
                                      address _endpoint,
                                      uint16 _mainEndpointId,
                                      uint256 _initialSupplyOnMainEndpoint
                                  ) OmnichainFungibleToken(_name, _symbol, _endpoint, _mainEndpointId, _initialSupplyOnMainEndpoint) {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Moves `amount` tokens from `sender` to `recipient` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              import "./IERC20.sol";
                              import "../../math/SafeMath.sol";
                              import "../../utils/Address.sol";
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using SafeMath for uint256;
                                  using Address for address;
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                                  }
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                                  }
                                  /**
                                   * @dev Deprecated. This function has issues similar to the ones found in
                                   * {IERC20-approve}, and its usage is discouraged.
                                   *
                                   * Whenever possible, use {safeIncreaseAllowance} and
                                   * {safeDecreaseAllowance} instead.
                                   */
                                  function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                      // safeApprove should only be called when setting an initial allowance,
                                      // or when resetting it to zero. To increase and decrease it, use
                                      // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                      // solhint-disable-next-line max-line-length
                                      require((value == 0) || (token.allowance(address(this), spender) == 0),
                                          "SafeERC20: approve from non-zero to non-zero allowance"
                                      );
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                                  }
                                  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                                      bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                      if (returndata.length > 0) { // Return data is optional
                                          // solhint-disable-next-line max-line-length
                                          require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <0.8.0;
                              /*
                               * @dev 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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                      return msg.data;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroEndpoint.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroReceiver.sol";
                              import "@layerzerolabs/contracts/contracts/interfaces/ILayerZeroUserApplicationConfig.sol";
                              contract OmnichainFungibleToken is ERC20, Ownable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig {
                                  // the only endpointId these tokens will ever be minted on
                                  // required: the LayerZero endpoint which is passed in the constructor
                                  ILayerZeroEndpoint immutable public endpoint;
                                  // a map of our connected contracts
                                  mapping(uint16 => bytes) public dstContractLookup;
                                  // pause the sendTokens()
                                  bool public paused;
                                  bool public isMain;
                                  event Paused(bool isPaused);
                                  event SendToChain(uint16 dstChainId, bytes to, uint256 qty);
                                  event ReceiveFromChain(uint16 srcChainId, uint64 nonce, uint256 qty);
                                  constructor(
                                      string memory _name,
                                      string memory _symbol,
                                      address _endpoint,
                                      uint16 _mainChainId,
                                      uint256 initialSupplyOnMainEndpoint
                                  ) ERC20(_name, _symbol) {
                                      if (ILayerZeroEndpoint(_endpoint).getChainId() == _mainChainId) {
                                          _mint(msg.sender, initialSupplyOnMainEndpoint);
                                          isMain = true;
                                      }
                                      // set the LayerZero endpoint
                                      endpoint = ILayerZeroEndpoint(_endpoint);
                                  }
                                  function pauseSendTokens(bool _pause) external onlyOwner {
                                      paused = _pause;
                                      emit Paused(_pause);
                                  }
                                  function setDestination(uint16 _dstChainId, bytes calldata _destinationContractAddress) public onlyOwner {
                                      dstContractLookup[_dstChainId] = _destinationContractAddress;
                                  }
                                  function chainId() external view returns (uint16){
                                      return endpoint.getChainId();
                                  }
                                  function sendTokens(
                                      uint16 _dstChainId, // send tokens to this chainId
                                      bytes calldata _to, // where to deliver the tokens on the destination chain
                                      uint256 _qty, // how many tokens to send
                                      address zroPaymentAddress, // ZRO payment address
                                      bytes calldata adapterParam // txParameters
                                  ) public payable {
                                      require(!paused, "OFT: sendTokens() is currently paused");
                                      // lock if leaving the safe chain, otherwise burn
                                      if (isMain) {
                                          // ... transferFrom the tokens to this contract for locking purposes
                                          _transfer(msg.sender, address(this), _qty);
                                      } else {
                                          _burn(msg.sender, _qty);
                                      }
                                      // abi.encode() the payload with the values to send
                                      bytes memory payload = abi.encode(_to, _qty);
                                      // send LayerZero message
                                      endpoint.send{value: msg.value}(
                                          _dstChainId, // destination chainId
                                          dstContractLookup[_dstChainId], // destination UA address
                                          payload, // abi.encode()'ed bytes
                                          msg.sender, // refund address (LayerZero will refund any extra gas back to caller of send()
                                          zroPaymentAddress, // 'zroPaymentAddress' unused for this mock/example
                                          adapterParam // 'adapterParameters' unused for this mock/example
                                      );
                                      emit SendToChain(_dstChainId, _to, _qty);
                                  }
                                  function lzReceive(
                                      uint16 _srcChainId,
                                      bytes memory _fromAddress,
                                      uint64 nonce,
                                      bytes memory _payload
                                  ) external override {
                                      require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security
                                      require(
                                          _fromAddress.length == dstContractLookup[_srcChainId].length && keccak256(_fromAddress) == keccak256(dstContractLookup[_srcChainId]),
                                          "OFT: invalid source sending contract"
                                      );
                                      // decode
                                      (bytes memory _to, uint256 _qty) = abi.decode(_payload, (bytes, uint256));
                                      address toAddress;
                                      // load the toAddress from the bytes
                                      assembly {
                                          toAddress := mload(add(_to, 20))
                                      }
                                      // mint the tokens back into existence, to the receiving address
                                      if (isMain) {
                                          _transfer(address(this), toAddress, _qty);
                                      } else {
                                          _mint(toAddress, _qty);
                                      }
                                      emit ReceiveFromChain(_srcChainId, nonce, _qty);
                                  }
                                  function estimateSendTokensFee(uint16 _dstChainId, bool _useZro, bytes calldata txParameters) external view returns (uint256 nativeFee, uint256 zroFee) {
                                      return endpoint.estimateFees(_dstChainId, address(this), bytes(""), _useZro, txParameters);
                                  }
                                  //---------------------------DAO CALL----------------------------------------
                                  // generic config for user Application
                                  function setConfig(
                                      uint16 _version,
                                      uint16 _chainId,
                                      uint256 _configType,
                                      bytes calldata _config
                                  ) external override onlyOwner {
                                      endpoint.setConfig(_version, _chainId, _configType, _config);
                                  }
                                  function setSendVersion(uint16 version) external override onlyOwner {
                                      endpoint.setSendVersion(version);
                                  }
                                  function setReceiveVersion(uint16 version) external override onlyOwner {
                                      endpoint.setReceiveVersion(version);
                                  }
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override onlyOwner {
                                      endpoint.forceResumeReceive(_srcChainId, _srcAddress);
                                  }
                                  function renounceOwnership() public override onlyOwner {}
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.0;
                              import "../../utils/Context.sol";
                              import "./IERC20.sol";
                              import "../../math/SafeMath.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 guidelines: functions revert instead
                               * of 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 {
                                  using SafeMath for uint256;
                                  mapping (address => uint256) private _balances;
                                  mapping (address => mapping (address => uint256)) private _allowances;
                                  uint256 private _totalSupply;
                                  string private _name;
                                  string private _symbol;
                                  uint8 private _decimals;
                                  /**
                                   * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
                                   * a default value of 18.
                                   *
                                   * To select a different value for {decimals}, use {_setupDecimals}.
                                   *
                                   * All three of these values are immutable: they can only be set once during
                                   * construction.
                                   */
                                  constructor (string memory name_, string memory symbol_) {
                                      _name = name_;
                                      _symbol = symbol_;
                                      _decimals = 18;
                                  }
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() public view virtual returns (string memory) {
                                      return _name;
                                  }
                                  /**
                                   * @dev Returns the symbol of the token, usually a shorter version of the
                                   * name.
                                   */
                                  function symbol() public view virtual 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 {_setupDecimals} is
                                   * called.
                                   *
                                   * 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 returns (uint8) {
                                      return _decimals;
                                  }
                                  /**
                                   * @dev See {IERC20-totalSupply}.
                                   */
                                  function totalSupply() public view virtual override returns (uint256) {
                                      return _totalSupply;
                                  }
                                  /**
                                   * @dev See {IERC20-balanceOf}.
                                   */
                                  function balanceOf(address account) public view virtual override returns (uint256) {
                                      return _balances[account];
                                  }
                                  /**
                                   * @dev See {IERC20-transfer}.
                                   *
                                   * Requirements:
                                   *
                                   * - `recipient` cannot be the zero address.
                                   * - the caller must have a balance of at least `amount`.
                                   */
                                  function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                                      _transfer(_msgSender(), recipient, amount);
                                      return true;
                                  }
                                  /**
                                   * @dev See {IERC20-allowance}.
                                   */
                                  function allowance(address owner, address spender) public view virtual override returns (uint256) {
                                      return _allowances[owner][spender];
                                  }
                                  /**
                                   * @dev See {IERC20-approve}.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   */
                                  function approve(address spender, uint256 amount) public virtual override returns (bool) {
                                      _approve(_msgSender(), spender, amount);
                                      return true;
                                  }
                                  /**
                                   * @dev See {IERC20-transferFrom}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance. This is not
                                   * required by the EIP. See the note at the beginning of {ERC20}.
                                   *
                                   * Requirements:
                                   *
                                   * - `sender` and `recipient` cannot be the zero address.
                                   * - `sender` must have a balance of at least `amount`.
                                   * - the caller must have allowance for ``sender``'s tokens of at least
                                   * `amount`.
                                   */
                                  function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
                                      _transfer(sender, recipient, amount);
                                      _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
                                      return true;
                                  }
                                  /**
                                   * @dev Atomically increases the allowance granted to `spender` by the caller.
                                   *
                                   * This is an alternative to {approve} that can be used as a mitigation for
                                   * problems described in {IERC20-approve}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   */
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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) {
                                      _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                                      return true;
                                  }
                                  /**
                                   * @dev Moves tokens `amount` from `sender` to `recipient`.
                                   *
                                   * This is internal function is equivalent to {transfer}, and can be used to
                                   * e.g. implement automatic token fees, slashing mechanisms, etc.
                                   *
                                   * Emits a {Transfer} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `sender` cannot be the zero address.
                                   * - `recipient` cannot be the zero address.
                                   * - `sender` must have a balance of at least `amount`.
                                   */
                                  function _transfer(address sender, address recipient, uint256 amount) internal virtual {
                                      require(sender != address(0), "ERC20: transfer from the zero address");
                                      require(recipient != address(0), "ERC20: transfer to the zero address");
                                      _beforeTokenTransfer(sender, recipient, amount);
                                      _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                                      _balances[recipient] = _balances[recipient].add(amount);
                                      emit Transfer(sender, recipient, amount);
                                  }
                                  /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                                   * the total supply.
                                   *
                                   * Emits a {Transfer} event with `from` set to the zero address.
                                   *
                                   * Requirements:
                                   *
                                   * - `to` 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 = _totalSupply.add(amount);
                                      _balances[account] = _balances[account].add(amount);
                                      emit Transfer(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);
                                      _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                                      _totalSupply = _totalSupply.sub(amount);
                                      emit Transfer(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 Sets {decimals} to a value other than the default one of 18.
                                   *
                                   * WARNING: This function should only be called from the constructor. Most
                                   * applications that interact with token contracts will not expect
                                   * {decimals} to ever change, and may work incorrectly if it does.
                                   */
                                  function _setupDecimals(uint8 decimals_) internal virtual {
                                      _decimals = decimals_;
                                  }
                                  /**
                                   * @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 to 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 { }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. ie: pay for a specified destination gasAmount, or receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroReceiver {
                                  // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                                  // @param _srcChainId - the source endpoint identifier
                                  // @param _srcAddress - the source sending contract address from the source chain
                                  // @param _nonce - the ordered message nonce
                                  // @param _payload - the signed payload is the UA bytes has encoded to be sent
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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);
                                          }
                                      }
                                  }
                              }
                              

                              File 14 of 16: Endpoint
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              import "./interfaces/ILayerZeroReceiver.sol";
                              import "./interfaces/ILayerZeroEndpoint.sol";
                              import "./interfaces/ILayerZeroMessagingLibrary.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              contract Endpoint is Ownable, ILayerZeroEndpoint {
                                  uint16 public immutable chainId;
                                  // installed libraries and reserved versions
                                  uint16 public constant BLOCK_VERSION = 65535;
                                  uint16 public constant DEFAULT_VERSION = 0;
                                  uint16 public latestVersion;
                                  mapping(uint16 => ILayerZeroMessagingLibrary) public libraryLookup; // version -> ILayerZeroEndpointLibrary
                                  // default send/receive libraries
                                  uint16 public defaultSendVersion;
                                  uint16 public defaultReceiveVersion;
                                  ILayerZeroMessagingLibrary public defaultSendLibrary;
                                  address public defaultReceiveLibraryAddress;
                                  struct LibraryConfig {
                                      uint16 sendVersion;
                                      uint16 receiveVersion;
                                      address receiveLibraryAddress;
                                      ILayerZeroMessagingLibrary sendLibrary;
                                  }
                                  struct StoredPayload {
                                      uint64 payloadLength;
                                      address dstAddress;
                                      bytes32 payloadHash;
                                  }
                                  // user app config = [uaAddress]
                                  mapping(address => LibraryConfig) public uaConfigLookup;
                                  // inboundNonce = [srcChainId][srcAddress].
                                  mapping(uint16 => mapping(bytes => uint64)) public inboundNonce;
                                  // outboundNonce = [dstChainId][srcAddress].
                                  mapping(uint16 => mapping(address => uint64)) public outboundNonce;
                                  // storedPayload = [srcChainId][srcAddress]
                                  mapping(uint16 => mapping(bytes => StoredPayload)) public storedPayload;
                                  // library versioning events
                                  event NewLibraryVersionAdded(uint16 version);
                                  event DefaultSendVersionSet(uint16 version);
                                  event DefaultReceiveVersionSet(uint16 version);
                                  event UaSendVersionSet(address ua, uint16 version);
                                  event UaReceiveVersionSet(address ua, uint16 version);
                                  event UaForceResumeReceive(uint16 chainId, bytes srcAddress);
                                  // payload events
                                  event PayloadCleared(uint16 srcChainId, bytes srcAddress, uint64 nonce, address dstAddress);
                                  event PayloadStored(uint16 srcChainId, bytes srcAddress, address dstAddress, uint64 nonce, bytes payload, bytes reason);
                                  constructor(uint16 _chainId) {
                                      chainId = _chainId;
                                  }
                                  //---------------------------------------------------------------------------
                                  // send and receive nonreentrant lock
                                  uint8 internal constant _NOT_ENTERED = 1;
                                  uint8 internal constant _ENTERED = 2;
                                  uint8 internal _send_entered_state = 1;
                                  uint8 internal _receive_entered_state = 1;
                                  modifier sendNonReentrant() {
                                      require(_send_entered_state == _NOT_ENTERED, "LayerZero: no send reentrancy");
                                      _send_entered_state = _ENTERED;
                                      _;
                                      _send_entered_state = _NOT_ENTERED;
                                  }
                                  modifier receiveNonReentrant() {
                                      require(_receive_entered_state == _NOT_ENTERED, "LayerZero: no receive reentrancy");
                                      _receive_entered_state = _ENTERED;
                                      _;
                                      _receive_entered_state = _NOT_ENTERED;
                                  }
                                  // BLOCK_VERSION is also a valid version
                                  modifier validVersion(uint16 _version) {
                                      require(_version <= latestVersion || _version == BLOCK_VERSION, "LayerZero: invalid messaging library version");
                                      _;
                                  }
                                  //---------------------------------------------------------------------------
                                  // User Application Calls - Endpoint Interface
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable override sendNonReentrant {
                                      LibraryConfig storage uaConfig = uaConfigLookup[msg.sender];
                                      uint64 nonce = ++outboundNonce[_dstChainId][msg.sender];
                                      _getSendLibrary(uaConfig).send{value: msg.value}(msg.sender, nonce, _dstChainId, _destination, _payload, _refundAddress, _zroPaymentAddress, _adapterParams);
                                  }
                                  //---------------------------------------------------------------------------
                                  // authenticated Library (msg.sender) Calls to pass through Endpoint to UA (dstAddress)
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external override receiveNonReentrant {
                                      // assert and increment the nonce. no message shuffling
                                      require(_nonce == ++inboundNonce[_srcChainId][_srcAddress], "LayerZero: wrong nonce");
                                      LibraryConfig storage uaConfig = uaConfigLookup[_dstAddress];
                                      // authentication to prevent cross-version message validation
                                      // protects against a malicious library from passing arbitrary data
                                      if (uaConfig.receiveVersion == DEFAULT_VERSION) {
                                          require(defaultReceiveLibraryAddress == msg.sender, "LayerZero: invalid default library");
                                      } else {
                                          require(uaConfig.receiveLibraryAddress == msg.sender, "LayerZero: invalid library");
                                      }
                                      // block if any message blocking
                                      StoredPayload storage sp = storedPayload[_srcChainId][_srcAddress];
                                      require(sp.payloadHash == bytes32(0), "LayerZero: in message blocking");
                                      try ILayerZeroReceiver(_dstAddress).lzReceive{gas: _gasLimit}(_srcChainId, _srcAddress, _nonce, _payload) {
                                          // success, do nothing, end of the message delivery
                                      } catch (bytes memory reason) {
                                          // revert nonce if any uncaught errors/exceptions if the ua chooses the blocking mode
                                          storedPayload[_srcChainId][_srcAddress] = StoredPayload(uint64(_payload.length), _dstAddress, keccak256(_payload));
                                          emit PayloadStored(_srcChainId, _srcAddress, _dstAddress, _nonce, _payload, reason);
                                      }
                                  }
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external override receiveNonReentrant {
                                      StoredPayload storage sp = storedPayload[_srcChainId][_srcAddress];
                                      require(sp.payloadHash != bytes32(0), "LayerZero: no stored payload");
                                      require(_payload.length == sp.payloadLength && keccak256(_payload) == sp.payloadHash, "LayerZero: invalid payload");
                                      address dstAddress = sp.dstAddress;
                                      // empty the storedPayload
                                      sp.payloadLength = 0;
                                      sp.dstAddress = address(0);
                                      sp.payloadHash = bytes32(0);
                                      uint64 nonce = inboundNonce[_srcChainId][_srcAddress];
                                      ILayerZeroReceiver(dstAddress).lzReceive(_srcChainId, _srcAddress, nonce, _payload);
                                      emit PayloadCleared(_srcChainId, _srcAddress, nonce, dstAddress);
                                  }
                                  //---------------------------------------------------------------------------
                                  // Owner Calls, only new library version upgrade (3 steps)
                                  // note libraryLookup[0] = 0x0, no library implementation
                                  // LIBRARY UPGRADE step 1: set _newLayerZeroLibraryAddress be the new version
                                  function newVersion(address _newLayerZeroLibraryAddress) external onlyOwner {
                                      require(_newLayerZeroLibraryAddress != address(0x0), "LayerZero: new version cannot be zero address");
                                      require(latestVersion < 65535, "LayerZero: can not add new messaging library");
                                      latestVersion++;
                                      libraryLookup[latestVersion] = ILayerZeroMessagingLibrary(_newLayerZeroLibraryAddress);
                                      emit NewLibraryVersionAdded(latestVersion);
                                  }
                                  // LIBRARY UPGRADE step 2: stop sending messages from the old version
                                  function setDefaultSendVersion(uint16 _newDefaultSendVersion) external onlyOwner validVersion(_newDefaultSendVersion) {
                                      require(_newDefaultSendVersion != DEFAULT_VERSION, "LayerZero: default send version must > 0");
                                      defaultSendVersion = _newDefaultSendVersion;
                                      defaultSendLibrary = libraryLookup[defaultSendVersion];
                                      emit DefaultSendVersionSet(_newDefaultSendVersion);
                                  }
                                  // LIBRARY UPGRADE step 3: stop receiving messages from the old version
                                  function setDefaultReceiveVersion(uint16 _newDefaultReceiveVersion) external onlyOwner validVersion(_newDefaultReceiveVersion) {
                                      require(_newDefaultReceiveVersion != DEFAULT_VERSION, "LayerZero: default receive version must > 0");
                                      defaultReceiveVersion = _newDefaultReceiveVersion;
                                      defaultReceiveLibraryAddress = address(libraryLookup[defaultReceiveVersion]);
                                      emit DefaultReceiveVersionSet(_newDefaultReceiveVersion);
                                  }
                                  //---------------------------------------------------------------------------
                                  // User Application Calls - UA set/get Interface
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external override validVersion(_version) {
                                      if (_version == DEFAULT_VERSION) {
                                          require(defaultSendVersion == defaultReceiveVersion, "LayerZero: can not set Config during DEFAULT migration");
                                          _version = defaultSendVersion;
                                      }
                                      require(_version != BLOCK_VERSION, "LayerZero: can not set config for BLOCK_VERSION");
                                      libraryLookup[_version].setConfig(_chainId, msg.sender, _configType, _config);
                                  }
                                  // Migration step 1: set the send version
                                  // Define what library the UA points too
                                  function setSendVersion(uint16 _newVersion) external override validVersion(_newVersion) {
                                      // write into config
                                      LibraryConfig storage uaConfig = uaConfigLookup[msg.sender];
                                      uaConfig.sendVersion = _newVersion;
                                      // the libraryLookup[BLOCK_VERSION || DEFAULT_VERSION] = 0x0
                                      uaConfig.sendLibrary = libraryLookup[_newVersion];
                                      emit UaSendVersionSet(msg.sender, _newVersion);
                                  }
                                  // Migration step 2: set the receive version
                                  // after all messages sent from the old version are received
                                  // the UA can now safely switch to the new receive version
                                  // it is the UA's responsibility make sure all messages from the old version are processed
                                  function setReceiveVersion(uint16 _newVersion) external override validVersion(_newVersion) {
                                      // write into config
                                      LibraryConfig storage uaConfig = uaConfigLookup[msg.sender];
                                      uaConfig.receiveVersion = _newVersion;
                                      // the libraryLookup[BLOCK_VERSION || DEFAULT_VERSION] = 0x0
                                      uaConfig.receiveLibraryAddress = address(libraryLookup[_newVersion]);
                                      emit UaReceiveVersionSet(msg.sender, _newVersion);
                                  }
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external override {
                                      StoredPayload storage sp = storedPayload[_srcChainId][_srcAddress];
                                      // revert if no messages are cached. safeguard malicious UA behaviour
                                      require(sp.payloadHash != bytes32(0), "LayerZero: no stored payload");
                                      require(sp.dstAddress == msg.sender, "LayerZero: invalid caller");
                                      // empty the storedPayload
                                      sp.payloadLength = 0;
                                      sp.dstAddress = address(0);
                                      sp.payloadHash = bytes32(0);
                                      // emit the event with the new nonce
                                      emit UaForceResumeReceive(_srcChainId, _srcAddress);
                                  }
                                  //---------------------------------------------------------------------------
                                  // view helper function
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParams) external view override returns (uint nativeFee, uint zroFee) {
                                      LibraryConfig storage uaConfig = uaConfigLookup[_userApplication];
                                      ILayerZeroMessagingLibrary lib = uaConfig.sendVersion == DEFAULT_VERSION ? defaultSendLibrary : uaConfig.sendLibrary;
                                      return lib.estimateFees(_dstChainId, _userApplication, _payload, _payInZRO, _adapterParams);
                                  }
                                  function _getSendLibrary(LibraryConfig storage uaConfig) internal view returns (ILayerZeroMessagingLibrary) {
                                      if (uaConfig.sendVersion == DEFAULT_VERSION) {
                                          // check if the in send-blocking upgrade
                                          require(defaultSendVersion != BLOCK_VERSION, "LayerZero: default in BLOCK_VERSION");
                                          return defaultSendLibrary;
                                      } else {
                                          // check if the in send-blocking upgrade
                                          require(uaConfig.sendVersion != BLOCK_VERSION, "LayerZero: in BLOCK_VERSION");
                                          return uaConfig.sendLibrary;
                                      }
                                  }
                                  function getSendLibraryAddress(address _userApplication) external view override returns (address sendLibraryAddress) {
                                      LibraryConfig storage uaConfig = uaConfigLookup[_userApplication];
                                      uint16 sendVersion = uaConfig.sendVersion;
                                      require(sendVersion != BLOCK_VERSION, "LayerZero: send version is BLOCK_VERSION");
                                      if (sendVersion == DEFAULT_VERSION) {
                                          require(defaultSendVersion != BLOCK_VERSION, "LayerZero: send version (default) is BLOCK_VERSION");
                                          sendLibraryAddress = address(defaultSendLibrary);
                                      } else {
                                          sendLibraryAddress = address(uaConfig.sendLibrary);
                                      }
                                  }
                                  function getReceiveLibraryAddress(address _userApplication) external view override returns (address receiveLibraryAddress) {
                                      LibraryConfig storage uaConfig = uaConfigLookup[_userApplication];
                                      uint16 receiveVersion = uaConfig.receiveVersion;
                                      require(receiveVersion != BLOCK_VERSION, "LayerZero: receive version is BLOCK_VERSION");
                                      if (receiveVersion == DEFAULT_VERSION) {
                                          require(defaultReceiveVersion != BLOCK_VERSION, "LayerZero: receive version (default) is BLOCK_VERSION");
                                          receiveLibraryAddress = defaultReceiveLibraryAddress;
                                      } else {
                                          receiveLibraryAddress = uaConfig.receiveLibraryAddress;
                                      }
                                  }
                                  function isSendingPayload() external view override returns (bool) {
                                      return _send_entered_state == _ENTERED;
                                  }
                                  function isReceivingPayload() external view override returns (bool) {
                                      return _receive_entered_state == _ENTERED;
                                  }
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view override returns (uint64) {
                                      return inboundNonce[_srcChainId][_srcAddress];
                                  }
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view override returns (uint64) {
                                      return outboundNonce[_dstChainId][_srcAddress];
                                  }
                                  function getChainId() external view override returns (uint16) {
                                      return chainId;
                                  }
                                  function getSendVersion(address _userApplication) external view override returns (uint16) {
                                      LibraryConfig storage uaConfig = uaConfigLookup[_userApplication];
                                      return uaConfig.sendVersion == DEFAULT_VERSION ? defaultSendVersion : uaConfig.sendVersion;
                                  }
                                  function getReceiveVersion(address _userApplication) external view override returns (uint16) {
                                      LibraryConfig storage uaConfig = uaConfigLookup[_userApplication];
                                      return uaConfig.receiveVersion == DEFAULT_VERSION ? defaultReceiveVersion : uaConfig.receiveVersion;
                                  }
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view override validVersion(_version) returns (bytes memory) {
                                      if (_version == DEFAULT_VERSION) {
                                          require(defaultSendVersion == defaultReceiveVersion, "LayerZero: no DEFAULT config while migration");
                                          _version = defaultSendVersion;
                                      }
                                      require(_version != BLOCK_VERSION, "LayerZero: can not get config for BLOCK_VERSION");
                                      return libraryLookup[_version].getConfig(_chainId, _userApplication, _configType);
                                  }
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view override returns (bool) {
                                      StoredPayload storage sp = storedPayload[_srcChainId][_srcAddress];
                                      return sp.payloadHash != bytes32(0);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroReceiver {
                                  // @notice LayerZero endpoint will invoke this function to deliver the message on the destination
                                  // @param _srcChainId - the source endpoint identifier
                                  // @param _srcAddress - the source sending contract address from the source chain
                                  // @param _nonce - the ordered message nonce
                                  // @param _payload - the signed payload is the UA bytes has encoded to be sent
                                  function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.7.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroMessagingLibrary {
                                  // send(), messages will be inflight.
                                  function send(address _userApplication, uint64 _lastNonce, uint16 _chainId, bytes calldata _destination, bytes calldata _payload, address payable refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // estimate native fee at the send side
                                  function estimateFees(uint16 _chainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  //---------------------------------------------------------------------------
                                  // setConfig / getConfig are User Application (UA) functions to specify Oracle, Relayer, blockConfirmations, libraryVersion
                                  function setConfig(uint16 _chainId, address _userApplication, uint _configType, bytes calldata _config) external;
                                  function getConfig(uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                      return msg.data;
                                  }
                              }
                              

                              File 15 of 16: NonceContract
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              import "./interfaces/ILayerZeroEndpoint.sol";
                              contract NonceContract {
                                  ILayerZeroEndpoint public immutable endpoint;
                                  // outboundNonce = [dstChainId][remoteAddress + localAddress]
                                  mapping(uint16 => mapping(bytes => uint64)) public outboundNonce;
                                  constructor(address _endpoint) {
                                      endpoint = ILayerZeroEndpoint(_endpoint);
                                  }
                                  function increment(uint16 _chainId, address _ua, bytes calldata _path) external returns (uint64) {
                                      require(endpoint.getSendLibraryAddress(_ua) == msg.sender, "NonceContract: msg.sender is not valid sendlibrary");
                                      return ++outboundNonce[_chainId][_path];
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              import "./ILayerZeroUserApplicationConfig.sol";
                              interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig {
                                  // @notice send a LayerZero message to the specified address at a LayerZero endpoint.
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains
                                  // @param _payload - a custom bytes payload to send to the destination contract
                                  // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
                                  // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
                                  // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
                                  function send(uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) external payable;
                                  // @notice used by the messaging library to publish verified payload
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source contract (as bytes) at the source chain
                                  // @param _dstAddress - the address on destination chain
                                  // @param _nonce - the unbound message ordering nonce
                                  // @param _gasLimit - the gas limit for external contract execution
                                  // @param _payload - verified payload to send to the destination contract
                                  function receivePayload(uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload) external;
                                  // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64);
                                  // @notice get the outboundNonce from this source chain which, consequently, is always an EVM
                                  // @param _srcAddress - the source chain contract address
                                  function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
                                  // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery
                                  // @param _dstChainId - the destination chain identifier
                                  // @param _userApplication - the user app address on this EVM chain
                                  // @param _payload - the custom message to send over LayerZero
                                  // @param _payInZRO - if false, user app pays the protocol fee in native token
                                  // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain
                                  function estimateFees(uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam) external view returns (uint nativeFee, uint zroFee);
                                  // @notice get this Endpoint's immutable source identifier
                                  function getChainId() external view returns (uint16);
                                  // @notice the interface to retry failed message on this Endpoint destination
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  // @param _payload - the payload to be retried
                                  function retryPayload(uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload) external;
                                  // @notice query if any STORED payload (message blocking) at the endpoint.
                                  // @param _srcChainId - the source chain identifier
                                  // @param _srcAddress - the source chain contract address
                                  function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);
                                  // @notice query if the _libraryAddress is valid for sending msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getSendLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the _libraryAddress is valid for receiving msgs.
                                  // @param _userApplication - the user app address on this EVM chain
                                  function getReceiveLibraryAddress(address _userApplication) external view returns (address);
                                  // @notice query if the non-reentrancy guard for send() is on
                                  // @return true if the guard is on. false otherwise
                                  function isSendingPayload() external view returns (bool);
                                  // @notice query if the non-reentrancy guard for receive() is on
                                  // @return true if the guard is on. false otherwise
                                  function isReceivingPayload() external view returns (bool);
                                  // @notice get the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _userApplication - the contract address of the user application
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  function getConfig(uint16 _version, uint16 _chainId, address _userApplication, uint _configType) external view returns (bytes memory);
                                  // @notice get the send() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getSendVersion(address _userApplication) external view returns (uint16);
                                  // @notice get the lzReceive() LayerZero messaging library version
                                  // @param _userApplication - the contract address of the user application
                                  function getReceiveVersion(address _userApplication) external view returns (uint16);
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroUserApplicationConfig {
                                  // @notice set the configuration of the LayerZero messaging library of the specified version
                                  // @param _version - messaging library version
                                  // @param _chainId - the chainId for the pending config change
                                  // @param _configType - type of configuration. every messaging library has its own convention.
                                  // @param _config - configuration in the bytes. can encode arbitrary content.
                                  function setConfig(uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config) external;
                                  // @notice set the send() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setSendVersion(uint16 _version) external;
                                  // @notice set the lzReceive() LayerZero messaging library version to _version
                                  // @param _version - new messaging library version
                                  function setReceiveVersion(uint16 _version) external;
                                  // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload
                                  // @param _srcChainId - the chainId of the source chain
                                  // @param _srcAddress - the contract address of the source contract at the source chain
                                  function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;
                              }
                              

                              File 16 of 16: TreasuryV2
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.7.6;
                              import "./interfaces/ILayerZeroTreasury.sol";
                              import "@openzeppelin/contracts/access/Ownable.sol";
                              import "@openzeppelin/contracts/math/SafeMath.sol";
                              import "./interfaces/ILayerZeroUltraLightNodeV2.sol";
                              contract TreasuryV2 is ILayerZeroTreasury, Ownable {
                                  using SafeMath for uint;
                                  uint public nativeBP;
                                  uint public zroFee;
                                  bool public feeEnabled;
                                  bool public zroEnabled;
                                  ILayerZeroUltraLightNodeV2 public uln;
                                  event NativeBP(uint bp);
                                  event ZroFee(uint zroFee);
                                  event FeeEnabled(bool feeEnabled);
                                  event ZroEnabled(bool zroEnabled);
                                  constructor(address _ulnv2) {
                                      uln = ILayerZeroUltraLightNodeV2(_ulnv2);
                                  }
                                  function getFees(bool payInZro, uint relayerFee, uint oracleFee) external view override returns (uint) {
                                      if (feeEnabled) {
                                          if (payInZro) {
                                              require(zroEnabled, "LayerZero: ZRO is not enabled");
                                              return zroFee;
                                          } else {
                                              return relayerFee.add(oracleFee).mul(nativeBP).div(10000);
                                          }
                                      }
                                      return 0;
                                  }
                                  function setFeeEnabled(bool _feeEnabled) external onlyOwner {
                                      feeEnabled = _feeEnabled;
                                      emit FeeEnabled(_feeEnabled);
                                  }
                                  function setZroEnabled(bool _zroEnabled) external onlyOwner {
                                      zroEnabled = _zroEnabled;
                                      emit ZroEnabled(_zroEnabled);
                                  }
                                  function setNativeBP(uint _nativeBP) external onlyOwner {
                                      nativeBP = _nativeBP;
                                      emit NativeBP(_nativeBP);
                                  }
                                  function setZroFee(uint _zroFee) external onlyOwner {
                                      zroFee = _zroFee;
                                      emit ZroFee(_zroFee);
                                  }
                                  function withdrawZROFromULN(address _to, uint _amount) external onlyOwner {
                                      uln.withdrawZRO(_to, _amount);
                                  }
                                  function withdrawNativeFromULN(address payable _to, uint _amount) external onlyOwner {
                                      uln.withdrawNative(_to, _amount);
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.5.0;
                              interface ILayerZeroTreasury {
                                  function getFees(bool payInZro, uint relayerFee, uint oracleFee) external view returns (uint);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.7.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.7.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity >=0.7.0;
                              pragma abicoder v2;
                              interface ILayerZeroUltraLightNodeV2 {
                                  // Relayer functions
                                  function validateTransactionProof(uint16 _srcChainId, address _dstAddress, uint _gasLimit, bytes32 _lookupHash, bytes32 _blockData, bytes calldata _transactionProof) external;
                                  // an Oracle delivers the block data using updateHash()
                                  function updateHash(uint16 _srcChainId, bytes32 _lookupHash, uint _confirmations, bytes32 _blockData) external;
                                  // can only withdraw the receivable of the msg.sender
                                  function withdrawNative(address payable _to, uint _amount) external;
                                  function withdrawZRO(address _to, uint _amount) external;
                                  // view functions
                                  function getAppConfig(uint16 _remoteChainId, address _userApplicationAddress) external view returns (ApplicationConfiguration memory);
                                  function accruedNativeFee(address _address) external view returns (uint);
                                  struct ApplicationConfiguration {
                                      uint16 inboundProofLibraryVersion;
                                      uint64 inboundBlockConfirmations;
                                      address relayer;
                                      uint16 outboundProofType;
                                      uint64 outboundBlockConfirmations;
                                      address oracle;
                                  }
                                  event HashReceived(uint16 indexed srcChainId, address indexed oracle, bytes32 lookupHash, bytes32 blockData, uint confirmations);
                                  event RelayerParams(bytes adapterParams, uint16 outboundProofType);
                                  event Packet(bytes payload);
                                  event InvalidDst(uint16 indexed srcChainId, bytes srcAddress, address indexed dstAddress, uint64 nonce, bytes32 payloadHash);
                                  event PacketReceived(uint16 indexed srcChainId, bytes srcAddress, address indexed dstAddress, uint64 nonce, bytes32 payloadHash);
                                  event AppConfigUpdated(address indexed userApplication, uint indexed configType, bytes newConfig);
                                  event AddInboundProofLibraryForChain(uint16 indexed chainId, address lib);
                                  event EnableSupportedOutboundProof(uint16 indexed chainId, uint16 proofType);
                                  event SetChainAddressSize(uint16 indexed chainId, uint size);
                                  event SetDefaultConfigForChainId(uint16 indexed chainId, uint16 inboundProofLib, uint64 inboundBlockConfirm, address relayer, uint16 outboundProofType, uint64 outboundBlockConfirm, address oracle);
                                  event SetDefaultAdapterParamsForChainId(uint16 indexed chainId, uint16 indexed proofType, bytes adapterParams);
                                  event SetLayerZeroToken(address indexed tokenAddress);
                                  event SetRemoteUln(uint16 indexed chainId, bytes32 uln);
                                  event SetTreasury(address indexed treasuryAddress);
                                  event WithdrawZRO(address indexed msgSender, address indexed to, uint amount);
                                  event WithdrawNative(address indexed msgSender, address indexed to, uint amount);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <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 GSN 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 payable) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes memory) {
                                      this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                                      return msg.data;
                                  }
                              }