Introduction
The NEAR Protocol has emerged as a significant player in the blockchain space, offering a developer-friendly platform for building decentralized applications (dApps). While NEAR has traditionally supported JavaScript/TypeScript and Rust for smart contract development, the introduction of the Python SDK opens up new possibilities for Python developers to join the blockchain ecosystem.
This guide explores the NEAR SDK for Python (near-sdk-py
), a toolkit that allows developers to write smart contracts for the NEAR blockchain using Python. By leveraging the familiarity and accessibility of Python, this SDK lowers the barrier to entry for blockchain development and expands NEAR’s developer community.
What is NEAR Protocol?
Before diving into the SDK, let’s understand what NEAR Protocol is:
NEAR is a layer-1 blockchain designed for usability and scalability. It uses a Proof-of-Stake consensus mechanism and implements sharding (called “Nightshade”) to achieve high transaction throughput. NEAR aims to make blockchain more accessible to developers and end-users alike with features like human-readable account names and developer-friendly tools.
Bridging AI and Blockchain: Python as the Common Language
The NEAR SDK for Python creates a strategic bridge for AI developers to enter the blockchain space. With Python firmly established as the dominant language in machine learning—powering TensorFlow, PyTorch, and scikit-learn—this SDK eliminates the need for AI specialists to learn entirely new programming paradigms.
This familiarity enables AI developers to build smart contracts that integrate machine learning capabilities directly on-chain. Examples include deploying prediction markets with statistical models or creating privacy-preserving recommendation systems. Rather than wrestling with unfamiliar language constructs, developers can focus on the innovative aspects of blockchain integration.
As decentralized AI grows in importance, this SDK becomes essential for building trustless AI systems where model parameters, data access rights, and inference processes are managed through smart contracts. This convergence of AI expertise and blockchain capabilities through Python has the potential to accelerate innovation at this technological intersection.
The NEAR SDK for Python: Overview
The near-sdk-py
repository provides Python developers with the tools needed to write, test, and deploy smart contracts on the NEAR blockchain. It serves as a bridge between Python’s simplicity and NEAR’s blockchain capabilities.
Key Components of near-sdk-py
Based on exploration of the repository, the SDK includes:
- Core Contract Framework: Functions and decorators for defining smart contracts
- Storage Management: Tools for handling persistent storage on the blockchain
- Types and Collections: Specialized data structures for blockchain operations
- Testing Utilities: Frameworks for testing contracts before deployment
- Build Tools: Mechanisms to compile Python contracts to WebAssembly for the NEAR runtime
Getting Started with near-sdk-py
Installation
To start using the NEAR SDK for Python, you’ll need to set up your development environment:
pip install near-sdk-py
Additionally, you’ll need the NEAR CLI to interact with contracts on the blockchain:
npm install -g near-cli
Project Structure
A typical NEAR Python project might have the following structure:
my-near-project/
├── contract/
│ ├── __init__.py
│ └── contract.py # Main contract code
├── tests/
│ ├── __init__.py
│ └── test_contract.py
├── build.sh # Build script
└── README.md
Writing Your First Smart Contract
Let’s examine how to write a simple smart contract using the NEAR SDK for Python:
from near_sdk import near, json, AccountId, NearConfig, Balance
# Initialize the contract with a decorator
@near.contract(config=NearConfig)
class MyFirstContract:
def __init__(self):
# Initialize contract state
self.owner_id = near.predecessor_account_id()
self.message = "Hello, NEAR!"
# Define a view method to read state
@near.view
def get_message(self) -> str:
return self.message
# Define a change method to modify state
@near.call
def set_message(self, new_message: str) -> str:
# Only the owner can change the message
assert near.predecessor_account_id() == self.owner_id, "Only the owner can change the message"
old_message = self.message
self.message = new_message
return f"Message changed from '{old_message}' to '{new_message}'"
# Define a payable method
@near.payable
def donate(self) -> str:
# Record the donation amount
amount = near.attached_deposit()
return f"Thank you for donating {amount} yoctoNEAR!"
Key Concepts in the Code:
- Contract Decorator:
@near.contract
marks the class as a NEAR smart contract. - View Methods: Functions marked with
@near.view
read contract state without modifying it. - Call Methods: Functions marked with
@near.call
can modify contract state. - Payable Methods: Functions marked with
@near.payable
can receive NEAR tokens. - Contract Context: Functions like
near.predecessor_account_id()
provide blockchain context.
Core Concepts in NEAR Python Development
State and Storage
One of the fundamental aspects of smart contracts is managing state. In the NEAR Python SDK, there are several ways to handle persistent storage:
from near_sdk import near, PersistentMap, PersistentVector, PersistentUnorderedMap
@near.contract
class StorageExample:
def __init__(self):
# Different types of persistent collections
self.map = PersistentMap(b"m", key_type=str, value_type=int)
self.vector = PersistentVector(b"v", element_type=str)
self.unordered_map = PersistentUnorderedMap(b"u", key_type=str, value_type=str)
The SDK provides specialized collection types that automatically handle the serialization and deserialization of data to and from blockchain storage.
Cross-Contract Calls
Smart contracts often need to interact with other contracts. The NEAR Python SDK facilitates this with asynchronous calls:
@near.call
def call_another_contract(self, contract_id: str, message: str) -> None:
# Create a promise to call another contract
promise = near.promise_create(
contract_id,
"set_message",
json.dumps({"new_message": message}).encode(),
0, # No attached deposit
near.prepaid_gas() // 2 # Use half of the remaining gas
)
# Return the promise to process the result
return near.promise_return(promise)
Testing Smart Contracts
The SDK provides utilities for testing contracts before deployment:
from near_sdk.testing import VMContext, setup_context
def test_get_message():
# Set up a test context
context = VMContext(
current_account_id="contract.near",
signer_account_id="alice.near",
predecessor_account_id="alice.near",
attached_deposit=0,
account_balance=1000000
)
setup_context(context)
# Initialize the contract
contract = MyFirstContract()
# Test the view method
assert contract.get_message() == "Hello, NEAR!"
Advanced Features
Function Call Permissions
NEAR has a robust permission system for contract calls:
@near.call(is_private=True)
def private_method(self) -> str:
# This method can only be called by the contract itself
return "This is private"
@near.call(can_be_called_by=["user.near", "admin.near"])
def restricted_method(self) -> str:
# This method can only be called by specific accounts
return "Access granted"
Handling NEAR Tokens
Working with tokens is common in blockchain applications:
@near.payable
def process_payment(self, product_id: str) -> str:
# Get the amount of tokens attached to the call
payment = near.attached_deposit()
# Check if payment is sufficient
price = self.products[product_id]
assert payment >= price, f"Insufficient payment, required {price}"
# Process the order
if payment > price:
# Refund excess payment
refund = payment - price
near.promise_create(
near.predecessor_account_id(),
"deposit",
b"{}",
refund,
near.prepaid_gas() // 10
)
return "Order processed successfully"
Deploying Your Contract
After writing and testing your contract, you’ll need to compile it to WebAssembly and deploy it to the NEAR blockchain:
# Build the contract
./build.sh
# Deploy to NEAR testnet
near deploy --accountId mycontract.testnet --wasmFile build/contract.wasm
Interacting with Your Contract
Once deployed, you can interact with your contract using the NEAR CLI:
# Call a view method
near view mycontract.testnet get_message
# Call a change method
near call mycontract.testnet set_message '{"new_message": "Hello, World!"}' --accountId myaccount.testnet
# Call a payable method with attached NEAR
near call mycontract.testnet donate --amount 1 --accountId myaccount.testnet
Best Practices for NEAR Python Development
- Use Type Hints: Python’s type hints improve code quality and help catch errors early.
- Prioritize Gas Efficiency: Blockchain operations cost gas, so optimize your code for efficiency.
- Handle Errors Gracefully: Use assertions and error handling to make contracts robust.
- Test Thoroughly: Extensive testing is crucial before deploying contracts to the mainnet.
- Implement Security Measures: Always validate inputs and implement proper access controls.
- Document Your Code: Clear documentation helps others understand your contract’s purpose and functionality.
Comparison with Other NEAR SDKs
Feature | near-sdk-py | near-sdk-js | near-sdk-rs |
---|---|---|---|
Language | Python | JavaScript/TypeScript | Rust |
Learning Curve | Low | Medium | High |
Performance | Good | Good | Excellent |
Ecosystem Maturity | Emerging | Established | Established |
Type Safety | Optional | Optional (TS) | Strong |
Conclusion
The NEAR SDK for Python represents a significant step toward making blockchain development more accessible. By leveraging Python’s simplicity and readability, developers can more easily create and deploy smart contracts on the NEAR blockchain.
Whether you’re building a simple token contract or a complex decentralized application, the Python SDK provides the tools needed to bring your ideas to life on the NEAR Protocol. As the ecosystem continues to grow, Python developers will play an increasingly important role in shaping the future of decentralized applications.