Similar question, in need of something simpler
Specs:
- Each time a user interacts with my contract, I want to deposit 100 USDC into Spirals
- tokens should be locked for at least 30 days
- deposited tokens will always be associated to the contract (not the user)
I am thinking to do this using a Batch
struct that keeps track of the timestamp the batch will be unlocked and its amount.
Question: Is there a better way to do this? Ideally without using loops.
Current pseudocode solution:
struct Batch {
uint256 withdrawableTimestamp;
uint256 amount;
}
contract Depositor {
Batch[] public batches;
function triggerDeposit() external{
// deposit 100 USDC
SpiralsImpactVault(0x123).deposit(10 * 10 ** 18);
// Add a new batch specifying the unlock date and the amount
batches.push(Batch(block.timestamp + 30 days, 10 * 10 ** 18));
}
function withdraw() external onlyOwner {
// withdraw all that is withdrawable
uint256 withdrawableAmount = withdrawable();
SpiralsImpactVault(0x123).withdraw(withdrawableAmount);
// update the batches array by popping the first elements,
// until `block.timestamp >= batches[i].withdrawableTimestamp`.
// this is the expensive bit.
...
}
function withdrawable() public view returns (uint256) {
uint256 withdrawableAmount = 0;
// loop in the array, summing all batches with a past timestamp
for (uint256 i=0; i < batches.length; ++i) {
if (block.timestamp >= batches[i].withdrawableTimestamp) {
withdrawableAmount += batches[i].amount;
} else {
break;
}
}
return withdrawableAmount ;
}
}