Scaling API-first – The story of a global engineering organization
Encode x NEAR: Technical Overview of NEAR 1
1. NEAR 101
An introductory workshop
for web developers
near.org
Workshop Preparation
Please complete the following steps before the workshop starts:
- [5 min] Install Node.js locally
- [2 min] Install NEAR CLI locally
- [3 min] Create a TestNet account on NEAR Protocol
If you have time, feel free to complete the following steps as well:
- Read and watch a few of the key articles about the NEAR platform:
- The Beginner’s Guide to NEAR Protocol
- Blockchain Infrastructure Landscape
- Watch Blockchain 101
- Deploy the Guestbook sample application (Gitpod or locally)
Available Recordings
- crowdcast.io/e/hacktherainbow/12
- crowdcast.io/e/hacktherainbow/6
- crowdcast.io/e/near-101---v0-4
- crowdcast.io/e/near-101---v0-3
- crowdcast.io/e/near-101---v0-2
- crowdcast.io/e/near-101---v0-1
6. - there are 2 main folders in the project:
- assembly contains the smart contract and tests
- src contains the application’s UX and tests
- there is another folder to be aware of:
- neardev contains contract account details
Guest Book
7. Guest Book (backend)
Contract Data Model : assembly/model.ts
- PostedMessage is a serializable class with three
attributes:
- premium to flag messages with attached
NEAR tokens
- sender to track the signer of the guest
book message
- text to hold the guest book message
- messages is a collection of guest book messages
stored as a PersistentVector of
PostedMessage objects
note: @nearBindgen marks the class as serializable
8. Contract Behavior : assembly/main.ts
- MESSAGE_LIMIT is used to avoid unbounded calls
(ie. potentially expensive) to retrieve guest book
messages from storage
- two public functions are exposed on the contract:
- addMessage()
- getMessages()
Guest Book (backend)
9. Guest Book (frontend)
Network Connection : src/config.js
- data and endpoints required to connect to the
NEAR network
- connection information is included for MainNet,
TestNet and BetaNet as well as the default
LocalNet configuration
10. Configuration : src/index.js
- configure connection to NEAR network
- configure contract interface by injecting
wallet connection and wiring up both
contract methods
Guest Book (frontend)
11. Guest Book (frontend)
Authentication : src/App.js
- NEAR Wallet is used for authentication
- near-api-js exposes two related methods
- wallet.requestSignIn()
- wallet.signOut()
note: useCallback() is a React Hook
12. CRUD : src/App.js
- add a message and, once complete, get a list of
all messages (up to MESSAGE_LIMIT)
Guest Book (frontend)
13. Monitoring the application ...
http post https://rpc.testnet.near.org
jsonrpc=2.0 id=dontcare
method=query params:='{
"request_type": "view_state",
"finality": "final",
"account_id": "test",
"prefix_base64": "U1RBVEU="
}’
And, using the watch command and some
JSON formatting with jq, automatically
refresh a convenient view while we use
the Guestbook example. Here’s how.
Also see here for our JSON RPC API docs
https://docs.near.org/docs/interaction/rpc
Guest Book
14. NEAR has two paths for extension
dApp UX development
- Use near-api-js to connect to
NEAR, manage accounts, call
contract methods and more
- Use JSON-RPC API to
communicate with NEAR from
any context (other than JS / TS)
- Manage devops with NEAR CLI
dApp Contract Development
- Use near-sdk-as to build
contracts using AssemblyScript
- Use near-sdk-rs to build
contracts using Rust
- Compose deployed contracts
using cross-contract calls
19. create-near-app
To start building on NEAR run the following* in your terminal:
npx create-near-app --help
* you must have Node.js installed to run npx
26. step #5 … n
- discover
- where do we setup a connection to NEAR?
hint: search the code for keyStore
- where do we login to the NEAR Wallet?
hint: search the code for requestSignIn
- which lines of code wire up the contract to our JS context?
hint: search the code for viewMethods or changeMethods
- control
- try to reverse the greeting string before writing on chain
hint 1: search for storage.set … AssemblyScript supports common Array and String functions
hint 2: message.split('').reverse().join('')
create-near-app
27. Rust
Pros
- Mature, battle-hardened compiler
- Thriving ecosystem
- Real world use cases
- near-sdk-rs makes life easy
Cons
- Steeper learning curve
AssemblyScript
Pros
- Easier for prototyping
- Trivial for JS and TS devs to learn
- Smaller binaries in Wasm
- Binaries are easier to read / debug
Cons
- Current compiler is not stable
- Immature ecosystem
AssemblyScript has its place
29. NEAR Explorer
- Monitor all public network activity including
validator nodes, block height, recent
transactions and account details
30. NEAR Wallet
- When your users log in, they will be
presented with this screen where they can
create a new account (funded with 500
NEAR tokens) and setup a preferred
recovery method
31. - When users are redirected back to your app,
they can check towill find in LocalStorage a
copy of the private keys giving your app
FunctionCall access to their account
- In Chrome Developer Tools
1. Open LocalStorage in the Application tab
2. Storage key name will be something like
near-api-js:keystore:ACCOUNT:default
3. Storage value will be the account private key
4. And using the code snippets previously
presented, keys are accessible at this path
NEAR Wallet
33. - managing NEAR primitives:
- key stores
- accounts
- contracts
- wallets
- connection providers (RPC)
- generating key pairs locally
- creating transactions locally
- signing transactions locally
- sending transactions to the network
near-api-js
Library designed to connect to the NEAR platform from any JavaScript
execution context (server-side or client-side JS)
38. - syntax is identical to TypeScript
(AS is a strict subset of TS)
near-sdk-as
Library designed to support the development of valid NEAR contracts using
AssemblyScript (AS)
39. near-sdk-rs
- Best choice for high value contracts
Library designed to support the development of valid NEAR contracts using
Rust (RS)
41. - human readable names that follow a DNS naming pattern
- may represent either a user, a contract or both
- maintain their own storage (via “storage staking” mechanism)
see https://docs.near.org/docs/concepts/account
see https://docs.near.org/docs/concepts/storage
NEAR Accounts
42. - composed of one or more Actions (currently there are 8 supported Actions)
- transactions that change state must be signed by a valid NEAR Account
- converted to “receipts” internally for cross-contract calls
see https://docs.near.org/docs/concepts/transaction
NEAR Transactions
43. - key-value store maintained as part of each NEAR account
- paid for using “storage staking” mechanism
see https://docs.near.org/docs/concepts/storage
NEAR State
44. Account ≈ Contract + State
Runtime Layer
state storage
virtual
machine
code
load
read write
Your dApp
send
receive
Blockchain Layer
RPC Interface
- P2P network
- Consensus
- Block Storage
near-api-js
contracts
near-sdk-as
near-sdk-rs
result
apply
45. Account ≈ Contract + State
Runtime Layer
state storage
virtual
machine
code
load
result
read write
apply
46. Account ≈ Contract + State
Runtime Layer
virtual
machine
code
load
metadata
result
read write
data
apply
state storage
47. Runtime Layer
result
apply
Account ≈ Contract + State
virtual
machine
code
load
read write
key value
STATE your contract code
message “hello world”
counter 3
prefix::identifier value at collection key
prefix::len PersistentVector length
prefix::last PersistentDeque last item
state storage
49. Cross-contract calls enable scalability
shard.1.vm shard.2.vm
…
send
receive
cross-contract call cross-contract call
Your
dApp
Each NEAR account is assumed to live on its own shard, even if two accounts are physically
located in the same shard. This makes any method invocation from one contract to another a
“cross-contract call” (contract = account + state)
From the perspective of a contract developer, cross-contract calls look a lot like promises in
popular languages. They may or may not return a value, support the orchestration of call
chains and are capable of merging multiple calls into one.
cross-contract call
50. Cross-contract calls enable scalability
shard.1.vm shard.2.vm
send
receive
internal
NEAR supports two contexts for cross-contract calls
- External calls originate from your client-side code (ie. using near-api-js)
- Internal calls originate from your contract code (ie. using near-sdk-as)
Both external and internal cross-contract calls support “batch” calls and “promise” calls
Your
dApp
external
53. Exploring cross-contract calls
External “promise” calls which are used to invoke methods on multiple contracts using the
standard Promise interface
This example was taken from MDN (just assume the functions wrap near-api-js)
A
55. Exploring cross-contract calls
Internal “batch” calls which are used to chain a series of Actions together to be executed on
some target account (including being applied to the current contract)
C
59. Contract testing is convenient and maturing
simulation
tests
integration
tests
- as-pect testing framework for
AssemblyScript
- uses rpec-style syntax with
support for exception paths
- full control over VM Context
(ie. signer_id, contract_id, etc)
AssemblyScript
contracts
near-sdk-as
unit testing
( as-pect )
internal
1
unit testing
( as-pect )
60. Contract testing is convenient and maturing
integration
tests
AssemblyScript
contracts
near-sdk-as
unit testing
( as-pect )
simulation
tests
- uses near-vm for parity
between Rust and
AssemblyScript contracts
( wraps the NEAR Protocol
on-chain virtual machine )
- allows fine-grained control of
economics configuration,
execution context and state
management
( simulate any genesis config,
account state and transaction
context )
simulation
near-vm
CLI
2
61. Contract testing is convenient and maturing
integration
tests
AssemblyScript
contracts
near-sdk-as
unit testing
( as-pect )
simulation
tests
- test cross-contract calls
- use any Node.js testing
framework ( ie. Jest, Ava )
- API supports all 8 NEAR action
types ( ie. CreateAccount )
- API is identical for both
AssemblyScript and Rust
( since we’re testing the Wasm
file at this point )
simulation
2
Runtime
API
62. Contract testing is convenient and maturing
integration
tests
AssemblyScript
contracts
near-sdk-as
unit testing
( as-pect )
simulation
tests
- deploy contracts to local node
(LocalNet) or TestNet
- invoke contract methods to
generate realistic resource
consumption estimates
- UX is identical for both
AssemblyScript and Rust
( since we’re testing the Wasm
file at this point )
simulation
3
NEAR CLI
63. Contract testing is convenient and maturing
integration
tests
AssemblyScript
contracts
near-sdk-as
unit testing
( as-pect )
simulation
tests
- test cross-contract calls
- use any JavaScript testing
framework ( ie. Jasmine )
- integrates closely with your
dApp UX
- API is identical for both
AssemblyScript and Rust
( since we’re testing via
near-api-js at this point )
simulation
3
near-api-js
API