Here is a sample smart contract for token distribution on the Ethereum blockchain using the Solidity programming language. Then I explain each line.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract TokenDistribution {
address public owner;
mapping(address => uint256) public balances;
event TokensDistributed(address indexed to, uint256 amount);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can execute this function");
_;
}
function distributeTokens(address[] memory recipients, uint256[] memory amounts) public onlyOwner {
require(recipients.length == amounts.length, "Recipients and amounts arrays must have the same length");
for (uint256 i = 0; i < recipients.length; i++) {
balances[recipients[i]] += amounts[i];
emit TokensDistributed(recipients[i], amounts[i]);
}
}
function getBalance(address account) public view returns (uint256) {
return balances[account];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract TokenDistribution {
TokenDistribution
.address public owner;
owner
of type address
to store the address of the contract owner.mapping(address => uint256) public balances;
balances
that maps addresses to their token balances.event TokensDistributed(address indexed to, uint256 amount);
TokensDistributed
that logs the distribution of tokens.constructor() {
owner = msg.sender;
owner
variable to the address that deployed the contract.modifier onlyOwner() {
onlyOwner
to restrict access to certain functions.require(msg.sender == owner, "Only the owner can execute this function");
_
onlyOwner
modifier.function distributeTokens(address[] memory recipients, uint256[] memory amounts) public onlyOwner {
distributeTokens
that takes two arrays as parameters: recipients
and amounts
.require(recipients.length == amounts.length, "Recipients and amounts arrays must have the same length");
recipients
and amounts
arrays are equal. If not, it throws an error.for (uint256 i = 0; i < recipients.length; i++) {
recipients
array.balances[recipients[i]] += amounts[i];
emit TokensDistributed(recipients[i], amounts[i]);
TokensDistributed
event for each recipient.function getBalance(address account) public view returns (uint256) {
getBalance
that returns the token balance of a given account.return balances[account];