-
bitcoin $77323.969542 USD
0.01% -
ethereum $2523.414850 USD
2.23% -
tether $0.999674 USD
0.01% -
bnb $732.334794 USD
2.37% -
xrp $1.364311 USD
0.51% -
usd-coin $0.999831 USD
0.00% -
solana $101.751035 USD
1.88% -
tron $0.339246 USD
0.15% -
hyperliquid $78.911101 USD
-1.42% -
zcash $1143.169120 USD
2.95% -
dogecoin $0.084522 USD
0.58% -
monero $539.820025 USD
5.75% -
chainlink $11.538258 USD
0.03% -
unus-sed-leo $9.111763 USD
0.28% -
cardano $0.208079 USD
-0.46%
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.
- CPEN Network Ink Token: A Deep Dive into Mobile Mining, Tokenomics, and Its Evolving Legacy
- 2026-09-12 16:35:02
- XRP Investors Face Critical Decision Amidst Market Uncertainty and Key Economic Events
- 2026-09-12 16:40:01
- Ethereum Whales Fuel ETH Explosion to 8-Month High Amidst Market Volatility
- 2026-09-12 16:35:02
- The sUSDe Yield, Aave Borrow Rate, and USDe Loop: A Tightrope Walk in DeFi's Big Apple
- 2026-09-12 12:45:01
- USDC Bridge CCTP, Stablecoin Chain Change, Bridge Shutdown: Navigating the New Era of Cross-Chain Transfers
- 2026-09-12 12:45:01
- Metaplanet Slashes Executive Share Pool by 41.1% Amidst Investor Outcry and Incentive Plan Withdrawal
- 2026-09-12 12:35:02
Related knowledge
How to Check DOGE Futures Volume and Open Interest?
Sep 12,2026 at 08:39am
Understanding DOGE Futures Volume1. Futures volume refers to the total number of DOGE futures contracts traded within a specific time frame, usually m...
How to Check BTC Futures Volume and Open Interest?
Sep 12,2026 at 03:19pm
Data Sources for BTC Futures Metrics1. CoinGlass API v4 delivers real-time funding rates, liquidation heatmaps, and granular open interest breakdowns ...
How to Read the DOGEUSDT Perpetual Contract Chart?
Sep 11,2026 at 07:19pm
Understanding Price Action on DOGEUSDT Perpetual Charts1. Candlestick formation reveals immediate market sentiment—green candles indicate buying domin...
How to Check BTC Futures Funding Fee on Binance?
Sep 10,2026 at 08:00am
Locating the Funding Rate Display1. Navigate to the Binance Futures trading interface and select the BTCUSDT perpetual contract. 2. Observe the area d...
How to Calculate SOLUSDT Futures Profit and Loss?
Sep 10,2026 at 07:19pm
Understanding SOLUSDT Futures Contract Specifications1. Each SOLUSDT futures contract is quoted in USDT and settled in USDT, making it a linear perpet...
How to Calculate XRPUSDT Futures PnL?
Sep 09,2026 at 05:40pm
Understanding XRPUSDT Futures Contract Specifications1. Each XRPUSDT perpetual contract is quoted in USDT and settled in USDT, with a face value of 1 ...
How to Check DOGE Futures Volume and Open Interest?
Sep 12,2026 at 08:39am
Understanding DOGE Futures Volume1. Futures volume refers to the total number of DOGE futures contracts traded within a specific time frame, usually m...
How to Check BTC Futures Volume and Open Interest?
Sep 12,2026 at 03:19pm
Data Sources for BTC Futures Metrics1. CoinGlass API v4 delivers real-time funding rates, liquidation heatmaps, and granular open interest breakdowns ...
How to Read the DOGEUSDT Perpetual Contract Chart?
Sep 11,2026 at 07:19pm
Understanding Price Action on DOGEUSDT Perpetual Charts1. Candlestick formation reveals immediate market sentiment—green candles indicate buying domin...
How to Check BTC Futures Funding Fee on Binance?
Sep 10,2026 at 08:00am
Locating the Funding Rate Display1. Navigate to the Binance Futures trading interface and select the BTCUSDT perpetual contract. 2. Observe the area d...
How to Calculate SOLUSDT Futures Profit and Loss?
Sep 10,2026 at 07:19pm
Understanding SOLUSDT Futures Contract Specifications1. Each SOLUSDT futures contract is quoted in USDT and settled in USDT, making it a linear perpet...
How to Calculate XRPUSDT Futures PnL?
Sep 09,2026 at 05:40pm
Understanding XRPUSDT Futures Contract Specifications1. Each XRPUSDT perpetual contract is quoted in USDT and settled in USDT, with a face value of 1 ...
See all articles














