Skip to content

Conversation

@r-near
Copy link
Contributor

@r-near r-near commented Jun 18, 2025

Summary

Implements support for NEAR's global contract functionality (NEP-591) in near-sdk-rs, adding both low-level FFI bindings and high-level Promise APIs.

This addresses issue #1365 and implements the bounty requirements for global contract support.

Changes

Low-level API (near-sys):

  • Added 4 new host function bindings for global contracts:
    • promise_batch_action_deploy_global_contract
    • promise_batch_action_deploy_global_contract_by_account_id
    • promise_batch_action_use_global_contract
    • promise_batch_action_use_global_contract_by_account_id

High-level API (near-sdk):

  • Extended Promise struct with chainable global contract methods
  • Added corresponding high-level wrapper functions in env.rs
  • Updated mock environment for testing

Feature Gating:

  • All global contract functionality is gated behind a global-contracts feature flag
  • Ensures compatibility with older near-sandbox versions that don't support global contracts
  • Prevents build failures in other examples when using older runtime versions
  • Must be explicitly enabled: near-sdk = { features = ["global-contracts"] }

Example & Tests:

  • New factory-contract-global example demonstrating:
    • Global contract deployment patterns
    • Multisig factory use case (cost savings)
    • Business onboarding scenarios
  • Comprehensive integration tests using near-workspaces
  • Unit tests for all new functionality

Use Cases (from NEP-591)

  • Multisig Contracts: Deploy once, use for many wallets without paying 3N storage each time
  • Smart Contract Wallets: Efficient user onboarding with chain signatures
  • Business Onboarding: Companies can create user accounts cost-effectively
  • DeFi Templates: Share common contract patterns across protocols

⚠️ Important Dependency Disclaimers

This PR cannot be merged yet due to runtime dependencies:

Current Status

  • Global contract host functions are implemented in nearcore but not yet released
  • This implementation is ready and waiting for runtime support
  • Tests pass using a specific nearcore commit hash

Required Release Order

  1. nearcore 2.7.0 must be released (includes global contract host functions)
  2. near-primitives, near-crypto, near-jsonrpc-primitives will be auto-published
  3. near-jsonrpc-client-rs needs update for 2.7 compatibility (breaking changes)
  4. near-workspaces-rs needs update to use new jsonrpc-client
  5. Only then can this PR's dependencies be updated to use proper versions

Current Workarounds

This PR uses git branch dependencies in Cargo.toml:

[patch.crates-io]
near-primitives = { git = "https://github.com/near/nearcore.git", branch = "jsonrpc-v32" }
near-crypto = { git = "https://github.com/near/nearcore.git", branch = "jsonrpc-v32" }
# ... etc

These must be removed before merging once proper crate versions are available.

Test Plan

  • Unit tests for all new APIs
  • Integration tests with near-workspaces using pinned nearcore version
  • Factory contract example with realistic scenarios
  • Cost comparison demonstrations
  • Mock environment support for testing
  • Feature flag gating to ensure compatibility

Links

Implements both low-level FFI bindings and high-level Promise APIs for NEAR's
global contract functionality, enabling cost-effective factory contract patterns.

Changes:
- Add 4 new host function bindings in near-sys
- Extend Promise struct with chainable global contract methods
- Add factory-contract-global example with comprehensive tests
- Support multisig factories, business onboarding, and DeFi templates

Addresses: #1365
Bounty: https://nearn.io/devhub/14/
NEP-591: https://github.com/near/NEPs/blob/master/neps/nep-0591.md
@codecov
Copy link

codecov bot commented Jun 18, 2025

Codecov Report

❌ Patch coverage is 79.31034% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.75%. Comparing base (93ebb5f) to head (d464f33).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
near-sdk/src/json_types/hash.rs 0.00% 2 Missing ⚠️
near-sdk/src/types/public_key.rs 0.00% 2 Missing ⚠️
...cros/src/core_impl/contract_metadata/build_info.rs 0.00% 1 Missing ⚠️
near-sdk-macros/src/lib.rs 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1369      +/-   ##
==========================================
+ Coverage   80.63%   80.75%   +0.11%     
==========================================
  Files         104      104              
  Lines       15457    15462       +5     
==========================================
+ Hits        12464    12486      +22     
+ Misses       2993     2976      -17     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

r-near added 4 commits June 17, 2025 22:34
To ensure compatibility with older near-sandbox versions that don't
support global contracts, gate all global contract functionality
behind a 'global-contracts' feature flag.

Changes:
- Add 'global-contracts' feature flag to near-sdk and near-sys
- Gate FFI bindings in near-sys behind feature flag
- Gate env.rs functions behind feature flag
- Gate Promise API methods and actions behind feature flag
- Gate mock implementations behind feature flag
- Update factory-contract-global example to use feature flag

