nahmii-community / bridge

The Nahmii gateway, for bridging assets between L1 <-> L2.
1 stars 2 forks source link

Maximum ETH in UX ignores gas fee #12

Closed HDauven closed 2 years ago

HDauven commented 3 years ago

Problem description

When a user fills in the maximum allowed amount in the amount field in the bridge view, the deposit cannot be executed due to there not being any ETH left for gas. It's only possible to reject the transaction and start over with a lower amount.

Expected behaviour

Catch this issue earlier by taking into account gas pricing. The amount a user deposits is the deposit + gas fee.

HDauven commented 2 years ago

There are two types of deposits for the Nahmii 2.0 bridge contract: ETH deposits and ERC20 deposits.

To calculate the to subtract gas fee, two values are required: The current gas price and the gas limit. Gas price can be requested from the Web3 provider.

Gas limits are a different story. For the depositing of ETH, the gas limit ends up being 215537 gas. ERC20s are dependent on the transfer function implementation. After a couple of test runs, the range is between 245468 and 345961 gas. Either a safe limit can be set to reduce API calls (375k?) or the estimateGas function can be called to get a calculated safe estimate.

HDauven commented 2 years ago

Problem description: When a user wants to deposit their full balance (ETH or any other native currency), the gas fee needs to be taken into account.

Knowns:

Caveats: EIP-1559 introduces a more complicated fee structure but also provides more metadata. Prior to EIP-1559, a dApp would only have to request the gas price and multiple it by the gas limit or request a guess estimate. The guess estimate operation would do the prior mentioned steps (price * limit) but with a lower precision.

A new function is introduced that provides fee data. This fee data consists of the gas price (same as before), the max fee per gas and the max priority fee per gas. The max fee per gas is the absolute maximum one can pay per unit of gas, whilst the max priority fee per gas is known as the 'miner tip'. This miner tip is there to incentive quicker inclusion/prioritization of a transaction.

Flows: A user has enough funds to cover the cost: Take the known gas limit and multiply it by the max fee per gas. Subtract this value, plus the amount they want to deposit, from their balance. If the result is greater than zero, the user has enough funds to deposit.

If the result is below zero, the user might be tight on funds.

A user might be tight on funds: Take the gas price and add the priority fee to it (Might need some extra headroom), multiply the resulting number by the gas limit. This value would be the base gas cost. Subtract the base gas cost from the users balance/requested amount to bridge (in this instance, it would be the same value). If the resulting value is negative, a user does not have enough funds to deposit. If it is positive, the user has enough funds.