Introducing a new way to review your PRs.

Read the announcement

near / near-sdk-rs

Rust library for writing NEAR smart contracts

View on GitHub

20 documents · Updated Nov 20, 2026

docs / contract-build-and-example-workflows

Contract build and example workflows

The repository uses cargo near as the main path to turn a Rust NEAR contract into a deployable WebAssembly artifact. Docker builds, size tools, example contracts, and CI checks support that path by making artifacts repeatable, small, and tested before deployment. Contract source patterns are covered in contract SDK authoring, while contract standards and global contracts explain related contract behavior.

Contract artifact model

Build outputs

The contract build produces WebAssembly for deployment and, by default, an ABI that describes the contract interface. A normal build is suitable for local work. A reproducible build uses a controlled build environment so that the same source and dependency inputs can produce the same artifact on different machines. The example workflows place these outputs under each example's target/near directory.

The build mode sets the purpose of the artifact:

Build modeMain useImportant property
non-reproducible-wasmLocal development and quick deploy checksFast contract build without a fixed cross-machine output guarantee
reproducible-wasmRelease work and CI size checksControlled build intended to make output comparison meaningful

The example READMEs use cargo near deploy build-non-reproducible-wasm after a local build. Deployment therefore consumes the artifact created by the selected build flow instead of asking engineers to assemble a Wasm file by hand.

References: README.md• L276-311 .github/…/sizes_baseline.yml• L45-68 examples/…/README.md• L5-30 examples/…/Cargo.toml• L23-50

Reproducible build environment

The contract-builder helper provides a Docker environment for builds that must behave consistently across host machines. Its image includes a pinned Rust toolchain and the Wasm target. The image build can publish an architecture-specific image tag, while the run helper mounts a host contract directory at /host for work inside the container.

The example manifests now describe the same build contract in their package.metadata.near.reproducible_build sections. The manifests identify the sourcescan/cargo-near:0.21.1-rust-1.96.1 image by digest and specify a locked cargo near build non-reproducible-wasm command for that metadata-driven container build. The repository-wide Docker script still invokes cargo near build reproducible-wasm --no-locked for the demo set because these example workspaces do not carry committed lock files. A product contract that needs a stable release artifact should keep its dependency lock data under version control and use a locked build.

This distinction keeps the two workflows clear. The manifest records the pinned environment and locked command expected by a reproducible build description. The example script is a broad demonstration path that resolves the demo dependencies without a lock file. Several integration suites also call the cargo near build API with an explicit member manifest, so their sandbox receives the same kind of contract artifact that the normal build flow produces.

References: contract-builder/README.md• L1-42 contract-builder/Dockerfile• L1-14 contract-builder/build.sh• L4-28 contract-builder/run.sh• L1-10 examples/build_all_docker.sh• L27-35 examples/…/Cargo.toml• L31-50 examples/…/Cargo.toml• L16-28 examples/…/Cargo.toml• L17-29 examples/…/workspaces.rs• L7-22 examples/…/workspaces.rs• L25-37

Artifact production workflows

Local example builds

The example build scripts provide one repeatable way to exercise the contract build tool across the supported examples. examples/build_all.sh builds each Wasm-producing example with the non-reproducible mode. examples/build_all_docker.sh runs the same set through the reproducible mode intended for a controlled environment. Workspace examples are listed by their contract members, so one example can produce more than one deployable artifact.

The high-level local flow is:

flowchart LR
    S[Contract source] --> B[cargo near build]
    B --> W[Wasm artifact]
    B --> A[ABI]
    W --> D[cargo near deploy]
    W --> V[Tests and size checks]

Use a non-reproducible build for a quick development cycle. Use the reproducible build when another machine or CI must compare the resulting artifact. The examples show both forms so that the same contract can be built locally, tested, and then checked in the release-style path.

References: examples/build_all.sh• L1-39 examples/build_all_docker.sh• L1-39 examples/…/README.md• L5-45 examples/…/README.md• L14-67 examples/…/Cargo.toml• L27-31 examples/…/Cargo.toml• L25-28

Contract builder image builds

The contract-builder scripts manage the build image rather than the contract artifact itself. The image is built for either amd64 or arm64, tagged with the branch and commit, and pushed to the project container registry. Engineers then run the image with the contract source mounted into it and invoke the normal build commands from /host.

This path matters when host compiler versions or operating systems could change the bytes in a deployable artifact. It does not replace cargo near; it gives that build command a stable environment.

