我正在尝试创建一个新的合同实例,但它不起作用。
contract Campaign {
struct Promotion {
string description;
uint max_influencer;
uint jobvalue;
bool achievement;
}
address[] public deployedPromotions;
uint budget = msg.value;
function createPromotion(string description, uint max_influencer) public payable {
address newPromotion = new Promotion(description, budget, max_influencer);
deployedPromotions.push(newPromotion);
newPromotion.transfer(budget);
}
}
你的代码有几个逻辑逻辑错误:
-
如果您想将
Promotion
合约部署到新地址,则需要将其定义为单独的合约-而不是struct
。 -
赋值
uint budget = <some value>;
只赋变量定义时的值。因此,如果您想使用msg.value
作为createPromotion()
作用域的一部分,则需要在函数内赋值。
其他较小的问题在代码注释
中指出。pragma solidity ^0.8;
contract Promotion {
string description;
uint max_influencer;
uint jobvalue;
bool achievement;
// since you're passing 3 values from the `createPromotion()`
// the constructor also receives 3 values here
// it also needs to be `payable` to accept native tokens in the constructor
constructor(string memory _description, uint _budget, uint _max_influencer) payable {
description = _description;
max_influencer = _max_influencer;
}
// the contract needs to have the `receive()` function to accept native tokens
receive() external payable {
}
}
// This is the main contract
contract Campaign {
address[] public deployedPromotions;
uint budget;
// don't forget about the data location (in this case `memory`) with reference types
function createPromotion(string memory description, uint max_influencer) public payable{
budget = msg.value; // moved the assigning here
address newPromotion = address(new Promotion(description, budget, max_influencer));
deployedPromotions.push(newPromotion);
payable(newPromotion).transfer(budget); // address needs to be `payable` to accept native tokens
}
}