Events, JSON, and contract types
The SDK defines the data forms that cross a contract boundary. It gives contracts a stable event format for indexers and callers, JSON and Borsh choices for method data, and typed values that keep common NEAR data safe at that boundary. Start with Smart contract SDK authoring for the wider authoring model.
Interface boundary
Caller and contract boundary
A contract caller is a wallet, client, or other contract that sends method arguments and reads method results. The boundary must agree on both the serializer and the shape of each value. Contract types use Borsh by default, while method arguments and results use JSON by default and can opt into Borsh. The generated ABI can describe the selected form for tooling. See Contract interface macros for the entrypoint and callback flow.
References: near-sdk/…/lib.rs• L399-448 near-sdk/…/lib.rs• L481-505 near-sdk-macros/…/serializer.rs• L5-37 near-sdk-macros/…/abi_generator.rs• L248-272
Interface choices
JSON is the readable boundary for values that clients inspect or construct. Borsh is the compact binary boundary used by default and remains available for types that need it. A type can support both forms when it is shared by more than one boundary, but the caller and callee must still select the same form for each method argument and result.
The SDK re-exports serde, serde_json, serde_with, and Borsh through its public surface. This lets contract code apply normal Serde rules to JSON types, including field names, enum names, aliases, and custom display forms. A serialization change is therefore an API change, even when the Rust type still compiles.
The near-sdk-core manifest keeps these capabilities optional. Its serde feature enables JSON support and related value conversions. Its borsh feature enables binary support. The abi feature joins Borsh schemas with JSON schema support for interface descriptions. This preserves the core crate's role as a small shared type layer for both contracts and off-chain callers.
References: near-sdk/…/lib.rs• L434-505 near-sdk-core/…/lib.rs• L18-41 near-sdk-macros/…/serializer.rs• L16-27 near-sdk-core/Cargo.toml• L17-43 near-sdk-core/Cargo.toml• L66-117
NEP-297 event stream
Event declarations
NEP-297 events are structured log records for indexers and other off-chain readers. A contract declares an event enum with #[near(event_json(standard = "..."))], then gives every variant an #[event_version("...")] value. The standard identifies the event family. The version lets readers accept known shapes as the family evolves.
The SDK derives the event metadata from the enum. Variant names become snake-case event names, so a Rust variant such as TokenTransfer is exposed as token_transfer. The event payload remains tied to the variant, which gives the Rust author type checks before the record reaches the log.
References: near-sdk/…/lib.rs• L1053-1084 near-sdk/…/lib.rs• L1097-1113 near-sdk-macros/…/mod.rs• L20-73 near-sdk-macros/…/lib.rs• L690-723
Event JSON shape
Each event has a small, fixed metadata envelope. The data value is present when the variant has a payload and is absent for a unit variant. A tuple or scalar variant uses that value directly, while a struct variant produces an object with its fields.
{
"standard": "nepXXX",
"version": "1.0.0",
"event": "token_transfer",
"data": {
"from": "alice.near",
"to": "bob.near"
}
}
The emitted log adds EVENT_JSON: before the JSON object. This prefix separates NEP-297 records from ordinary logs. The event wrapper exposes the metadata and the raw borrowed payload, and its JSON helpers provide either a serde_json::Value, a JSON string, or the complete log line.
The event path is a short transformation from a typed Rust value to a record that an indexer can recognize.
flowchart LR
A[Typed event enum] --> B[Standard and variant version]
B --> C[NEP-297 JSON envelope]
C --> D[EVENT_JSON log line]
D --> E[Indexers and off-chain callers]
References: near-sdk-core/…/events.rs• L3-28 near-sdk-core/…/events.rs• L30-60 near-sdk-core/…/events.rs• L62-105 near-sdk-macros/…/lib.rs• L736-778 near-sdk/…/event_tests.rs• L74-109
Event emission
The generated emit() method serializes the event and sends one log line to the NEAR runtime. to_nep297_event() is useful when a caller needs to inspect metadata or create the representation without emitting it. The lower-level Nep297Event type borrows the payload, so inspection and serialization do not require a second event value.
The reusable fungible-token and non-fungible-token standards follow the same contract. Their single-record and batch helpers produce nep141 and nep171 records with versioned event names. These logs are intended for indexers, so their field names and numeric forms are part of the public standard rather than private Rust details.
References: near-sdk-macros/…/lib.rs• L736-778 near-sdk-core/…/events.rs• L62-105 near-contract-standards/…/event.rs• L5-30 near-contract-standards/…/events.rs• L21-43 near-contract-standards/…/events.rs• L20-42
JSON data representations
JSON serialization
The #[near(serializers = [json])] form makes a struct or enum a JSON boundary. Serde attributes then control the public names and layout. The same rules apply to method arguments and results when a method uses JSON serialization, so one type can serve both a contract method and an event payload when its shape is suitable.
JSON must represent values in a form that client languages can read without losing meaning. This is why the SDK supplies wrappers for values that JSON handles poorly, instead of asking every caller to repeat its own encoding rules.
References: near-sdk/…/lib.rs• L399-448 near-sdk/…/lib.rs• L481-505 near-sdk-macros/…/impl_item_method_info.rs• L366-392
JSON-safe helper types
The near_sdk::json_types module re-exports small wrappers for common values that need a clear JSON form. They keep the Rust value typed while defining the wire form used by clients and schemas.
| Type | JSON representation | Boundary concern |
|---|---|---|
U64, U128, I64, I128 | Base-10 string | Avoids precision loss in JSON readers that only support safe integers up to 53 bits. |
Base64VecU8 | Base64 string | Represents bytes as one portable text value instead of a JSON number array. |
Base58CryptoHash | Base58 string | Gives hashes a readable, fixed-length text form with validation on input. |
PublicKey | Curve name and Base58 key data | Keeps the key type visible to callers while validating its byte length. |
These wrappers support conversion back to the underlying Rust values. They also expose JSON schema information as supported, which keeps generated interface descriptions aligned with the value seen by callers.
References: near-sdk-core/…/mod.rs• L1-34 near-sdk-core/…/integers.rs• L1-73 near-sdk-core/…/vector.rs• L1-69 near-sdk-core/…/hash.rs• L67-117 near-sdk-core/…/public_key.rs• L123-145 near-sdk-core/…/public_key.rs• L249-277 near-sdk-core/Cargo.toml• L69-99
Schema and ABI descriptions
The ABI describes the public method boundary for tools and clients. For a JSON argument or result it carries a JSON Schema; for a Borsh value it carries a Borsh schema. The NearSchema derive and the #[abi(json)] or #[abi(borsh)] choice supply the type information needed to build that description.
The schema is a contract for tooling, not a replacement for runtime serialization. A type can have a schema while a caller still fails if it sends the wrong serializer, field name, or encoded value. Keep the wire shape and its schema under the same change review.
References: near-sdk/…/lib.rs• L1549-1563 near-sdk-macros/…/abi_generator.rs• L10-39 near-sdk-macros/…/abi_generator.rs• L248-272 near-sdk-macros/…/lib.rs• L404-505
Contract-facing type system
Runtime value types
The core type set gives contract code names for values that have a shared meaning across contracts and the runtime. AccountId identifies an account. NearToken and Gas keep token and gas units distinct. Timestamp, Duration, CryptoHash, PublicKey, and CurveType cover other common runtime values.
The core type exports also include AccountIdRef and GasWeight. AccountIdRef provides a borrowed account identifier for interfaces that do not need an owned value. GasWeight represents the relative share used when unused gas is distributed across weighted function calls, and its default weight is one.
These types are more than aliases at a JSON boundary. Their parse and display rules define what callers send and receive. For example, PublicKey uses a human-readable curve prefix and Base58 data, then checks that the key has the length required by that curve.
References: near-sdk-core/…/mod.rs• L1-49 near-sdk-core/…/public_key.rs• L4-68 near-sdk-core/…/public_key.rs• L123-145 near-sdk-core/…/public_key.rs• L249-277
Bounded contract values
BoundedString, BoundedVec, and BoundedBase64VecU8 put a fixed upper limit on input values that would otherwise grow without bound. They reject oversized values during construction and during the JSON or Borsh deserialization paths they support, so contract logic does not need to handle an unbounded value first. These types are exported from near_sdk_core::types when the unstable feature is enabled.
BoundedString<MAX> measures UTF-8 bytes and keeps the JSON string and Borsh String wire forms. BoundedVec<T, MAX> measures elements and keeps the Borsh Vec<T> form; it serializes to a JSON array but does not deserialize from JSON. BoundedBase64VecU8<MAX> measures decoded bytes and presents bytes as a Base64 JSON string while using the Borsh Vec<u8> form. Their JSON schemas advertise maxLength or maxItems as an upper bound for the accepted value. Bound nested variable-size elements too when the total input must stay controlled.
An oversized value returns TooLongError, which reports the rejected length and the allowed maximum. This makes the limit part of the type contract and keeps the same guard active for method inputs, stored values, and other shared data forms. The Base64 wrapper converts to and from BoundedVec<u8, MAX>, which lets callers choose the JSON form without changing the bounded byte value.
References: near-sdk-core/…/mod.rs• L1-62 near-sdk-core/…/string.rs• L7-17 near-sdk-core/…/string.rs• L124-233 near-sdk-core/…/vec.rs• L5-15 near-sdk-core/…/vec.rs• L141-200 near-sdk-core/…/base64_vec.rs• L5-17 near-sdk-core/…/base64_vec.rs• L139-237 near-sdk-core/…/mod.rs• L7-10
Error contracts
FunctionError is the small interface for errors returned from methods marked with #[handle_result]. It turns a typed error into a runtime panic message. Abort supplies the no-message variant for a method that must stop without exposing a custom error.
This error boundary is separate from JSON result data. A successful result is serialized for the caller. An error uses the runtime failure path instead, so clients must treat the method result and the transaction outcome as different parts of the contract interface.
References: near-sdk-core/…/error.rs• L1-39 near-sdk-core/…/error.rs• L41-93 near-sdk/…/lib.rs• L1565-1596
Utility support
Logs and assertions
The SDK utility layer provides the small operations that preserve these boundaries during contract execution. log! formats ordinary diagnostic text through the runtime log API, while require! and related checks stop execution through the runtime when a condition is false. Event emission uses the same log channel but adds the NEP-297 marker so readers can distinguish structured records.
These helpers affect observable contract behavior. A log is persisted on chain, and an assertion changes the call from a successful result to a failed execution. Use Runtime environment and execution context for the runtime APIs behind these helpers.
References: near-sdk/…/mod.rs• L1-40 near-sdk/…/mod.rs• L42-88 near-sdk/…/env.rs• L2506-2526 near-sdk-core/…/events.rs• L83-91
Type support
The SDK re-exports core types through near_sdk, while near-sdk-core keeps the reusable type and JSON layer available without the full contract toolkit. The public re-exports let contract code use one namespace for account, token, gas, key, hash, and JSON helper types. Feature selection controls which serialization, schema, bounded-type, and host-only interop traits are available. The event metadata trait keeps the same shape across feature combinations.
This split lets indexers, CLIs, and frontends use the same value definitions as contracts without pulling in the full smart contract SDK. It also keeps host-only testing types separate from the types that a WebAssembly contract needs. Bounded types are opt-in through the unstable feature, while serialization and ABI support are enabled by their matching core features. See Promises and cross-contract calls for asynchronous result types and Persistent collections and store APIs for storage values.
The core crate's dependency and feature contract also keeps host-only crypto support off WebAssembly targets. This allows unit-testing support to use host interop without forcing the native crypto dependency into contract builds. Contracts and off-chain tools therefore share the core definitions while selecting only the capabilities needed by their target.
References: near-sdk/…/mod.rs• L1-10 near-sdk/…/lib.rs• L1613-1626 near-sdk-core/README.md• L1-14 near-sdk-core/…/events.rs• L94-105 near-sdk/…/vm_types.rs• L1-36 near-sdk-core/Cargo.toml• L43-57 near-sdk-core/Cargo.toml• L66-117
Change checklist
When these files or sections are changed, remember to consider these:
- Event enum variants, fields, Serde attributes, or versions: check indexer parsers and every caller that consumes the NEP-297 record.
- Method serializer choices or public type attributes: check the matching caller serializer and the generated ABI schema.
- JSON helper encodings: check client code that treats large integers, bytes, hashes, or keys as text.
- Core type display or parse rules: check stored JSON, event payloads, cross-contract arguments, and external API examples.
- Bounded string, vector, or byte limits: check client validation, generated JSON schema limits, supported JSON and Borsh paths, and any nested value that can still grow without a bound.
- Event log construction or runtime logging: check the
EVENT_JSON:prefix and the distinction between structured events and ordinary logs. near-sdk-corefeature flags or dependency versions: check which serialization, schema, bounded-type, and host-only interop traits are available to each contract or support-tool build.- Core type exports or gas weight behavior: check callers that import
AccountIdReforGasWeight, and confirm weighted gas calls still use the intended default and relative shares.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A caller uses JSON while the method expects Borsh, or the reverse. | The contract cannot decode the input or the caller cannot decode the result. | Keep the serializer choice in the method contract and ABI aligned on both sides. |
| An event variant has no version or the event declaration has no standard. | The event declaration fails to compile. | Set one string standard and one event_version on every variant. |
| An event changes its name, version, or payload shape without a reader plan. | Indexers and clients can ignore the event or read it incorrectly. | Treat event metadata and payload fields as versioned public API. |
| A large integer is sent as a normal JSON number. | A client can round the value and use the wrong amount. | Use U64, U128, I64, or I128 for large JSON-facing integers. |
| Raw bytes use an unexpected JSON layout. | A caller cannot decode the value as the agreed text form. | Use Base64VecU8 or BoundedBase64VecU8 when the boundary calls for Base64 bytes. |
A JSON caller tries to deserialize BoundedVec. | The value cannot be decoded even when the array has an allowed number of elements. | Use BoundedBase64VecU8 for bounded byte strings or a JSON-capable type for bounded arrays. |
| An input exceeds a bounded string, vector, or byte limit. | Construction or supported deserialization fails before contract logic receives the value. | Set limits that match the product contract and validate client input against the same bounds. |
A structured event is logged without EVENT_JSON: or is sent only through an ordinary log helper. | NEP-297 readers do not recognize it as an event. | Emit through the generated event method or the standard event helper. |
A build enables a type feature without its matching core dependency feature, or uses bounded types without unstable. | A contract or support tool loses the required serializer, schema, or type export. | Treat near-sdk-core feature groups as part of the public build contract. |
A caller uses GasWeight with the wrong relative value or assumes a zero default. | Unused gas is shared in an unexpected way across function calls. | Use explicit weights when distribution matters and remember that the default weight is one. |
Key files
| File | Why to read it |
|---|---|
| near-sdk/…/lib.rs | Public guide for serializer choices, event declarations, schemas, and the SDK re-exports. |
| near-sdk-core/README.md | Explains how the core type crate serves off-chain callers without the full SDK. |
| near-sdk-core/Cargo.toml | Defines the core crate's optional serialization, schema, bounded-type, and host interop capabilities. |
| near-sdk-core/…/events.rs | Shared NEP-297 representation and the conversion points from typed events to JSON and log lines. |
| near-sdk-macros/…/mod.rs | Rules for accepting event declarations and attaching the event standard. |
| near-sdk-macros/…/lib.rs | Generated event methods, metadata accessors, and the AsNep297Event implementation. |
| near-sdk-core/…/mod.rs | Public list of JSON helper types. |
| near-sdk-core/…/integers.rs | Safe string forms for 64-bit and 128-bit integers. |
| near-sdk-core/…/vector.rs | Base64 representation for byte vectors. |
| near-sdk-core/…/hash.rs | Base58 representation and validation for crypto hashes. |
| near-sdk-core/…/mod.rs and near-sdk-core/…/public_key.rs | Core account, token, gas, hash, account reference, gas weight, and public-key types used at contract boundaries. |
| near-sdk-core/…/mod.rs | Common bounds, error behavior, and public exports for length-limited contract values. |
| near-sdk-core/…/string.rs | Bounded UTF-8 strings with JSON, Borsh, and schema boundary support. |
| near-sdk-core/…/vec.rs | Bounded element vectors and their Borsh and JSON behavior. |
| near-sdk-core/…/base64_vec.rs | Bounded byte values with Base64 JSON representation. |
| near-sdk-macros/…/abi_generator.rs | Mapping between serializer choice and the ABI schema exposed to tools. |
| near-contract-standards/…/events.rs and near-contract-standards/…/events.rs | Concrete interoperable event records for fungible and non-fungible token actions. |
| near-sdk/…/event_tests.rs | End-to-end examples of event JSON shape, metadata access, log emission, and payload forms. |