我有一个阈值和一些必须传递给智能契约的数据。智能契约使用这些数据进行决策。我在用web3js。如何将这些数据传递给智能契约?
发布于 2020-12-21 23:21:52
以我自己为例:
假设您与以下人员有智能合同:
与以下类似,还会发出一个事件来知道何时设置了新值:
uint globalValue;
function addinfo(uint calldata value) public {
globalValue = value;
emit NewValue(globalValue);
} 在智能契约中声明事件,以便浏览器应用程序接收到该事件:
event NewValue(
uint globalValue
);为了验证这个过程,让我们假设您还有一个getInfo()函数:
function getInfo() public view returns (uint memory) {
return globalValue;
} 在您的javascript文件中,对于浏览器应用程序,您将拥有:
var myabi = [COPY GENERATED ABI FROM YOUR CODE IN REMIX]
var contractAddress = '0x7f2cd0448d0a44c4d58a2c9593d6d109a181f023';
var mySmartContract;
var miAddress;
function init() {
if (typeof window.ethereum !== 'undefined') {
try {
window.ethereum.autoRefreshOnNetworkChange = false;
} catch (error) {
// User denied account access
console.log('User denied web3 access');
return;
}
web3 = new Web3(window.ethereum);
window.ethereum.enable();
}
else if (window.web3) {
// Deprecated web3 provider
web3 = new Web3(web3.currentProvider);
// no need to ask for permission
}
else {
console.log('No web3 provider detected');
return;
}
initContract();
}
function initContract() {
mySmartContract = new web3.eth.Contract(myabi,contractAddress);
console.log('Contract initialized OK');
//console.log(mySmartContract);
}
init();在浏览器中初始化web3和智能契约后,调用该函数:
var value = "foo";
mySmartContract.methods.addinfo(value).send({"from":myAddress})Metamask将提示您要求您提供天然气和交易细节的确认。
mySmartContract.events.NewValue({}, function(error, event) {
console.log(event);
})如果一切顺利,您可以在浏览器javascript应用程序中使用以下函数验证值(不需要气体):
mySmartContract.methods.getInfo().call().then(function(value){
console.log("The new value is:");
console.log(value);
});function _safeTransferFrom(
IERC20 token,
address sender,
address recipient,
uint amount
) private {
bool sent = token.transferFrom(sender, recipient, amount);
require(sent, "Token transfer failed");
}https://ethereum.stackexchange.com/questions/91390
复制相似问题