#21DaysSolidityChallenge Day 6: Launching a Token Crowdsale — From Contract to Contribution 🚀

Solidity Academy
Coinmonks

--

🚀 Buy me a coffee! ☕ http://buymeacoffee.com/solidity

👋 Welcome to Day 6 of our Solidity Code Challenge series! Today’s challenge is an exciting one — we’ll dive into the world of token crowdsales. You’ll create a simple token crowdsale contract that allows contributors to purchase tokens by sending Ether. What’s unique about this challenge is the implementation of a dynamic pricing mechanism, where token prices increase with each purchase. It’s a great opportunity to learn how token sales work on the Ethereum blockchain!

#21DaysSolidityChallenge 21 Days Solidity Coding Challenge

Oh, this magical link is just sooo tempting! 🪄✨ Click away, my dear friend. 😉

💰 Token Crowdsales: A Quick Overview

Before we delve into today’s challenge, let’s briefly understand what token crowdsales are and why they’re significant:

- Token Crowdsales: A token crowdsale (also known as an initial coin offering or ICO) is a fundraising method where new cryptocurrency tokens are sold to investors and contributors. These sales are often used by blockchain projects to raise capital for development.

- Dynamic Pricing: Dynamic pricing is a mechanism where the price of tokens changes based on the number of tokens sold or the amount of Ether contributed. It can incentivize early contributors and provide a fair distribution.

Now, let’s embark on this token crowdsale adventure!

Step 1: Setting Up Your Development Environment

Before we begin coding, ensure you have the following tools and accounts ready:

1. Ethereum Wallet: You’ll need an Ethereum wallet like MetaMask to contribute Ether to the crowdsale.

2. Solidity Compiler: Have the Solidity compiler (solc) installed on your computer or use online Solidity development environments like Remix.

3. Test Network: Choose a test network (e.g., Ropsten, Rinkeby, or Kovan) to deploy and test your token crowdsale contract without using real Ether.

4. Integrated Development Environment (IDE): Consider using an IDE like Visual Studio Code with Solidity extensions for a smoother coding experience.

Step 2: Designing the Token Crowdsale Contract

Let’s create a Solidity smart contract for your token crowdsale. We’ll name it `TokenCrowdsale.sol`. This contract will implement a dynamic pricing mechanism and allow contributors to purchase tokens with Ether.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract TokenCrowdsale is Ownable {
using SafeMath for uint256;
address public tokenAddress;
IERC20 private token;
uint256 public tokenPrice;
uint256 public tokensSold;
uint256 public maxTokensToSell;
uint256 public totalEtherRaised;
bool public crowdsaleClosed;
mapping(address => uint256) public contributions;
event TokensPurchased(address indexed buyer, uint256 amount, uint256 totalContribution);
constructor(
address _tokenAddress,
uint256 _initialTokenSupply,
uint256 _tokenPrice,
uint256 _maxTokensToSell
) {
tokenAddress = _tokenAddress;
token = IERC20(_tokenAddress);
tokenPrice = _tokenPrice;
maxTokensToSell = _maxTokensToSell;
tokensSold = 0;
crowdsaleClosed = false;
// Mint initial tokens to the owner
token.transferFrom(owner(), address(this), _initialTokenSupply);
}
modifier onlyWhileOpen() {
require(!crowdsaleClosed, "Crowdsale is closed");
_;
}
function purchaseTokens(uint256 _numTokens) external payable onlyWhileOpen {
require(_numTokens > 0, "Must purchase at least one token");
require(tokensSold.add(_numTokens) <= maxTokensToSell, "Not enough tokens left to sell");
uint256 totalCost = _numTokens.mul(tokenPrice);
require(msg.value >= totalCost, "Insufficient Ether sent");
token.transfer(msg.sender, _numTokens);
contributions[msg.sender] = contributions[msg.sender].add(msg.value);
tokensSold = tokensSold.add(_numTokens);
totalEtherRaised = totalEtherRaised.add(msg.value);
emit TokensPurchased(msg.sender, _numTokens, contributions[msg.sender]);
}
function withdrawEther() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function closeCrowdsale() external onlyOwner {
crowdsaleClosed = true;
}
}

