I'm working on a smart contract that allows users to subscribe to different Plans.
I have a nested mapping that returns a struct(Subscription). I wanted to create a function that returns all the subscriptions that exist in a specific plan(0,1,2..).
The function that I wrote doesn't return all structs it returns only the first one after that it returns only zeros.
totalSubscriptions increase when a new user creates a new subscription.
address[] allSubcribers contains all the addresses of subscribers.
currentId represents the id of the plan that a subscriber signed up for.
struct Subscription {
address subscriber;
uint start;
uint nextPayment;
}
mapping(address => mapping(uint => Subscription)) public subscriptions;
function getAllsubscriptions() external view returns (Subscription[] memory) {
Subscription[] memory items = new Subscription[](totalLoans);
for(uint256 i = 0; i < totalSubscriptions; i++) {
uint256 currentId = i;
LoanRequest storage currentItem = subscriptions[allSubcribers[currentId]][currentId];
items[currentId] = currentItem;
currentId += 1;
}
return items;
}
What do you think?
Best Answer
To help you, I wrote a contract with functions that can return list of all addresses subscribed to a specific subscription plan (0,1,2 ....) + other functions like deleteUser(),subscribeUser() etc.
It's example of how you can do it all without for loops (you instead use mapping to remember "index")
This is a simple example where every user only has a single subscription, but it can be modified such that a single user has as many subscriptions as you wish. But I tried to keep it simple/redable so as to not overwhelm you.
Hope it helps.
EDIT: Considering you said the first answer did not suit your needs, I just tried to fix your code (What is a bit tricky as we don't have entire contract so I have to guess some stuff)
I think your issue was mixing unit currentIndex vs unit currentId, you seem to be using both instead only one of those variables.
Below is adapted version of your code.
EDIT2: Second version of contract (Here for simplicity I assumed every user only has a single Subscription + subscriptionID cant be Zero)