References: contract-builder/build.sh• L4-28 contract-builder/run.sh• L1-10

Artifact minification

The minifier directory contains an optional Wasm size-reduction flow. It removes selected standard-library code, removes code that becomes unreachable, drops unused Wasm sections, and applies a final optimizer pass. The result is a new minified-<name>.wasm file while a stripped copy gives a size point of comparison.

This tool is retained for cases that need extra size reduction, but its own documentation says that it is not actively maintained. Its transformations can be aggressive and can change runtime behavior. Treat minification as a separate artifact variant and run the contract's tests against that exact variant before deployment.

References: minifier/README.md• L1-18 minifier/minify.sh• L3-13 minifier/minify_examples.sh• L14-21

Validation workflows

Local validation scripts

The repository has two shell entry points with different levels of coverage. run-tests.sh checks formatting and lint rules, runs workspace tests, and then tests and builds all examples. ci-test.sh also covers the dependency mode used for development and the released dependency mode. In its development path it adds a reproducible example build and example tests before it invokes ./…/size_all.sh; that size script is not present at the current repository path, so this entry point cannot complete the size step unless the script is supplied.

The core GitHub workflow separates source and package checks from a direct artifact-link check. Its cargo-hack matrix checks selected crates across Linux and macOS with pinned Rust 1.95 and floating stable. It exercises feature combinations in both off-chain and on-chain modes. Its test matrix runs the suite and doctests across the same toolchain families and feature sets, while stable skips the gas-budget performance test because those values depend on the pinned compiler. Other jobs cover lint, compilation, Windows Wasm checks, dependency audit, and generated documentation. The wasm-link job uses stable Rust and the latest cargo-near installer to build adder through the canonical user path. This guards against a toolchain change that allows source checks to pass but breaks real contract linking.

The validation sequence connects source checks to artifact checks:

flowchart TD
    C[Workspace and example source] --> L[Format and lint]
    L --> T[Unit and integration tests]
    T --> B[Build example Wasm]
    B --> X[Example and artifact checks]
    X --> R[Deployable artifact confidence]

References: run-tests.sh• L1-8 ci-test.sh• L3-36 .github/…/test.yml• L11-221 .github/…/test.yml• L223-293 examples/…/lib.rs• L50-72 examples/…/lib.rs• L46-69

Continuous integration example tests

The example workflows run contract tests on Linux and macOS with Rust 1.93 and the Wasm target installed. They split the examples into a main matrix and a smaller matrix to keep each job focused. cargo-nextest runs each example workspace with the CI test profile, while warning denial and an RPC timeout make the environment stricter and less likely to hide a remote test failure.

These workflows validate behavior at the example level. The local all-examples script also builds each example after its tests, so a contract can pass host-side tests and still fail the artifact build before the script succeeds. Several integration suites build a selected contract member through the cargo near build API, deploy those exact bytes to a sandbox, and then exercise the deployed interface. This adds an artifact-level check to behavior checks that run only in the host process.

References: .github/…/test_examples.yml• L1-66 .github/…/test_examples_small.yml• L1-61 examples/test_all.sh• L7-40 examples/…/workspaces.rs• L3-19 examples/…/workspaces.rs• L7-30 examples/…/workspaces.rs• L25-76 examples/…/workspaces.rs• L13-42 examples/…/utils.rs• L44-89

Example artifact tests

Example artifact tests use a sandbox as the boundary between contract code and a deployable Wasm file. They build the target contract or workspace member, deploy the resulting bytes, initialize any required companion contracts, and assert returned values, state changes, and expected failures.

The main validation patterns are:

PatternWhat it provesRepresentative examples
Single-contract deploymentA contract can be built, deployed, initialized, and called through its public interfaceadder, callback-results, test-contract
Multi-contract setupDependent contracts can be built and used togetherfactory-contract, fungible-token, non-fungible-token, factory-contract-global
Contract feature behaviorAsync callbacks, token rules, private initialization, state upgrades, and locked balances work after deploymentcallback-results, fungible-token, lockable-fungible-token, test-contract, versioned
ABI and external-response checksThe artifact exposes its ABI and can complete or time out when an outside service respondsstatus-message, mission-control, mpc-contract

This pattern makes the examples useful as supported workflows rather than only code samples. A source change is considered in the context of the artifact that the sandbox receives and the other contracts that artifact must work with. The ABI examples also check the deployed artifact's embedded interface, not only its Rust-level behavior.

