![](/img/trans.png)
[英]call a public function with another function in the same contract in solidity
[英]Can a function in Solidity call another function within the contract?
我對編程完全陌生,我正在嘗試編寫一個可以接收資金並通過函數將它們轉移到其他地址的智能合約。 在我的代碼中,我有一個修飾符,它定義了一個可以調用提款/轉移函數的所有者。 我定義了 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 個函數。
為了更好地理解你的任務,如果智能合約可以用 Java 或其他語言編寫,你將如何實現它
你冷做如下:
定義一組地址以及它們需要轉移的金額:
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]);
}
}
我建議你閱讀這篇文章以獲得更好的理解和更多的練習。
從文章:
在 Solidity 中,映射對於存儲地址的令牌值非常有用。 我們已經在許多合約中看到它,它們通常是這樣定義的:
這是你想要的嗎?
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.