Neo Native Contracts: Built-in System Modules for Core Blockchain Functionality
Neo native contracts are protocol-level system modules compiled directly into the client that implement essential blockchain services—including tokenomics, governance, cryptography, and contract lifecycle management—through deterministic, fixed-script-hash deployments.
The Neo blockchain embeds critical protocol logic directly into its virtual machine through a suite of native contracts located in the neo-project/neo repository. These specialized system contracts, found under src/Neo/SmartContract/Native/, exist at predetermined script hashes and provide deterministic execution for everything from NEP-17 token transfers to committee governance, cryptographic primitives, and oracle services.
What Are Native Contracts in Neo?
Native contracts in Neo are specialized system contracts that inherit from the abstract NativeContract base class. Unlike user-deployed contracts, these modules are compiled directly into the protocol binary and registered during node startup. They exist at fixed script hashes, ensuring every node references the same deterministic state.
The NativeContract Base Class
The foundation for all native contracts resides in src/Neo/SmartContract/Native/NativeContract.cs. This base class defines static properties that expose singleton instances of each native contract (lines 58-86), allowing the VM to resolve them via NativeContract.GetContract.
Key virtual hooks enable contracts to participate in blockchain lifecycle events:
InitializeAsync: Executes during genesis block processing or hard-fork activation to set initial state.OnPersistAsync: Triggers after block persistence, enabling state updates like GAS distribution or committee reconfiguration.PostPersistAsync: Runs finalization logic after allOnPersistAsyncoperations complete, such as minting rewards to voters.OnManifestCompose: Customizes the contract manifest exposed to the VM.
Fixed Script Hashes and Registration
During node initialization, native contracts register themselves in a global dictionary mapping script hashes to instances. This registration occurs in the static constructor of NativeContract.cs, ensuring that calls to System_Contract_CallNative resolve correctly. Because these hashes are protocol-defined, user contracts can reliably invoke native methods without deployment concerns.
Core Blockchain Services Implemented by Native Contracts
Neo’s native contract layer implements the protocol's essential services, from tokenomics to cryptographic verification. Each contract specializes in a specific domain, exposing methods that user contracts invoke through standard NEP-17 or custom ABIs.
Tokenomics and Governance (NeoToken and GasToken)
The dual-token system relies on NeoToken.cs and GasToken.cs in src/Neo/SmartContract/Native/.
NeoToken manages the NEO governance token:
RegisterCandidate/UnregisterCandidate: Validator candidate management.Vote: Delegates voting power to candidates, influencing committee selection.GetCommittee: Retrieves the current consensus committee.UnclaimedGas: Calculates GAS rewards for NEO holders.SetGasPerBlock: Committee-controlled parameter adjusting block rewards.
GasToken implements the utility token:
Mint: Creates GAS for NEO holders and committee members duringPostPersistAsync.Burn: Destroys GAS for transaction fees.Transfer: Standard NEP-17 transfer method.
Contract Lifecycle Management (ContractManagement)
ContractManagement.cs controls the deployment, update, and destruction of user contracts:
Deploy: Registers new contracts with validation and fee checks.Update: Allows contract authors to upgrade code while preserving storage.Destroy: Removes contracts from the global registry.GetContract: Retrieves contract state by script hash.HasMethod: Checks method availability for dynamic invocation.ListContracts: Enumerates deployed contracts.
Cryptographic Operations (CryptoLib)
CryptoLib.cs exposes cryptographic primitives without external dependencies:
Sha256,RIPEMD160,Keccak256,Murmur32: Hash algorithms.VerifyWithECDsa: ECDSA signature verification with configurable curves viaNamedCurveHashenum.VerifyWithEd25519: Ed25519 signature support.RecoverSecp256K1: Public key recovery from signatures.
Utility Functions (StdLib)
StdLib.cs provides general-purpose utilities:
Serialize/Deserialize: Binary serialization.JsonSerialize/JsonDeserialize: JSON handling.Base64Encode/Base58Encode/HexEncode: Encoding utilities.MemoryCompare: Low-level memory operations.
Blockchain State Access (LedgerContract)
LedgerContract.cs offers read-only access to chain data:
GetBlock: Retrieves block by index or hash.GetTransaction: Looks up transactions.CurrentIndex: Returns the current block height.GetBlockHeight: Alternative height query.GetContractState: Queries contract deployment state.
System Policy and Access Control (PolicyContract and RoleManagement)
PolicyContract.cs manages protocol parameters:
SetFeePerByte: Adjusts transaction fees.SetMaxGasInvoke: Limits invocation gas.SetMaxTransactionSize: Enforces size limits.IsBlocked: Checks if accounts are blacklisted.IsWhitelistFeeContract: Identifies fee-exempt contracts.
RoleManagement.cs handles role-based permissions:
AddRole/RemoveRole: Assigns roles likeCommittee,Oracle, orNotarydefined inRole.cs.HasRole: Verifies role membership.GetRoles: Lists roles assigned to an account.
Oracle and Notary Services (OracleContract and Notary)
OracleContract.cs enables off-chain data feeds:
Request: Registers oracle requests.Respond: Submits verified responses.GetRequest/GetResponse: Query request/response status.SetGasForResponse: Configures response fees.
Notary.cs provides data notarization:
Notarize: Stores data hashes with signer proofs for cross-chain verification.GetNotaryInfo: Retrieves notarization records.
Treasury and Fee Management (Treasury and WhitelistedContract)
Treasury.cs manages protocol fees:
Withdraw: Distributes accumulated fees.GetBalance: Checks treasury balance.SetWithdrawAddress: Configures payout addresses.
WhitelistedContract.cs supports PolicyContract by tracking fee-exempt contracts internally.
How Native Contracts Integrate with the Neo VM
Native contracts embed directly into the Neo Virtual Machine through a specialized invocation mechanism that bypasses the need for deployed bytecode while maintaining full ABI compatibility.
Block Lifecycle Hooks
The NativeContract base class defines virtual methods that the protocol invokes during specific blockchain events:
InitializeAsync: Executes during genesis block processing or hard-fork activation to set initial state.OnPersistAsync: Called after block persistence, enabling state updates like token minting or committee reconfiguration.PostPersistAsync: Runs finalization logic after allOnPersistAsyncoperations complete, such as minting GAS rewards to voters.OnManifestCompose: Customizes the contract manifest exposed to the VM.
These hooks ensure that native contracts modify state deterministically across all nodes during block processing.
System Calls and Invocation
User contracts invoke native methods through the System_Contract_CallNative syscall. When the VM encounters this syscall, it resolves the target contract using NativeContract.GetContract, which maps fixed script hashes to singleton instances.
The Invoke method in NativeContract.cs handles method dispatch by matching the called method name against the contract's ABI. Because native contracts generate their NEF scripts at runtime from reflected methods (GetAllowedMethods), every node produces identical bytecode, ensuring consensus.
Hard-Fork Activation
Native contracts support protocol upgrades through the Activations property on methods. The IsActive helper checks whether a method should be callable at the current block height, allowing new features to activate at specific block heights without breaking existing deployments.
Security and Access Control Mechanisms
Native contracts enforce strict security boundaries through call flags and committee verification.
State-modifying methods require CallFlags.States and verify committee signatures via AssertCommittee (implemented in NativeContract.cs). This ensures that sensitive operations like SetGasPerBlock or SetMinimumDeploymentFee can only execute with explicit multi-sig approval from the Neo committee.
Role-based permissions delegate to RoleManagement, which maintains mappings for roles such as Committee, Oracle, and Notary defined in Role.cs. Methods check role membership through HasRole before executing privileged logic.
Interacting with Native Contracts from Smart Contracts
Developers invoke native contracts using standard contract calls. Below are practical C# examples demonstrating interaction with Neo's native contract layer.
Query NEO Token Supply
public static BigInteger GetNeoTotalSupply()
{
var neo = NativeContract.NEO;
var result = (BigInteger)Contract.Call(neo.Hash, "totalSupply", CallFlags.ReadStates, neo);
return result;
}
This example retrieves the total supply of NEO by calling the totalSupply method on the native NEO contract using CallFlags.ReadStates for read-only access.
Encode Data with StdLib
public static string EncodeBase64(byte[] data)
{
return StdLib.Base64Encode(data);
}
The StdLib native contract provides utility methods like Base64Encode that contracts can invoke directly without deploying external libraries.
Verify Cryptographic Signatures
public static bool VerifySignature(
byte[] message,
byte[] pubKey,
byte[] signature,
NamedCurveHash curve = NamedCurveHash.secp256r1SHA256)
{
return CryptoLib.VerifyWithECDsa(message, pubKey, signature, curve);
}
CryptoLib exposes native cryptographic verification through VerifyWithECDsa, supporting multiple curves via the NamedCurveHash enum defined in NamedCurveHash.cs.
Participate in Governance Voting
public static bool VoteForCandidate(UInt160 account, ECPoint? candidatePubKey)
{
return NeoToken.Vote(account, candidatePubKey).Result;
}
The NeoToken native contract manages on-chain governance, allowing NEO holders to vote for validator candidates through the Vote method.
Access Blockchain State
public static uint GetCurrentBlock()
{
return Ledger.CurrentIndex();
}
LedgerContract provides read-only access to blockchain data, returning the current block height through CurrentIndex.
Summary
- Native contracts are protocol-level modules in
neo-project/neothat implement core blockchain functionality at fixed script hashes, located insrc/Neo/SmartContract/Native/. - The
NativeContractbase class inNativeContract.csprovides lifecycle hooks (InitializeAsync,OnPersistAsync,PostPersistAsync) for deterministic state management across all nodes during block processing. - NeoToken and GasToken handle the dual-token economy, governance voting, committee selection, and GAS distribution mechanics through methods like
Vote,RegisterCandidate, andMint. - ContractManagement controls the deployment, update, and destruction of user contracts through
Deploy,Update, andDestroy. - CryptoLib and StdLib provide cryptographic primitives (
VerifyWithECDsa,Sha256) and serialization utilities (Serialize,Base64Encode) without external dependencies. - PolicyContract and RoleManagement enforce system-wide parameters and role-based access control, verifying committee signatures via
AssertCommitteeand role membership viaHasRole. - Invocation occurs via the
System_Contract_CallNativesyscall, with theInvokemethod inNativeContract.csdispatching to the appropriate method based on the contract ABI.
Frequently Asked Questions
What is the difference between native contracts and regular smart contracts on Neo?
Native contracts are compiled directly into the Neo protocol binary and exist at fixed script hashes defined in NativeContract.cs, whereas regular smart contracts are deployed by users and stored in the blockchain's contract storage. Native contracts implement core protocol features like the NEO/GAS tokens, cryptography, and governance, while user contracts build application logic on top of these primitives. The VM invokes native contracts through the System_Contract_CallNative syscall rather than loading bytecode from storage.
How does Neo ensure that native contract upgrades don't break existing deployments?
Neo implements hard-fork awareness through the Activations property on native contract methods. The IsActive helper checks the current block height against activation thresholds before executing new methods. This allows the protocol to introduce new native contract features at specific block heights while maintaining backward compatibility for existing contracts until the hard fork activates, ensuring deterministic behavior across all nodes.
Can developers call native contract methods from their own smart contracts?
Yes, developers invoke native contracts using the standard Contract.Call method with the native contract's fixed script hash. For example, calling Contract.Call(NativeContract.NEO.Hash, "transfer", CallFlags.All, args) invokes the NEO token transfer method. The VM resolves these calls through NativeContract.GetContract and routes them via the System_Contract_CallNative syscall to the appropriate implementation, treating them like regular contract calls but with protocol-level performance.
What security mechanisms protect sensitive native contract operations?
State-modifying native contract methods require CallFlags.States and verify committee signatures via AssertCommittee (implemented in NativeContract.cs). This ensures that sensitive operations like SetGasPerBlock, SetMinimumDeploymentFee, or role management in RoleManagement can only execute with explicit multi-signature approval from the Neo committee. Additionally, role-based permissions delegate to RoleManagement, which maintains mappings for roles such as Committee, Oracle, and Notary defined in Role.cs, verifying membership through HasRole before executing privileged logic.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →