This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of Solidity.
The purpose of building this blog is to write down the detailed operation history and my memo for learning the dApps.
If you are also interested and want to get hands dirty, just follow these steps below and have fun!~
Prerequisites
Getting started
First we create a contract named Account:
// SPDX-License-Identifier:MIT
// Adjust your own solc
pragma solidity ^0.8.14;
contract Account {
address public bank;
address public owner;
constructor (address _owner) payable {
bank = msg.sender;
owner = _owner;
}
}
This contract
Account
has two state variablesbank
andowner
and uses apayable
constructor to initialize state variableowner
.
We will be using another contract called AccountFactory to deploy contract Account.
...
contract AccountFactory {
Account[] public accounts;
function createAccount(address _owner) external payable {
Account account = new Account{value: 111}(_owner);
accounts.push(account);
}
}
The whole contract New.Sol:
// SPDX-License-Identifier:MIT
// Adjust your own solc
pragma solidity ^0.8.14;
contract Account {
address public bank;
address public owner;
constructor (address _owner) payable {
bank = msg.sender;
owner = _owner;
}
}
contract AccountFactory {
Account[] public accounts;
function createAccount(address _owner) external payable {
Account account = new Account{value: 111}(_owner);
accounts.push(account);
}
}
We created an Account array
accounts
. When we deploy a new contract (using contract Account), we name it account and send 111 wei to this contract and push it intoaccounts
. We make functioncreateAccount
payable since we want the newly created contract receive ETH.
Now time to use Remix to deploy and test our smart contract.
Select contract AccountFactory and click Deploy to deploy it.
Paste the current account address (address(0)) along with 200 Wei and click createAccount
.
Then if we input 0 to fetch accounts[0], we will get the contract address that we have just deployed:
Let's copy this contract address(accounts[0]) and paste it into At Address and switch the contract to Account, and then click At Address:
We will get values transferred to state variable bank
and owner
via constructor Account()
:
We can see the owner is the address who has created the contract accounts[0], and the bank is referred to the msg.sender, which is the address of contract AccountFactory.
Reference
https://www.youtube.com/watch?v=J2Wp2SHq1Qo&list=PLO5VPQH6OWdVQwpQfw9rZ67O6Pjfo6q-p&index=45
Top comments (0)