This prevents build failures in other examples when using older
near-sandbox versions that lack global contract support.
Add fallback match arms for DeployGlobalContract and UseGlobalContract
variants when the 'global-contracts' feature is not enabled. This
prevents compilation errors due to non-exhaustive pattern matching
when the feature flag is disabled but the upstream MockAction enum
still contains these variants.

The fallback cases panic with a helpful error message indicating
that the 'global-contracts' feature flag is required.
- Add tests for Promise global contract methods (deploy_global_contract, use_global_contract, etc.)
- Add tests for MockAction global contract variants and receipt_index() method
- Add tests for LogicMockAction conversion with proper type handling
- Add panic tests for global contract fallback when feature is disabled
- All tests are properly feature-gated with #[cfg(feature = "global-contracts")]
- Tests verify correct action creation and proper error handling
@frol
Copy link
Collaborator

frol commented Jun 19, 2025

@r-near The implementation looks great! I only left a couple of comments in the contract-factory-global example.

- Replace Vec<u8> with Base64VecU8 for code parameters to follow best practices
- Use CryptoHash type for storing deployed contract hashes
- Return Base58CryptoHash from get_global_contract_hash instead of raw bytes
- Use env::attached_deposit() instead of explicit amount parameters
- Fix type conversions and test compilation issues
@r-near r-near requested a review from frol June 19, 2025 20:01
@frol
Copy link
Collaborator

frol commented Jun 25, 2025

I'm waiting for the nearcore release to testnet, and once it is there, I'll merge this PR, and once it is live on mainnet, I'll cut the next release for near-sdk

@petersalomonsen
Copy link

petersalomonsen commented Aug 15, 2025

Looking forward to see this merged @frol @r-near . It works great, I've tested all of it here: petersalomonsen/session_vault_factory#1

( used the sandbox build for 2.7.0 btw )

@r-near
Copy link
Contributor Author

r-near commented Aug 15, 2025

Looking forward to see this merged @frol @r-near . It works great, I've tested all of it here: petersalomonsen/session_vault_factory#1

( used the sandbox build for 2.7.0 btw )

Glad that it works for you! We still need to get the dependencies sorted out, but once those are published, I'll update the PR to use the new versions.

@frol frol force-pushed the global-contracts branch from 2affa35 to d464f33 Compare August 19, 2025 05:10
Copy link
Collaborator

@frol frol left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@race-of-sloths score 8

@race-of-sloths
Copy link

race-of-sloths commented Aug 19, 2025

@r-near Thank you for your contribution! Your pull request is now a part of the Race of Sloths!
Do you want to apply for monthly streak? Get 8+ score for a single PR this month and receive boost for race-of-sloths!

Shows inviting banner with latest news.

Shows profile picture for the author of the PR

Current status: executed
Reviewer Score
@frol 8

Your contribution is much appreciated with a final score of 8!
You have received 90 (80 base + 10 monthly bonus) Sloth points for this contribution

@frol received 25 Sloth Points for reviewing and scoring this pull request.

Congratulations @r-near! Your PR was highly scored and you completed another monthly streak! To keep your monthly streak make another pull request next month and get 8+ score for it

What is the Race of Sloths

Race of Sloths is a friendly competition where you can participate in challenges and compete with other open-source contributors within your normal workflow

For contributors:

  • Tag @race-of-sloths inside your pull requests
  • Wait for the maintainer to review and score your pull request
  • Check out your position in the Leaderboard
  • Keep weekly and monthly streaks to reach higher positions
  • Boast your contributions with a dynamic picture of your Profile

For maintainers:

  • Score pull requests that participate in the Race of Sloths and receive a reward
  • Engage contributors with fair scoring and fast responses so they keep their streaks
  • Promote the Race to the point where the Race starts promoting you
  • Grow the community of your contributors

Feel free to check our website for additional details!

Bot commands
  • For contributors
    • Include a PR: @race-of-sloths include to enter the Race with your PR
  • For maintainers:
    • Invite contributor @race-of-sloths invite to invite the contributor to participate in a race or include it, if it's already a runner.
    • Assign points: @race-of-sloths score [1/2/3/5/8/13] to award points based on your assessment.
    • Reject this PR: @race-of-sloths exclude to send this PR back to the drawing board.
    • Exclude repo: @race-of-sloths pause to stop bot activity in this repo until @race-of-sloths unpause command is called

@frol frol merged commit deae7bb into master Aug 19, 2025
42 of 43 checks passed
@github-project-automation github-project-automation bot moved this from NEW❗ to Shipped 🚀 in DevTools Aug 19, 2025
@frol frol deleted the global-contracts branch August 19, 2025 05:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Shipped 🚀

Development

Successfully merging this pull request may close these issues.

5 participants