1 of 65

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:�

2 of 65

web2 → web3

3 of 65

Coming from web2 to web3: a primer

web2

web3

topology

client-server

client-(server+blockchain)

app dev technology

  • JS frontend
  • multiple backend techs
  • JS frontend
  • Rust and AssemblyScript (like JS/TS) on NEAR

security

accounts

  • username / password
  • oAuth

accountsasymmetric key pairs (public and private keys)

servers

  • AWS / GCP / Azure

servers�← web2 + consensus (PoW, PoS, etc)

key performance

fast. cheap. data is “native”

unassailable. permanent. money is "native"

4 of 65

Dissecting an

Application

5 of 65

Guest Book

6 of 65

  • 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 of 65

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 of 65

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 of 65

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 of 65

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 of 65

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 of 65

CRUD : src/App.js

  • add a message and, once complete, get a list of all messages (up to MESSAGE_LIMIT)

Guest Book (frontend)

13 of 65

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 of 65

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

15 of 65

Runtime Layer

state storage

virtual

machine

code

load

apply

result

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

deploy

NEAR Protocol for Developers

16 of 65

Lifecycle of a transaction

Runtime Layer

state storage

virtual

machine

code

load

apply

result

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

1

2

3

4

5

6

7

deploy

17 of 65

write

read`

Runtime Layer

state storage

virtual

machine

code

load

apply

result

Your dApp

send

receive

Blockchain Layer

RPC Interface

  • P2P network

  • Consensus

  • Block Storage

near-api-js

contracts

near-sdk-as

near-sdk-rs

deploy

Structure of the Sample Application

18 of 65

Build with NEAR

19 of 65

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

20 of 65

create-near-app

Choose templates for a frontend and a contract:

Frontend

  • JavaScript
  • React

Contract

  • AssemblyScript
  • Rust

21 of 65

create-near-app

Choose templates for a frontend and a contract:

Frontend

  • JavaScript
  • React

Contract

  • AssemblyScript
  • Rust

22 of 65

create-near-app

step #1

npx create-near-app banana

23 of 65

create-near-app

step #2

yarn dev�

( or use npm run dev )

24 of 65

step #3

create-near-app

Sign in to NEAR Wallet

( 1 ) create new account

( 2 ) authorize your app

25 of 65

step #4

create-near-app

Change the message

( 1 ) edit the greeting

( 2 ) click Save

( 3 ) observe a → b

a

b

b

26 of 65

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 of 65

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

28 of 65

Exploring the

Platform

29 of 65

NEAR Explorer

  • Monitor all public network activity including validator nodes, block height, recent transactions and account details

30 of 65

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 of 65

  • 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

32 of 65

NEAR CLI

33 of 65

  • 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)

34 of 65

Client-side

Server-side

near-api-js

35 of 65

Server-side

UnencryptedFileSystemKeyStore

Client-side

BrowserLocalStorageKeyStore

near-api-js

36 of 65

near-api-js

Your dApp

Examples at near.dev

NEAR Explorer

NEAR Wallet

NEAR CLI

send

receive

RPC Interface

Blockchain Layer

near-api-js uses JSON RPC API

37 of 65

near-api-js

Your dApp

Examples at near.dev

NEAR Explorer

NEAR Wallet

NEAR CLI

send

receive

RPC Interface

Blockchain Layer

near-api-js uses JSON RPC API

38 of 65

  • 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 of 65

near-sdk-rs

  • Best choice for high value contracts

Library designed to support the development of valid NEAR contracts using Rust (RS)

40 of 65

Accounts

Transactions

& State

41 of 65

  • 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 of 65

  • 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 of 65

  • 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 of 65

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 of 65

Account ≈ Contract + State

Runtime Layer

state storage

virtual

machine

code

load

result

read

write

apply

46 of 65

Account ≈ Contract + State

Runtime Layer

virtual

machine

code

load

metadata

result

read

write

data

apply

state storage

47 of 65

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

48 of 65

Scale with NEAR

49 of 65

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 of 65

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

51 of 65

Exploring cross-contract calls

B

A

C

D

B & A are NOT cross-contract calls

C & D are cross-contract calls

52 of 65

Exploring cross-contract calls

B

A

C

D

B & A are NOT cross-contract calls

C & D are cross-contract calls

53 of 65

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

54 of 65

Exploring cross-contract calls

External “batch” calls are used to chain a series of Actions together to be executed on some target account�

B

55 of 65

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

56 of 65

Exploring cross-contract calls

Internal “promise” calls which are used to invoke methods on other contracts (or recursively on the current contract)

D

57 of 65

Testing

58 of 65

deploy

MainNet

simulation

integration

deploy

TestNet

unit

build

contract

Our APIs in a landscape of testing

2

AssemblyScript

contracts

near-sdk-as

Rust

contracts

near-sdk-rs

1

3

unit testing

( as-pect )

unit testing

( #[test] )

Runtime API

near-vm CLI

blockchain

near-api-js API

NEAR CLI

59 of 65

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 of 65

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 of 65

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 of 65

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 of 65

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

64 of 65

share bit.ly / near-101

Thank you!

65 of 65

visit near.help

Touch base on Telegram

Discover us on Discord

Suggest topics on StackOverflow