【发布时间】:2022-07-08 05:54:44
【问题描述】:
我想在我部署的智能合约中调用应付函数,但它不起作用。这是我得到的错误:
错误:返回错误:方法 eth_sendTransaction 不存在/不可用
我能找到的答案是只使用私钥,因为 infura 不支持这种方法,但是我希望用户使用 MetaMask 签署智能合约的交易。
这是我的代码:
export async function helloworld() {
const rpcURL =
"https://ropsten.infura.io/v3/KEY";
const web3 = new Web3(rpcURL);
let provider = window.ethereum;
if (typeof provider !== "undefined") {
provider
.request({ method: "eth_requestAccounts" })
.then((accounts) => {
selectedAccount = accounts[0];
console.log(`Selected account is ${selectedAccount}`);
})
.catch((err) => {
console.log(err);
return;
});
window.ethereum.on("accountsChanged", function (accounts) {
selectedAccount = accounts[0];
console.log(`Selected account changed to ${selectedAccount}`);
});
}
const networkId = await web3.eth.net.getId();
const thecontract = new web3.eth.Contract(
simpleContractAbi,
"0x50A404efF9A057900f87ad0E0dEfA0D485931464"
);
isInitialized = true;
investit(thecontract, selectedAccount);
}
这是实际引发错误的代码:
export const investit = async (thecontract, selectedAccount) => {
if (!isInitialized) {
await helloworld();
}
thecontract.methods
.invest()
.send({ from: selectedAccount, value: 10000 })
.catch(function (err) {
console.log(err);
});
};
我完全迷路了,因为如果我使用普通的window.ethereum.request (https://docs.metamask.io/guide/sending-transactions.html#example) 发送交易,元掩码会打开,我可以签名。使用合约调用它根本不起作用。
你知道原因吗?我该如何解决这个问题?
【问题讨论】:
-
你连接到 infura 了吗?你如何连接到你的合约部署的区块链
-
@Yilmaz 是的,正如您在第一个代码示例开头看到的那样,我已连接到 infura
标签: javascript reactjs solidity web3js