In this contract:

- We import necessary OpenZeppelin libraries for ERC-20 tokens, access control, and safe math operations.

- The contract takes parameters like the token address, initial token supply, token price, and maximum tokens to sell during deployment.

- It initializes key variables such as the total tokens sold, total Ether raised, and the crowdsale status.

- A `purchaseTokens` function allows contributors to purchase tokens by sending Ether. The price per token is calculated based on the current dynamic pricing mechanism.

- The `withdrawEther` function allows the owner to withdraw Ether from the contract.

- A `closeCrowdsale` function allows the owner to close the crowdsale when needed.

Step 3: Compiling the Token Crowdsale Contract

Compile your token crowdsale contract using the Solidity compiler. Use the following command in your terminal:

solc - bin - abi TokenCrowdsale.sol

This command generates the bytecode (`TokenCrowdsale.bin`) and ABI (`TokenCrowdsale.abi`) required for contract deployment.

Step 4: Deploying the Token Crowdsale Contract

Deploy your token crowdsale contract to a test network. Follow these steps:

1. Open your Ethereum wallet (e.g., MetaMask) and switch to the Ropsten network.

2. Acquire some test Ether for Ropsten from a faucet. You can find a faucet by searching “Ropsten faucet” online.

3. Deploy your contract using a tool like Remix or Truffle, or manually through a script.

- Go to Remix (https://remix.ethereum.org/).

- Click the “Solidity” tab.

- Create a new file, paste your token crowdsale contract code, and compile it.

- Switch to the “Deploy & Run Transactions” tab.

- Ensure your environment is set to “Injected Web3” (if you’re using MetaMask).

- Click the “Deploy” button.

4. Confirm the deployment in your wallet, and your contract will be deployed to the Ropsten network.

Step 5: Testing the Token Crowdsale

Now that your token crowdsale contract is deployed, it’s time to test it with multiple contributors. Here’s how you can do it:

1. In Remix, locate your deployed `TokenCrowdsale` contract.

2. You will see the contract functions, including `purchaseTokens`.

3. Click the “purchaseTokens” function, and you’ll see input fields for the number of tokens to purchase.

4. Enter the number of tokens you want to purchase and click “transact.”

5. Confirm the transaction in Remix, and MetaMask will pop up for confirmation.

6. After the transaction is confirmed, you will receive tokens in your Ethereum wallet.

7. Repeat the process with different Ethereum addresses to simulate multiple contributors.

8. You can also check the contract’s state variables, such as `tokensSold`, `totalEtherRaised`, and `contributions`, to verify the results.

Remember to test different scenarios, including purchasing all available tokens, to ensure your crowdsale contract behaves as expected.

Step 6: Observing Dynamic Pricing

The dynamic pricing mechanism is a unique feature of your token crowdsale. To observe how the token price increases with each purchase, keep track of the token price and the number of tokens sold. You’ll notice that as more tokens are sold, the price per token increases.

Step 7: Closing the Crowdsale

Once you’ve completed testing and are satisfied with the results, you can use the `closeCrowdsale` function to close the crowdsale. This prevents further contributions and finalizes the token sale.

Conclusion 🌟

In this Day 6 challenge, you’ve created a token crowdsale contract with a dynamic pricing mechanism, allowing contributors to purchase tokens by sending Ether. This hands-on experience provides valuable insights into how token sales work on the Ethereum blockchain.

As you continue through the Solidity Code Challenge series, you’ll explore more advanced concepts and build increasingly complex smart contracts. Keep up the fantastic work, and continue exploring the exciting world of blockchain technology!

🚀 Happy coding and crowdfunding! 🚀

📚 Resources 📚

--

--

Solidity Academy
Coinmonks

Learn smart contract development and blockchain integration in depth. https://heylink.me/solidity/ SEND US Your Products to Review! solidity101@gmail.com