【发布时间】:2022-08-02 18:02:33
【问题描述】:
我是 Solidity 和 Ethers.js 的新手,所以如果有任何业余错误,那就是原因。
我正在尝试构建一个 dApp,它在我的智能合约上运行一个函数,检索从事件发出的数据,然后将其显示在我的前端。到目前为止,我已经让它在 Localhost 上运行。目前,MetaMask 连接到我的前端,但是当我尝试确认与合约的交易时它会引发错误。
创建函数(JS):
async function create() {
///Acquiring values
postBody = document.getElementById(\"in-1-pbd\").value;
postSubcat = document.getElementById(\"in-2-sc\").value;
console.log(postBody + \", \" + postSubcat);
///Connecting with Ethereum
await requestAccount()
if (typeof window.ethereum != \'undefined\') {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(blokracyAddress, Blokracy.abi, signer)
const transaction = await contract.createBallot(postSubcat, postBody)
await transaction.wait()
///Building and presenting the ballot
contract.on(\"Creation\", (message, idnum ) => {
console.log(\"Creation Event Data: \", message, idnum);
buildBallot(Wallet.publicKey, idnum, postBody);
});
} else {
window.alert(\"Non-Ethereum browser detected. You should consider installing MetaMask.\")
}
}
申请账户功能:
async function requestAccount() {
await window.ethereum.request({ method: \'eth_requestAccounts\' });
}
创建函数(Solidity):
///Event Declaration
event Creation(string message, uint idnum);
///Functionality
///Creating a Ballot:
function createBallot(
string memory _subcategory, string memory _post
) public {
///Set Operator
operator = msg.sender;
///Increment ballotNum
ballotNum ++;
///Apply specifics to ballot
ballot[ballotNum] = Ballot(
ballotNum, _subcategory, operator,
_post, 0, 0, 0, 0
);
///return string and ballotNum
emit Creation(\"Ballot was successfully posted!\", ballotNum);
}
任何洞察力都会令人惊叹。就像我说的,我是新手,并试图通过构建这个项目尽可能多地了解 dApp。
标签: javascript ethereum solidity metamask ethers.js