Security Best Practices
Securing smart contracts is critical, as any vulnerabilities can result in substantial financial loss, data breaches, and a decline in user confidence. When building JavaScript-based smart contracts on Zetrix or any compatible platform it is essential to follow established security best practices. The following provides a detailed overview of these key practices.
1. Understand the Smart Contract Environment
Before beginning to code, it's essential to gain a clear understanding of the blockchain environment in which you're developing:
Blockchain Specifics: Familiarize yourself with the Zetrix blockchain’s architecture, consensus mechanism (DPoS), and how it handles smart contracts.
Execution Model: Understand how smart contracts are executed, including gas costs, transaction handling, and state management.
Security Model: Grasp the security model of the blockchain, including permission levels, access controls, and typical attack vectors.
2. Follow Secure Coding Standards
Adhering to established coding standards helps prevent common vulnerabilities:
Use Strict Mode: Enable strict mode in JavaScript (
'use strict';) to catch common coding bloopers, preventing the use of undeclared variables and other errors.'use strict';Consistent Coding Style: Maintain a consistent coding style using tools like ESLint with security-focused plugins (e.g.,
eslint-plugin-security).Modular Code Structure: Break down your code into smaller, reusable, and testable modules to enhance readability and maintainability.
3. Input Validation and Sanitization
Consistently validate and sanitize all inputs to safeguard against malicious data that could trigger unintended or harmful behavior in the contract.
Type Checking: Ensure that inputs are of the expected type (e.g., numbers, strings, addresses).
function transferFrom(from, to, value) { Utils.assert(Utils.addressCheck(from) === true, 'Arg-from is not a valid address.'); Utils.assert(Utils.addressCheck(to) === true, 'Arg-to is not a valid address.'); Utils.assert(Utils.stoI64Check(value) === true, 'Arg-value must be alphanumeric.'); Utils.assert(Utils.int64Compare(value, '0') > 0, 'Arg-value must be greater than 0.'); Utils.assert(from !== to, 'From cannot equal to address.'); // Transfer logic }Boundary Checks: Implement checks for input ranges to avoid integer overflows or underflows.
function checkBalance(amount <= balances[msg.sender], "Insufficient balance");Avoid Trusting External Inputs: Do not trust data coming from outside the contract without proper validation.
4. Access Control and Authorization
Implement robust access control mechanisms to restrict sensitive functions:
Role-Based Access Control (RBAC): Define roles (e.g., admin, user) and restrict function access based on these roles.
Modifiers: Use function modifiers to enforce access restrictions.
Least Privilege Principle: Grant the minimum necessary permissions to each role or function.
5. Prevent Reentrancy Attacks
Reentrancy is a prevalent attack method where an external contract exploits a vulnerability by invoking the original contract before its previous execution has finished, potentially manipulating its state or draining assets.
Use Checks-Effects-Interactions Pattern: Perform all necessary checks, update state variables, and then interact with external contracts.
Reentrancy Guards: Implement mutexes or reentrancy guards to prevent multiple simultaneous calls.
6. Secure Handling of ZETRIX and Tokens
Manage the transfer and receipt of Zetrix or tokens securely:
Use Safe Transfer Methods: Prefer using
Chain.payCoinfor transferring ZETRIX, or use safe token transfer functions provided by Zetrix Standard.
7. Implement Proper Error Handling
Ensure that your smart contract gracefully handles errors:
Use Require, Revert, and Assert Appropriately:
requirefor input validation and conditions.revertfor manual error throwing with messages.assertfor invariants and conditions that should never be false.
Descriptive Error Messages: Provide clear and descriptive error messages to aid in debugging and transparency.
8. Optimize for Gas Efficiency
Although not strictly a security measure, optimizing gas consumption helps prevent denial-of-service (DoS) attacks that exploit out-of-gas exceptions, ensuring more reliable and efficient contract execution.
Efficient Code: Write gas-efficient code to minimize transaction costs and prevent attackers from exploiting high gas consumption.
Avoid Unbounded Loops: Limit the number of iterations in loops to prevent excessive gas consumption.
9. Conduct Regular Security Audits and Penetration Testing
Regularly assess the security posture of your smart contracts:
Scheduled Audits: Plan periodic security audits, especially after significant code changes or updates.
Bug Bounties: Consider implementing bug bounty programs to incentivize external security researchers to identify vulnerabilities.
Automated Testing: Integrate automated security testing into your continuous integration/continuous deployment (CI/CD) pipeline.
10. Implement Time Locks and Pausable/Freezable Contracts
Provide mechanisms to mitigate potential vulnerabilities post-deployment:
Time Locks: Introduce delays for critical operations to allow for oversight and intervention if malicious activity is detected.
Pausable/Freezable Contracts: Allow the contract to be paused in case of emergencies to prevent further damage.
11. Smart contract — Hierarchical access control standard
All smart contracts in this project follow a standardized two-tier hierarchical access control model. Role naming must adhere to this standard across all contracts to ensure consistency and reduce audit surface area.

Access tiers
Tier 1 — Highest ( admin / owner )
Must be a multisig wallet
Manages all role grants and revocations
Controls critical contract parameters
Sole authority to rotate operator roles
Tier 2 — Operational ( operator / manager )
EOA account (externally owned)
May be stored in backend for automation
If compromised, admin rotates the key
Day-to-day operational functions only
Naming standard
DEFAULT_ADMIN_ROLE
admin / owner
Multisig
Required — no EOA permitted
OPERATOR_ROLE
operator / manager
EOA
Rotation handled by admin
Security Notes
Contracts that assign
DEFAULT_ADMIN_ROLEto an EOA will fail security review.Multisig is mandatory for Tier 1 regardless of environment (testnet included for production-bound deployments).
Operator keys stored in the backend must follow the team's secrets management policy.
Key rotation procedures should be documented and tested before mainnet deployment.
Conclusion
Creating secure JavaScript-based smart contracts on the Zetrix blockchain or any blockchain platform demands a holistic approach that includes secure coding standards, extensive testing, routine audits, and ongoing monitoring. Following the best practices detailed above helps minimize security risks and strengthens the resilience and dependability of your smart contracts.
Last updated