I want to make a contract with function that will deploy other contract while it called. Is it possible? Any ideas?
Here's an example of a contract that deploys contracts.
https://ethereum.stackexchange.com/questions/13415/is-there-a-simple-contract-factory-pattern
Hope it helps.
Let's say you have this Test contract.
contract Test{
address public owner=msg.sender;
// since this contract is deployed by another contract, that contract will be the owner of
function setOwner(address _owner) public {
require(msg.sender==owner,"not owner");
owner=_owner;
}
}
Write a Deployer contract. pass the bytecode of above contract to the deploy
function. to get the bytecode call getByteCode()
and copy the bytecode from Remix
contract Deployer{
// we need bytecode to deploy a contract
function deploy(bytes memory _bytecode) external payable returns (address addr){
assembly{
// we cannot access to msg.value here. we use `callvalue()`
// when code is loaded first 32 bytes encodes the length of the code. actual code starts after 32 bytes. 0x20=32 in hexadecimal
// the size of the code is stored in the first 32 bytes
addr := create(callvalue(), add(_bytecode,0x20),mload(_bytecode))
// we get the address and load contract using address in remix
}
// zero address means that there was an error creating the code
require(addr !=address(0),'deploy failed');
}
function getByteCode() external pure returns (bytes memory){
bytes memory bytecode=type(Test).creationCode;
return bytecode;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.