References: examples/…/lib.rs• L50-72 examples/…/lib.rs• L91-177 examples/…/workspaces.rs• L7-50 examples/…/workspaces.rs• L7-190 examples/…/workspaces.rs• L25-99 examples/…/workspaces.rs• L13-60 examples/…/utils.rs• L44-149 examples/…/lib.rs• L76-91 examples/…/mission_control.rs• L101-117 examples/…/lib.rs• L79-95 examples/…/lib.rs• L150-165

Contract size comparison

The size workflows use reproducible builds as their measurement input. A baseline run records the byte size of each Wasm output. A pull request run builds the same example set, creates a current size record, and compares it with the baseline for the target branch.

The comparison treats new and removed artifacts as changes and flags size increases at or above the configured one percent threshold. It creates a Markdown report and uses hidden markers to decide whether CI should fail on an increase. A missing baseline produces a warning and an empty baseline instead of a false comparison.

References: .github/…/sizes_baseline.yml• L17-75 .github/…/compare_sizes.yml• L19-129 ci/compare_sizes.py• L46-151

Example contract set

Contract feature examples

The examples are reference contracts and build targets. They show how the SDK's common contract patterns become deployable Wasm and how those artifacts are tested in isolation or as a group.

Example groupContract concern shownArtifact shape
adder, status-message, test-contractSmall single-contract build and deploy cycleOne contract artifact
callback-results, cross-contract-callsCalls between contracts and callback handlingOne or more coordinated contracts
fungible-token, non-fungible-token, lockable-fungible-tokenToken contract standards, locked balances, and related receiversStandard contract plus test or receiver contracts where needed
factory-contract, factory-contract-globalContract creation and global contract useFactory and related contract artifacts
versionedState-aware contract upgrade patternOne versioned contract artifact
mission-control, mpc-contractLarger application-shaped contract behaviorContract artifact with broader integration tests

The workspace examples are important because their top-level directory is not always the artifact boundary. The build workflow enters each member that produces Wasm, while the test workflow runs the example workspace as one behavior group. The workspace manifests make this boundary explicit for multi-contract examples such as cross-contract-calls, factory-contract, fungible-token, and non-fungible-token. Their tests then build the relevant member artifacts and bring the needed receivers or dependent contracts into the same sandbox.

References: examples/…/README.md• L5-45 examples/…/README.md• L5-45 examples/…/README.md• L14-65 examples/…/README.md• L14-69 examples/…/Cargo.toml• L30-52 examples/…/Cargo.toml• L16-31 examples/…/Cargo.toml• L24-26 examples/…/Cargo.toml• L25-28 examples/…/Cargo.toml• L26-29 examples/…/workspaces.rs• L3-19 examples/…/workspaces.rs• L24-50 examples/…/workspaces.rs• L40-99 examples/…/utils.rs• L59-149

Deployment demonstrations

Most example READMEs present the same sequence: build a local Wasm artifact, create a testnet development account, deploy the named build output, and optionally repeat the build in reproducible mode. These are demonstrations of the supported contract lifecycle, not release artifacts for production use.

The global-contract example has an extra runtime condition. Its integration behavior needs nearcore support for global contracts, so a successful build does not mean that the deployment demonstration can run on every released network version.

References: examples/…/README.md• L5-30 examples/…/README.md• L14-77 examples/…/workspaces.rs• L7-136 examples/…/Cargo.toml• L28-45

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the example directory lists in examples/build_all.sh, examples/build_all_docker.sh, examples/test_all.sh, and the two example CI matrices aligned with the set of supported contract targets.
  • Preserve the distinction between non-reproducible-wasm for local work and reproducible-wasm for artifact comparison. Keep the manifest image digest and container build command aligned with the intended locked or unlocked dependency policy.
  • If an example workspace gains or loses a Wasm member, check both artifact collection under target/near and the size baseline keys. The size report identifies missing artifacts as removed contracts.
  • If a test builds a contract through an explicit manifest, keep that manifest path and the deployed artifact tied to the intended workspace member. This is especially important when a workspace contains receivers, factories, or more than one contract.
  • If the minifier changes, test the minified Wasm itself. A passing test of the unminified output does not validate the transformed deployment artifact.
  • If the contract-builder image changes, review its Rust and Wasm toolchain assumptions together with the image tags and digests used by the build path.
  • If an example integration test changes its build target or companion contracts, keep the artifact path, deployment setup, and method assertions aligned. A test can otherwise deploy a valid but wrong contract.
  • If ABI generation or embedded ABI checks change, review both the build metadata and the deployed __contract_abi checks in the ABI examples.
  • If sandbox protocol versions or callback timing assumptions change, review tests that inspect receipt outcomes, wait for external responses, or depend on global-contract support.
  • If the core CI toolchain or cargo-near installer changes, keep the stable wasm-link job on the canonical user build path so source checks do not replace artifact-link coverage.

