0

I have a script which calls a smart contract method swapExactinputSingle(amtIn). I want to make sure that once this particular method call is successful, then only the code lines to print updated balances should run. I tried using the following approach:

   const singleSwap = new ethers.Contract(
      singleSwapAddress,
      swapjson.abi,
      provider
   );

// ... ... ...

   const transaction = await singleSwap
      .connect(accounts[0])
      .swapExactInputSingle(amtIn, {
         gasLimit: 270000,
      }); // swapExactInputSingle() is the contract function.

   console.log(transaction.hash);  // works fine

   const receipt = await provider.getTransactionReceipt(transaction.hash);  // receipt comes null.

   if (receipt) {
      console.log(   // print updated balances.
         "WMATIC balance after single swap: ",
         await wmatic.balanceOf(accounts[0].address)
      );
   }

In above code, the receipt value comes as null. Also if I directly print the updated balances right after calling the contract method swapExactinputSingle(), then it prints old balances instead of updated ones. However, I want to print updated balances only after the method call transaction gets mined and updated on blockchain. How to solve this issue?

1 Answer 1

4

Anyways, I got the solution myself. We can use transaction.wait().then() to do so. Here is the code:

       const transaction = await singleSwap
          .connect(accounts[0])
          .swapExactInputSingle(amtIn, {
             gasLimit: 270000,
          }); // call contract function.
    
       transaction.wait().then(async (receipt) => {
          // console.log(receipt);
          if (receipt && receipt.status == 1) {
             // transaction success.
             console.log(
                "WMATIC balance after single swap: ",
                await wmatic.balanceOf(accounts[0].address)  // print updated balances.
             );
          }
       });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.