EstimateTransferTokensGas

Description

This function can be used to estimate the Gas Limit and Gas Price that will be required by a TransferTokens invocation. The information can be presented to users before they confirm the transaction.

Details

Signature

async EstimateTransferTokensGas(args, apiKey)

Arguments

Parameter
Type
Definition

args.to

String

Address to send tokens to.

args.amount

String

Amount to send in display units of the currency. So if you want the user to pay 0.5 ETH, pass in '0.5' to this field.

args.currency

Asset (class)

Asset object of the currency you want to send. You can pass a custom token here as well, please refer to the example below.

apiKey

String

Return Value

{
    "statusCode": 1/0,
    "data": {
        "estimatedGas": "estimatedGas", // the gas limit of the transaction in BigNumber
        "estimatedGasPrice": "estimatedGasPrice" // the gas price of the transaction in BigNumber
    }
    "error": "error" // error if any
}

Handling Large Numerical Values

The result of the estimation is returned in the BigNumber format. A conversion will need to be made to display the result in a human-readable format, and the following function can be used:

ConvertBigNumberToNumber(bigNumber, decimal) - Use this method while converting response values from a smart contract function call (which are in BigNumber format) to a JS Number.

Example

Calling TransferTokens for a native currency:

import { 
    TransferTokens,
    EstimateTransferTokensGas,
    ConvertBigNumberToNumber,
    assets
} from '@metafi/metafi-js-package';

function App() {

    const tx = {
        to: "0xd4594dECd0ed8BA4C7d5810dbB8D004C74250BD5",
        amount: "1",
        currency: assets.matic_matic, // use your custom token object here
    }

    // estimate gas fees
    const estimateGas = () => {
        const result = await EstimateTransferTokensGas(
            tx,
            "YOUR-API-KEY",
        );
        
        console.log(
            "gas fees are: ", 
            ConvertBigNumberToNumber(
                result.data.estimatedGas.mul(result.data.estimatedGasPrice)
            )
        );
    }
    
    // transfer tokens
    const transferTokens = () => {
        TransferTokens({
                ...tx,
                callback: (result) => {
                    console.log("callback result", result);
                },
            },
            "YOUR-API-KEY"
        );
    }
    
    return (
        <div>
            <button onClick={estimateGas}>Estimate Gas Fees</button>
	    <button onClick={transferTokens}>Transfer 1 Matic</button>
        </div>
    );
}

export default App;

Last updated