[英]How to get an unsigned transaction data from web3.py using contract interaction
[英]How to make transactions using web3.py from any account?
我在后端使用Flask并为我的区块链项目使用ganache 。 我也在使用Metamask 。 我的智能合约在混音网站上。 这是我的合同:
pragma solidity ^0.4.21;
contract Election{
struct Candidate {
uint voteCount;
string name;
}
struct voter {
bool authorized;
bool voted;
uint vote;
}
address public owner;
string public electionName;
mapping(address => voter) public voters;
Candidate[] public candidates;
uint public totalVotes;
modifier ownerOnly() {
require(msg.sender == owner);
_;
}
constructor(string _name) public {
owner = msg.sender;
electionName = _name;
}
function addCandidate(string _name) ownerOnly public {
candidates.push(Candidate(0, _name));
}
function getNumCandidates() public view returns(uint) {
return candidates.length;
}
function authorize(address _person) ownerOnly public {
voters[_person].authorized = true;
}
function vote(uint _voteIndex) public {
require(!voters[msg.sender].voted);
require(voters[msg.sender].authorized);
voters[msg.sender].vote = _voteIndex;
voters[msg.sender].voted = true;
candidates[_voteIndex].voteCount += 1;
totalVotes += 1;
}
function end() ownerOnly public {
selfdestruct(owner);
}
}
我遇到了投票function 的问题。 当我在混音网站上部署后运行整个合同时,它工作正常。 但是,当我从基于 flask 的应用程序进行交易时,即使在选民名单中有选民之后也会出现还原错误。 因此,我想使用元掩码进行投票交易。 我使用默认帐户部署合同。
w3 = Web3(HTTPProvider('http://127.0.0.1:7545'))
w3.eth.defaultAccount = w3.eth.accounts[0]
contract = w3.eth.contract(address=address, abi=data["abi"])
tx_hash = contract.functions.vote(candidate_index).transact()
w3.eth.wait_for_transaction_receipt(tx_hash)
现在我想从我在 Metamask 中选择的帐户进行交易。 因为上面的方法行不通。 有什么方法或例子可以做到吗? 我还访问了 metamask 文档,其中建议使用ethereum.request() 。 但是我无法在 web3py 中实现它。
你的代码是正确的。 vote
中有 2 个要求声明。 我认为这就是您收到错误的原因。 您可以将自定义消息添加到require
函数,以便查看是哪一个导致了错误:
require(!voters[msg.sender].voted,"You already voted");
require(voters[msg.sender].authorized,"You are not authorized");
我相信,由于您已经使用默认帐户进行了vote
,因此您没有通过第一个require
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.