Important failure modes

TriggerConsequenceGuard
A contract builds on the host but does not link for WasmCI or deployment fails after source tests passThe stable wasm-link job builds a real example through cargo near
A demo reproducible build uses --locked without a committed lock fileThe build cannot resolve the intended dependency setUse the documented --no-locked demo flow or commit a lock file for a real reproducible release
A manifest image digest or build command differs from the controlled build policyTwo builds can use different tools or dependency rulesKeep the shared image digest and container command aligned across contract manifests
A workspace member is omitted from a build listIts Wasm is not produced or measuredKeep build lists and matrix entries aligned with workspace members
An explicit test manifest points to the wrapper or a different member instead of the deployable contractThe sandbox test validates the wrong artifactUse the member manifest that produces the intended Wasm and assert the expected interface after deployment
Minification removes code needed at runtimeThe deployed contract can fail even though the original artifact passedTest the exact minified artifact before deployment
No baseline exists for a size comparisonThe report cannot show a meaningful regression against the target branchCI creates an empty baseline and warns; establish a baseline before treating size results as a release signal
Global-contract tests run without supported nearcore featuresBuild may pass but integration or deployment behavior is unavailableRun those tests against a nearcore version with global-contract support
An integration test builds or deploys the wrong workspace memberAssertions fail for an unrelated interface or miss the changed contractKeep explicit member paths and deployment fixtures aligned with the intended artifact
A test reads a transaction before async callbacks or an external response finishThe test reports incomplete state or misses the final resultPoll for callback completion and use the example's timeout guard
A contract is tested without its required receiver or dependent contractA valid contract appears broken because its cross-contract precondition is missingInitialize all companion contracts before exercising the flow

Key files

FileWhy to read it
README.mdDefines the user-facing cargo near build and deploy workflow.
examples/build_all.shShows the complete local example build set.
examples/build_all_docker.shShows the reproducible example build set.
examples/test_all.shConnects example tests with a follow-up build of every example.
examples/…/Cargo.tomlShows the shared example build metadata, pinned image digest, and locked container command.
examples/…/Cargo.tomlShows how a workspace groups multiple Wasm-producing contract members.
examples/…/workspaces.rsShows direct cargo near artifact builds for high-level and low-level factory contracts.
examples/…/Cargo.tomlShows the workspace boundary for a contract and its dependent test contract.
examples/…/workspaces.rsShows multi-contract token setup and deployed artifact behavior checks.
examples/…/workspaces.rsShows direct artifact building and deployed checks for locked token balances.
examples/…/utils.rsShows how an NFT and its receiver contracts are built and initialized together.
examples/…/lib.rsShows a contract flow that waits for an outside response and handles success or timeout.
examples/…/mission_control.rsShows embedded ABI validation for an application-shaped contract.
examples/…/lib.rsShows a small stateful contract and an embedded ABI check.
examples/…/lib.rsShows artifact ABI checks and private initialization behavior.
examples/…/lib.rsShows how an example artifact preserves old state while moving it to a newer contract version.
contract-builder/README.mdExplains the Docker-based reproducible build environment.
contract-builder/DockerfileShows the toolchain and Wasm target supplied by that environment.
minifier/README.mdStates the status, risk, and transformation goals of the optional minifier.
minifier/minify.shShows the input-to-minified-artifact workflow.
ci-test.shDefines the broad local CI-style validation sequence.
.github/…/test.ymlContains core package checks and the real Wasm link regression guard.
.github/…/test_examples.ymlDefines the main cross-platform example test matrix.
.github/…/test_examples_small.ymlDefines the smaller cross-platform example test matrix.
.github/…/sizes_baseline.ymlBuilds examples and records baseline Wasm sizes.
.github/…/compare_sizes.ymlCompares pull request artifact sizes and publishes the report.
ci/compare_sizes.pyDefines which size changes are significant and which increases fail CI.
examples/…/README.mdDocuments a deployment example with a specific runtime requirement.