Solidity 练习:New

2022-12-29 Web3 Solidity

# 一、题目说明

可以使用 new 关键字从一个合约创建一个新合约。下面给出被创建合约的内容。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract Account {
    address public bank;
    address public owner;
    uint public withdrawLimit;

    constructor(address _owner, uint _withdrawLimit) payable {
        bank = msg.sender;
        owner = _owner;
        withdrawLimit = _withdrawLimit;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 二、任务列表

  • 完成函数 createSavingsAccount,该函数将创建一个新的 Account 合约(withdrawLimit 为 1000)。
  • 将新创建的合约加入到 accounts 数组。

# 三、解答代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "./Account.sol";

contract Bank {
    Account[] public accounts;

    function createAccount(address _owner) external {
        Account account = new Account(_owner, 0);
        accounts.push(account);
    }

    function createAccountAndSendEther(address _owner) external payable {
        Account account = (new Account){value: msg.value}(_owner, 0);
        accounts.push(account);
    }

    function createSavingsAccount(address _owner) external {
        Account account = new Account(_owner, 1000);
        accounts.push(account);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 四、参考资料

Last Updated: 2023-01-28 4:31:25