I want stop listening metamask transaction event after getting transaction hash.
This is my code.
const transaction = await contract.methods
.contractMethod(value)
.send({ from: address, value: ethValue })
.on("transactionHash", async (txhash: string) => {
return txHash
})
I want to stop listening a transaction after transactionHash
,
however this code listen until transaction is confirmed.
Is there any way to stop listening transaction event after getting transaction hash?
Also, this is my related code with this problem.
<template>
....
</template>
import { sendTransaction } from "@/utils/trancaction";
export default defineComponent({
name: "Form",
setup() {
const state = reactive<{
ethValue: any;
modal: boolean;
error: {
ethValue: string;
};
}>({
ethValue: 0,
boolean: true,
error: {
ethValue: ""
}
});
const confirm = async () => {
const transactionHash = await sendTransaction(state.icbValue, state.ethValue);
console.log(2, transactionHash);
state.modal = false;
};
return {
confirm,
};
}
});
</script>
And I tried three different ways.
import { contractAbi } from "./contract-abi";
import Web3 from "web3";
export const sendTransaction = async (icbValue: number, ethValue: number) => {
await window.ethereum.enable().catch((error: any) => {
console.log(error);
});
const web3 = new Web3(Web3.givenProvider);
const accounts = await web3.eth.getAccounts();
const address = accounts[0];
const contract = await new web3.eth.Contract(contractAbi, "0xa8f6D9A3bF52941691604b0f76455b41c9f3Fc60");
// 1. using once with methods
const transaction = await contract.methods
.contractMethod(value)
.send({ from: address, value: ethValue })
.once("transactionHash", async (txhash: string) => {
return txHash
})
// 2. using callback with sendTrancsaction
const trancactionHash = await web3.eth.sendTransaction(
{
from: address,
to: "contract address",
value: ethValue,
data: functionData // deploying a contracrt
})
.once("transactionHash", function(hash) {
console.log("hash", hash);
return;
})
// 3. using callback with sendTrancsaction
const functionData = await contract.methods
.contractMethod(value)
.encodeABI({ from: address, value: ethValue });
const trancactionHash = await web3.eth.sendTransaction(
{
from: address,
to: "contract address",
value: ethValue,
data: functionData // deploying a contracrt
},
function(error, hash) {
console.log("hash", hash);
return hash;
}
);
};