【问题标题】:Can a function in Solidity call another function within the contract?Solidity 中的函数可以调用合约中的另一个函数吗?
【发布时间】:2021-03-06 04:58:31
【问题描述】:

我对编程完全陌生,我正在尝试编写一个可以接收资金并通过函数将资金转移到其他地址的智能合约。 在我的代码中,我有一个修饰符,它定义了一个可以调用提取/转移函数的所有者。我已经定义了 3 个地址变量,函数将 ETH 转移到其中。幸运的是,它可以按我的意愿工作。

pragma solidity ^0.7.0;

contract SubscriptionPayment {

// address variable defining the owner 
address public owner = msg.sender
;

// modifier that restricts access to the owner of contract
modifier onlyOwner{
    require(msg.sender == owner);
_;
}
// contract is able to handle ETH
receive() external payable{
}

// function to withdraw restricted to owner 
function withdraw(uint _value) external onlyOwner {
    msg.sender.transfer(_value)
;
}

// define address variables 
address payable public account1Address = 0xF6D461F87BBce30C9D03Ff7a8602156f006E2367 ;
address payable public account2Address = 0xb6a76127EDf7E0B7dfcEd9aDE73Fa8780eC26592 ;
address payable public account3Address = 0x722b95CA56b1C884f574BAE4832f053197Ca3F58 ;

// function to pay all subscriptions
function paySubscriptions() external onlyOwner {
    account1Address.transfer(1000000000000000000);
    account2Address.transfer(1000000000000000000);
    account3Address.transfer(2000000000000000000);
}

我的问题与 paySubscriptions 功能有关。有什么方法可以单独并按顺序执行到这 3 个地址的转移?当然,我可以只创建 3 个单独的函数来将 ETH 转移到每个地址,但这会给我 3 个单独的函数来调用。 是否可以编写代码,当调用一个函数时,从合约中调用另一个函数,当调用此函数时,从合约中调用另一个函数?如果是这样,我可以编写一个可以在外部调用的函数 1,并在调用/执行函数 1 后从合约中调用其他 2 个函数。

【问题讨论】:

    标签: function ethereum solidity contract


    【解决方案1】:

    为了更好地理解你的任务,写下如果智能合约可以用 Java 或其他语言编写,你将如何实现它

    【讨论】:

    • 很抱歉,我没有任何类型的编程能力。
    【解决方案2】:

    你冷做如下:

    定义一组地址和他们需要转移的金额:

    mapping (address => uint) public balances;
    address payable [] public subscribers;
    

    然后循环该映射为每个付款,例如:

     function paySubscribers() public{
           for (uint i=0; i<subscribers.length; i++) {
              address payable currAddress = subscribers[i];
              currAddress.transfer(balances[currAddress]);
          }
        
        }
    

    我建议您阅读这篇文章以获得更好的理解和更多的实践。

    Looping in solidity

    来自文章:

    在solidity中,映射对于存储一个token值非常有用 地址。我们在许多合同中都看到了它,它们通常是 这样定义:

    【讨论】:

      【解决方案3】:

      这是你想要的吗?

      function paySubscription(address receiverAddress, uint256 amount) external onlyOwner {
          receiverAddress.transfer(amount);
      
      }
      
      function payAllSubs(address[] memory receivers, uint256[] amounts) external onlyOwner {
             for (uint i=0; i<receivers.length; i++) {
                address currAddress = receivers[i];
                uint256 amt = amounts[i]
                this.paySubscription(currAddress, amt);
            }
          
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-25
        • 2023-01-29
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 2022-10-25
        • 2021-07-14
        • 2015-10-21
        • 2015-08-18
        相关资源
        最近更新 更多