Contract interface macros
The near-sdk-macros proc-macro crate turns Rust contract types and method signatures into NEAR contract interfaces. The #[near] and #[near_bindgen] annotations define exported entrypoints, state and argument boundaries, callback handling, and cross-contract call builders. This page gives the interface view needed before reading contract SDK authoring or the pages on runtime context, promises, and contract state.
Contract interface model
The macros keep the contract method as the source of business logic and add a NEAR-facing boundary around it. A state type describes the contract data, an annotated implementation describes callable behavior, and the generated wrapper connects both to NEAR host calls.
flowchart LR
A[NEAR function call] --> B[Generated WASM entrypoint]
B --> C[Input and callback boundaries]
C --> D[Contract method]
D --> E[State write or value serialization]
E --> F[NEAR return value]
D -.-> G[Generated Ext call builder]
G --> H[Promise for another execution]
The interface has two directions. NEAR invokes generated entrypoints by method name. Contract code invokes another contract through a generated Ext builder that produces a Promise with the same method name and compatible argument format.
Contract state and entrypoints
Contract state type
#[near(contract_state)] marks the single type that represents persistent contract state. It gives the type the SDK state contract and the default Borsh boundary needed for state storage. A custom state key can be used when the contract needs a different storage location.
The state annotation also creates the base for the contract's <ContractType>Ext call API. #[near] on an implementation block then adds wrappers for its exposed methods. #[near_bindgen] provides the older form of this authoring model and requires more serialization setup on the type.
References: near-sdk/…/lib.rs• L162-181 near-sdk/…/lib.rs• L230-239 near-sdk-macros/…/state.rs• L6-41 near-sdk-macros/…/lib.rs• L243-326
Entrypoint lifecycle
Each exposed method receives a generated WASM entrypoint with the method's name. The wrapper separates NEAR concerns from the method body through a fixed sequence:
- It prepares panic reporting and applies access and deposit rules.
- It reads and decodes regular arguments from the call input.
- It reads contract state for calls and views, or creates state through an initializer.
- It invokes the original Rust method.
- It returns encoded output and writes changed state for methods that can mutate it.
Views do not write state. Initializers require a contract-state result and, unless ignore_state is set, reject a second initialization. A method without payable rejects an attached deposit, while private limits the caller to the contract account.
References: near-sdk/…/lib.rs• L578-623 near-sdk/…/lib.rs• L625-707 near-sdk/…/lib.rs• L1202-1257 near-sdk-macros/…/impl_item_method_info.rs• L7-49 near-sdk-macros/…/impl_item_method_info.rs• L151-220
Serialization boundaries
Call input and output formats
Regular method arguments cross the NEAR boundary as one serialized input value. JSON is the default format for both arguments and return values. Borsh can be selected for all regular arguments on a method with #[serializer(borsh)], and for a return value with #[result_serializer(borsh)].
The macros build an input record from the method's regular arguments. This makes named JSON fields part of the public contract interface. #[deny_unknown_arguments] makes JSON reject fields that the method does not declare; it has no effect when the input uses Borsh. Callback arguments are not part of this regular input record.
Types marked with #[near(serializers = [...])] receive the requested JSON and/or Borsh support. The default type format is Borsh. These type-level formats must agree with the method boundary that carries the type.
References: near-sdk/…/lib.rs• L399-505 near-sdk/…/lib.rs• L550-576 near-sdk/…/lib.rs• L709-757 near-sdk/…/lib.rs• L760-788 near-sdk-macros/…/attr_sig_info.rs• L50-132 near-sdk-macros/…/attr_sig_info.rs• L189-201
Cross-contract call builders
For a contract state type, the macros generate <ContractType>Ext. For an external trait, #[ext_contract] generates a module with a similar builder. Both forms turn a Rust method signature into a Promise call and serialize its regular arguments with the method's input format.
The builder can target an account, attach to an existing promise, set a deposit, and set gas settings. The generated method name is the on-chain function name, so renaming a Rust method changes the cross-contract interface as well as the local entrypoint.
References: near-sdk/…/lib.rs• L271-340 near-sdk/…/lib.rs• L1330-1385 near-sdk-macros/…/ext.rs• L9-90 near-sdk-macros/…/ext.rs• L138-187 near-sdk-macros/…/item_trait_info.rs• L6-23
Callback boundaries
Promise result arguments
Callback annotations tell a generated entrypoint to read promise results instead of reading those values from normal call input. The callback result index follows the order of callback arguments in the method signature, which lets one callback consume results from a chained or joined promise.
The annotations express different failure policies:
| Annotation | Method argument | Failed promise behavior |
|---|---|---|
#[callback_unwrap] | The decoded value T | The wrapper panics when the promise fails or the value cannot be decoded |
#[callback_result] | Result<T, PromiseError> | The method receives the failure and decides how to handle it |
#[callback_vec] | Vec<T> from all promise results | The wrapper panics if any result fails |
Each callback can set max_bytes to limit the data accepted from the promise result. A callback method is normally also private, so only a call made by the contract can reach it.
References: near-sdk/…/lib.rs• L871-959 near-sdk/…/lib.rs• L959-1051 near-sdk-macros/…/arg_info.rs• L7-22 near-sdk-macros/…/attr_sig_info.rs• L228-348
Callback serialization
Callback values use the serializer selected for that argument. The wrapper checks the promise result first, then decodes its bytes as JSON or Borsh. A callback result with T = () also supports the empty return payload used by a method with no return value.
#[callback_vec] reads the full promise-result range and decodes each item into the vector. Only one vector callback is allowed on a method because it consumes the complete result set.
References: near-sdk-macros/…/attr_sig_info.rs• L246-305 near-sdk-macros/…/attr_sig_info.rs• L310-348 near-sdk-macros/…/abi_generator.rs• L133-169
Compile-time interface validation
Method shape rules
The macros classify a method as an initializer, a view, or a state-changing call from its annotations and receiver. They validate the shape before generating a wrapper, so many interface errors appear during compilation rather than during a transaction.
The main rules are:
- Contract API methods cannot be
async, variadic, or declared with a Rust binary ABI. - Contract API methods cannot use type or const generics in their signatures.
- Initializers cannot take
selfand must return the contract state. - A view cannot be payable.
#[handle_result]requiresResult<T, E>unless thealiasedform is used. The error type must support the SDK's function-error behavior.#[callback_result]requiresResult<T, PromiseError>, and#[callback_vec]requiresVec<T>.- Regular input arguments must use one serializer type for the method. A method cannot mix JSON and Borsh regular inputs.
The checks preserve a stable boundary between Rust types and the NEAR call model. They also reject nested #[near] or #[near_bindgen] attributes and reserve generated method names used for contract metadata and ABI output.
References: near-sdk-macros/…/mod.rs• L95-114 near-sdk-macros/…/attr_sig_info.rs• L66-201 near-sdk-macros/…/visitor.rs• L55-169 near-sdk-macros/…/visitor.rs• L234-261 near-sdk-macros/…/lib.rs• L49-103 near-sdk-macros/…/lib.rs• L249-280
ABI and metadata surface
When ABI generation is enabled through the macro crate's abi feature family, the macro records each exposed function's name, kind, modifiers, argument schemas, callback schemas, and result schema. The __abi-embed and __abi-generate feature forms support the build contexts that publish or embed this machine-readable description of the same interface that the WASM entrypoints use. The feature is enabled for the docs build so this ABI surface remains documented.
The state annotation can also add NEP-330 source metadata and a contract_source_metadata view. An event enum marked with event_json gains the NEP-297 event shape and metadata methods. These generated surfaces describe or standardize the contract interface; they do not replace the entrypoint rules.
References: near-sdk-macros/Cargo.toml• L33-39 near-sdk-macros/…/abi_generator.rs• L10-40 near-sdk-macros/…/abi_generator.rs• L80-229 near-sdk-macros/…/mod.rs• L66-114 near-sdk-macros/…/mod.rs• L20-73 near-sdk-macros/…/lib.rs• L690-778
Change checklist
When these files or sections are changed, remember to consider these:
- Changing a public method name or signature changes the WASM entrypoint, generated
Extmethod, ABI entry, and every external caller. - Changing a regular argument serializer requires matching the serializer on every
Extorext_contractcaller and on the carried type. - Adding or reordering callback arguments changes promise-result indexes and can silently connect a callback to the wrong result.
- Changing
#[handle_result]or a function error type changes whether a failure becomes a returned value or a contract panic. - Changing state annotation or its storage key must stay aligned with the state initialization and persistent-storage contract.
- Changing event standard or event versions changes the NEP-297 data read by indexers and clients.
- Changing ABI feature selection can change whether generated interface descriptions are embedded, generated, or available to documentation tools.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Regular arguments use both JSON and Borsh | The contract interface does not compile | Use one serializer for all regular inputs on a method |
A callback type is not Result<T, PromiseError> or Vec<T> | Callback ABI generation or wrapper generation fails | Match the annotation to its required argument shape |
A callback result exceeds max_bytes or cannot decode | The callback panics before the method runs | Set a suitable limit and use the serializer used by the producing call |
| A non-payable method receives a deposit | The generated entrypoint panics and the call fails | Mark the method #[payable] only when it handles attached funds |
| An initializer runs after state already exists | The generated entrypoint rejects the call | Use a new initializer or explicitly choose ignore_state for a controlled migration |
| A private method is called by another account | The generated caller check rejects the call | Use private methods only for self-calls and callbacks |
| A Rust method is renamed without updating callers | Cross-contract calls target a missing function name | Treat method names as on-chain API names |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/lib.rs | Public annotation contract and the high-level rules for state, entrypoints, serialization, callbacks, Ext, ABI, events, and metadata |
| near-sdk/…/near_annotations.rs | Compact index of annotations shared by #[near] and #[near_bindgen] |
| near-sdk-macros/Cargo.toml | Feature selection for optional ABI generation and documentation support |
| near-sdk-macros/…/lib.rs | Macro entry points and the flow from source items to generated wrappers, Ext APIs, ABI, and metadata |
| near-sdk-macros/…/attr_sig_info.rs | Signature and annotation model used to classify method arguments and serializers |
| near-sdk-macros/…/visitor.rs | Rules that classify calls, views, and initializers and validate their combinations |
| near-sdk-macros/…/impl_item_method_info.rs | Generated entrypoint lifecycle and the boundary between host calls and the original method |
| near-sdk-macros/…/attr_sig_info.rs | Generated regular-input and callback decoding behavior |
| near-sdk-macros/…/ext.rs | Generated cross-contract builders and method wrappers |
| near-sdk-macros/…/abi_generator.rs | Generated ABI description for methods, arguments, callbacks, results, and modifiers |