Ethers.js: Calling payable contract method with arguments

Created on 22 Jul 2019  路  4Comments  路  Source: ethers-io/ethers.js

I'm trying to execute trades on uniswap but I can't find how to call a payable method with arguments. I'm finding the documentation a little bit vague.

For example, in web3, it would be like this:
exchangeContract.methods.ethToTokenSwapOutput(tokens_bought, deadline).send({value: ethValue})

What would be the equivalent using ether.js ?

discussion

Most helpful comment

Heya!

The value is part of the overrides you pass in as an optional (n + 1)th parameter to the call. The syntax you are trying to use is more akin to how Solidity represents call overrides.

What you likely want is something like:

let overrides = {
    // To convert Ether to Wei:
    value: ethers.utils.parseEther("1.0")     // ether in this case MUST be a string

    // Or you can use Wei directly if you have that:
    // value: someBigNumber
    // value: 1234   // Note that using JavaScript numbers requires they are less than Number.MAX_SAFE_INTEGER
    // value: "1234567890"
    // value: "0x1234"

    // Or, promises are also supported:
    // value: provider.getBalance(addr)
};

// Pass in the overrides as the 3rd parameter to your 2-parameter function:
let tx = await exchangeContract.ethToTokenSwapOutput(tokens_bought, deadline, overrides);

For more on overrides, here is the documentation: https://docs.ethers.io/ethers.js/html/api-contract.html#overrides

Let me know if you still have any issues. :)

All 4 comments

Heya!

The value is part of the overrides you pass in as an optional (n + 1)th parameter to the call. The syntax you are trying to use is more akin to how Solidity represents call overrides.

What you likely want is something like:

let overrides = {
    // To convert Ether to Wei:
    value: ethers.utils.parseEther("1.0")     // ether in this case MUST be a string

    // Or you can use Wei directly if you have that:
    // value: someBigNumber
    // value: 1234   // Note that using JavaScript numbers requires they are less than Number.MAX_SAFE_INTEGER
    // value: "1234567890"
    // value: "0x1234"

    // Or, promises are also supported:
    // value: provider.getBalance(addr)
};

// Pass in the overrides as the 3rd parameter to your 2-parameter function:
let tx = await exchangeContract.ethToTokenSwapOutput(tokens_bought, deadline, overrides);

For more on overrides, here is the documentation: https://docs.ethers.io/ethers.js/html/api-contract.html#overrides

Let me know if you still have any issues. :)

Great explanation - big thanks Richard!

Closing now, but if you still have issues, please feel free to re-open. :)

Thanks!

Great! Thank you so much

Was this page helpful?
0 / 5 - 0 ratings