-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathtokenSplitter.sol
More file actions
82 lines (67 loc) · 2.77 KB
/
Copy pathtokenSplitter.sol
File metadata and controls
82 lines (67 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
import "@nilfoundation/smart-contracts/contracts/Nil.sol";
import "@nilfoundation/smart-contracts/contracts/NilTokenBase.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title TokenSplitter
* @notice Distributes received =nil; native tokens (identified by TokenId) to multiple recipients across different shards asynchronously.
* @dev expects tokens to be transferred to this contract *while* calling splitTokens.
* @dev Inherits NilTokenBase primarily for convenient access to sendTokenInternal.
*/
contract TokenSplitter is NilBase, NilTokenBase, Ownable, ReentrancyGuard {
event TokensSplit(
TokenId indexed tokenId,
uint256 totalAmount,
uint256 numRecipients
);
event AsyncTransferInitiated(
TokenId indexed tokenId,
uint256 indexed shardId,
address indexed recipient,
uint256 amount
);
//Error messages
error InvalidAmount();
error InvalidRecipientAddress();
error InvalidTokenId();
error InsufficientTokenBalance();
error ArrayLengthMismatch();
error NoRecipientsSpecified();
receive() external payable {}
constructor() Ownable(msg.sender) {}
function splitTokens(
TokenId _tokenId,
address[] calldata _recipients,
uint256[] calldata _amounts
) external payable nonReentrant {
if (_recipients.length == 0) revert NoRecipientsSpecified();
if (_recipients.length != _amounts.length) revert ArrayLengthMismatch();
Nil.Token[] memory tokens = Nil.txnTokens(); // TODO: [PoC] Tokens remove it
uint256 totalAmountToSend = 0;
for (uint256 i = 0; i < _amounts.length; i++) {
if (_amounts[i] <= 0) revert InvalidAmount();
totalAmountToSend += _amounts[i];
}
if (tokens[0].amount < totalAmountToSend)
revert InsufficientTokenBalance();
for (uint256 i = 0; i < _recipients.length; i++) {
address recipient = _recipients[i];
if (_recipients[i] == address(0)) revert InvalidRecipientAddress();
uint256 amount = _amounts[i];
uint256 shardId = Nil.getShardId(recipient);
sendTokenInternal(recipient, _tokenId, amount);
emit AsyncTransferInitiated(_tokenId, shardId, recipient, amount);
}
emit TokensSplit(_tokenId, totalAmountToSend, _recipients.length);
}
function withdrawStuckTokens(
TokenId _tokenId,
address _to
) external onlyOwner {
uint256 balance = Nil.tokenBalance(address(this), _tokenId);
if (balance == 0) revert InsufficientTokenBalance();
sendTokenInternal(_to, _tokenId, balance);
}
}