-
bitcoin $87959.907984 USD
1.34% -
ethereum $2920.497338 USD
3.04% -
tether $0.999775 USD
0.00% -
xrp $2.237324 USD
8.12% -
bnb $860.243768 USD
0.90% -
solana $138.089498 USD
5.43% -
usd-coin $0.999807 USD
0.01% -
tron $0.272801 USD
-1.53% -
dogecoin $0.150904 USD
2.96% -
cardano $0.421635 USD
1.97% -
hyperliquid $32.152445 USD
2.23% -
bitcoin-cash $533.301069 USD
-1.94% -
chainlink $12.953417 USD
2.68% -
unus-sed-leo $9.535951 USD
0.73% -
zcash $521.483386 USD
-2.87%
How to Write Your First Smart Contract with Solidity? (Step-by-Step Tutorial)
Set up Node.js, Truffle, and Ganache; write an ERC-20 token using OpenZeppelin; compile, deploy locally, and test via Truffle console and JavaScript.
Jan 17, 2026 at 12:00 am
Setting Up the Development Environment
1. Install Node.js and npm to manage dependencies required for Solidity tooling.
2. Use npm to install Truffle globally — a widely adopted development framework for Ethereum-based smart contracts.
3. Install Ganache as a personal blockchain for local testing; it provides private accounts with pre-funded ETH.
4. Configure a new Truffle project using truffle init to generate essential directories like contracts/, migrations/, and test/.
5. Verify installation integrity by running truffle version and confirming compatibility with Solidity compiler v0.8.x or higher.
Writing a Basic Token Contract
1. Create a new file named MyToken.sol inside the contracts/ folder.
2. Declare the Solidity version pragma: pragma solidity ^0.8.20; to ensure deterministic compilation behavior.
3. Import OpenZeppelin’s ERC-20 implementation: import '@openzeppelin/contracts/token/ERC-20/ERC-20.sol';
4. Define the contract inheritance: contract MyToken is ERC20 { ... } and initialize name, symbol, and total supply in the constructor.
5. Add a mint function restricted to the owner using onlyOwner modifier from OpenZeppelin’s AccessControl library.
Compiling and Deploying the Contract
1. Write a migration script in migrations/2_deploy_contracts.js to instantiate and deploy MyToken with 1 million tokens.
2. Run truffle compile to generate ABI and bytecode; confirm no syntax or version mismatch errors appear.
3. Launch Ganache and copy its RPC server URL (e.g., http://127.0.0.1:7545) into truffle-config.js under the development network.
4. Execute truffle migrate --network development to deploy the contract and record transaction hashes and contract addresses.
5. Confirm deployment success by checking Ganache’s transaction log and verifying the contract address appears in the console output.
Interacting via Truffle Console
1. Start the Truffle console connected to Ganache: truffle console --network development.
2. Fetch the deployed instance: let instance = await MyToken.deployed();
3. Query total supply using (await instance.totalSupply()).toString() — expect output matching the initial mint value.
4. Transfer tokens between accounts: await instance.transfer('0xAb8483F64d9C6d1EcF9b849Ae677dC320f55a1B5', '1000').
5. Validate balance changes with (await instance.balanceOf('0xAb8483F64d9C6d1EcF9b849Ae677dC320f55a1B5')).toString().
Testing with JavaScript
1. Create test/mytoken.js containing Mocha-style test cases for core functionality.
2. Use contract() to define test context and it() blocks to assert behavior like minting, transferring, and event emission.
3. Assert correct event logs with assert.equal(receipt.logs[0].event, 'Transfer') after calling transfer.
4. Test reversion conditions: attempt to transfer more than balance and verify revert is thrown using expectRevert utility.
5. Run tests with truffle test and confirm all assertions pass without timeout or runtime exceptions.
Frequently Asked Questions
Q: Can I deploy a Solidity contract without using Truffle?A: Yes. Alternatives include Hardhat, Remix IDE, or direct web3.js calls with compiled bytecode and ABI.
Q: What happens if I forget the payable keyword on a function that receives ETH?A: The function will revert any transaction attempting to send ETH, resulting in a failed execution and gas consumption.
Q: Is it safe to use tx.origin for access control?A: No. tx.origin can be manipulated via phishing contracts and must never replace msg.sender in permission checks.
Q: How do I verify my contract source code on Etherscan?A: Submit the exact Solidity source, compiler version, optimization settings, and constructor arguments through Etherscan’s verification form.
Disclaimer:info@kdj.com
The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!
If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.
- DeepSnitch AI Ignites Crypto Presale Frenzy with Potential 100x Gains Amidst Market Volatility
- 2026-02-09 06:40:01
- Big Game Kickoff: BetMGM Deals $1,500 Bonus for Coin Toss Betting Thrills
- 2026-02-09 07:15:01
- Bitcoin's Rollercoaster: Navigating FOMO, Opportunity, and the Ever-Present Trap
- 2026-02-09 07:10:01
- The Super Bowl Coin Toss: A Flip of Fate, A Bet of Billions, and the Enduring Allure of Heads or Tails
- 2026-02-09 07:10:01
- XRP's High-Stakes Horizon: Charting a Breakout While Dodging Rug Pull Worries
- 2026-02-09 07:05:01
- Massive Token Unlocks Set to Shake Altcoins Amidst Market Volatility
- 2026-02-09 07:05:01
Related knowledge
How to Maximize Leverage Safely for Day Trading Crypto?
Feb 08,2026 at 01:19am
Understanding Leverage Mechanics in Crypto Derivatives1. Leverage multiplies both potential gains and losses by allowing traders to control larger pos...
How to Trade Ethereum Futures Before and After Major Upgrades?
Feb 08,2026 at 09:40am
Understanding Ethereum Futures Mechanics1. Ethereum futures contracts are standardized agreements to buy or sell ETH at a predetermined price and date...
How to Find High-Liquidity Pairs for Large Contract Trades?
Feb 08,2026 at 06:20pm
Finding High-Liquidity Pairs for Large Contract TradesTraders executing large contract orders must prioritize liquidity to avoid slippage and price im...
How to Use "Mark Price" vs. "Last Price" to Prevent Liquidation?
Feb 07,2026 at 05:39pm
Understanding Mark Price Mechanics1. Mark price is a composite value derived from multiple spot exchange indices and funding rate adjustments, designe...
How to Calculate "Return on Equity" (ROE) in Leverage Trading?
Feb 08,2026 at 04:39am
Understanding Return on Equity in Leverage Trading1. Return on Equity (ROE) in leverage trading measures the profitability generated relative to the t...
How to Trade Breakouts with Buy-Stop and Sell-Stop Orders?
Feb 08,2026 at 05:40pm
Understanding Breakout Mechanics in Cryptocurrency Markets1. Breakouts occur when price moves decisively beyond a well-defined consolidation zone, oft...
How to Maximize Leverage Safely for Day Trading Crypto?
Feb 08,2026 at 01:19am
Understanding Leverage Mechanics in Crypto Derivatives1. Leverage multiplies both potential gains and losses by allowing traders to control larger pos...
How to Trade Ethereum Futures Before and After Major Upgrades?
Feb 08,2026 at 09:40am
Understanding Ethereum Futures Mechanics1. Ethereum futures contracts are standardized agreements to buy or sell ETH at a predetermined price and date...
How to Find High-Liquidity Pairs for Large Contract Trades?
Feb 08,2026 at 06:20pm
Finding High-Liquidity Pairs for Large Contract TradesTraders executing large contract orders must prioritize liquidity to avoid slippage and price im...
How to Use "Mark Price" vs. "Last Price" to Prevent Liquidation?
Feb 07,2026 at 05:39pm
Understanding Mark Price Mechanics1. Mark price is a composite value derived from multiple spot exchange indices and funding rate adjustments, designe...
How to Calculate "Return on Equity" (ROE) in Leverage Trading?
Feb 08,2026 at 04:39am
Understanding Return on Equity in Leverage Trading1. Return on Equity (ROE) in leverage trading measures the profitability generated relative to the t...
How to Trade Breakouts with Buy-Stop and Sell-Stop Orders?
Feb 08,2026 at 05:40pm
Understanding Breakout Mechanics in Cryptocurrency Markets1. Breakouts occur when price moves decisively beyond a well-defined consolidation zone, oft...
See all articles














