I am a new developer, working on a smart contract mostly for my own learning. I am developing a Smart Contract to handle subscriptions. The contract has the below features.
- Subscribers can subscribe to other public addresses and deposit ether into their account.
- Producers (people you subscribe to) can execute a charge function, which will loop though all of their subscriptions, calculate the payout, deduct the payout from subscriber accounts and send the ether to the person calling the function.
Here is a snippet of my code:
function charge() external {
uint payout;
uint service;
Producer storage producer = producers[msg.sender];
// calculate payout
for (uint i = 0; i < producer.subscribers.length; i++) {
// get subscriber
address subscriberAddress = producer.subscribers[i].account;
Subscriber storage subscriber = subscribers[subscriberAddress];
//check balance
if (subscriber.balance >= weeklyCharge) {
subscriber.balance -= weeklyCharge + serviceCharge;
payout += weeklyCharge;
service += serviceCharge;
}
}
// send total ETH to producer address
producer.lastPayment = now;
msg.sender.transfer(payout);
serviceAddress.transfer(serviceCharge);
Charged(msg.sender, payout, service);
}
I am leaving out some details for simplicity's sake. The full code is here: https://github.com/cseale/patrecoin/blob/master/smart-contracts/contracts/Subscriptions.sol.
This charge function seems to me to potentially be a very expensive function, if someone had, let's say, 1M subscribers.
Can anyone advise me on how I might make this function more efficient, or design my smart contracts in a better way?
EDIT: One restriction. I want to put the control for charging into the hands of the person calling the charge function. If I invert the payment control to the subscribers, there is no point in the contract. I want to set up this accounting system to track payments and ensure a certain revenue flow for what I call the "Producer"