Nate Lapinski

Photo by Kanchanara on Unsplash

In this quick post, I’ll show how to set msg.value when calling an arbitrary method on a contract in ethers.js

tl;dr

Follow this pattern, assuming the contract MyContract has a payable method called myMethod :

// ...ethersjs contract factory setupconst MyContract = new ethers.ContractFactory(
// abi and bytecode and signer vals
);
const myContract = await MyContract.deploy();
await myContract.deployed();
// calls myMethod and send along 1 ether as msg.value
await.myContract.myMethod("some random arg", {value: ethers.utils.parseEther("1.0")});

Note that in the call to myMethod the very last argument we passed was an object containing a value property:

{value: ethers.utils.parseEther("1.0")}

You can see that this optional final param is referred to as overrides in the etherjs documentation. This can be very useful when you need to send along some ether as part of a contract call.

Thanks for reading!

--

--

Nate Lapinski

Nate Lapinski

Fullstack Developer. Love digging into the internals of stuff. Always trying to reach the next level. @nate_lapinski on Twitter. Writer for AngularInDepth.