text
stringlengths 46
74.6k
|
---|
NEAR and Galxe Team Up for SPACE ID Voyage Season 2
NEAR FOUNDATION
June 8, 2023
NEAR Foundation and Galxe —the leading platform for Web3 community building — are joining forces to provide new and existing Web3 users with a seamless onboarding experience for SPACE ID’s renewed referral program, “Voyage Season 2 – Calling”.
This new partnership is significant, as Galxe is the first major Web3 partner launching a component on NEAR’s Blockchain Operating System (BOS). The BOS is an OS on which developers can effortlessly build and distribute chain-agnostic, decentralized apps and experiences on the Open Web.
SPACE ID is a universal name service network with a one-stop identity platform to discover, register, trade, and manage Web3 domains. It also includes a Web3 Name SDK & API for developers across blockchains and provides a multi-chain name service for everyone to easily build and create a web3 identity. Established in the third quarter of 2022, SPACE ID quickly took the market by storm with its .bnb domain name service, as well as more recently with .arb name service.
How the BOS will power the SPACE ID Voyage decentralized frontend
NEAR’s BOS will be powering the decentralized frontend for SPACE ID’s Voyage, a referral program where users invite others to register a .bnb or .arb address and earn special Voyage Boxes in return. Starting on June 7th, users will be able to participate in Space ID’s Voyage program through near.org and register .bnb names — enjoying a seamless, one-stop, decentralized experience powered by BOS.
Before the BOS integration, participating in quests like Voyage could be a complicated process. Users had to navigate through multiple pages, going back and forth to sign-in, register a domain, check eligibility, and claim rewards separately. A tech stack for decentralized and user-friendly frontends, BOS enables a unified interface where users can do all of the above with a single sign-in — directly in-app — so that users never have to leave the page on which they started.
How SPACE ID uses BOS’s composable components
The BOS components for SPACE ID are created independently and composed inside another composite component. This, in and of itself, clearly demonstrates the true composability strengths of BOS.
And thanks to BOS’s permissionless nature, developers are able to fork the components and embed them into their BOS components or websites. Users are then able to view the source code for each of the these components both on-chain and in-browser — improving transparency and security at every step of the user journey.
Discover Galxe’s exciting SPACE ID Campaign today. Register a .bnb domain name and claim a Voyage Box today on near.org.
Stay tuned for more exciting NEAR Foundation and Galxe campaigns to come — powered by BOS! |
NEARCON ‘23 Day Three: Governance and Multi-Chain in the Spotlight
NEAR FOUNDATION
November 10, 2023
As NEARCON ’23 drew to a close, the vibrant energy of innovation and unity in the open web was palpable. Attendees reflected on a journey filled with groundbreaking discussions and pivotal connections, marking the final day as a celebration of collective progress and shared visions for the future.
The conference’s last act spotlighted transformative dialogues and educational strides, with a keen focus on empowering the next wave of builders. Governance talks, innovative partnerships, and technical milestones underscored NEAR’s commitment to nurturing talent and fostering a future where the open web thrives.
Major EigenLayer and LayerZero announcements
Day Three was headlined by two major announcements that will impact the NEAR Protocol and ecosystem in a variety of ways moving forward.
NEAR and EigenLayer enable fast finality on Ethereum
NEAR Foundation partners with Eigen Labs to develop a “fast finality layer” for Ethereum rollups, promising swift and economical transactions. This initiative, set for a 2024 testnet launch, aims to quicken cross-rollup communication and minimize costs, streamlining the developer experience and enhancing Web3 interoperability.
LayerZero integrates with NEAR for cross-chain messaging
A second big announcement was the integration with LayerZero Labs on NEAR’s EVM layer, Aurora, enabling NEAR to connect with over 40 blockchain networks. LayerZero’s endpoint paves the way for trustless cross-chain messaging, expanding NEAR’s interoperability and user experience. For further details, visit LayerZero’s documentation here.
Day Three ecosystem news and announcements
EigenLayer and LayerZero were just the tip of the iceberg for the ecosystem on Day Three. Here’s a rundown of other key happenings.
Activelink boosted by NEAR grant
Activelink, enhancing sports and media engagement, has received a NEAR Foundation grant to facilitate on-chain transactions, fostering direct fan connections and monetization on the NEAR protocol.
Ample kicks off Horizon program
Ample, readying to disrupt media distribution, leverages the Horizon Programme to launch a unique platform for artists. It aims to democratize entertainment by tokenizing content, ensuring creators’ ownership, and optimizing monetization without requiring open web expertise.
Encode: Kickstarting NEAR Innovations
Encode teams up with NEAR Horizon for an eight-week online accelerator, starting November 23rd including workshops, mentorship, and global networking opportunities. Open to unfunded hackathon and startup projects, it’s a launchpad to growth without full-time commitment. Check out the Encode accelerator website to learn more and fill out an application today.
QSTN: NFT Success and Testnet Launch
QSTN announced a full sell-out of their NFT collection on NEAR, gearing up for their public incentivized testnet on November 13th. QSTN is calling on the open community to engage and earn NEAR rewards for survey participation and feedback with Telegram integration plans.
World of Rogues brings mobile adventure to NEAR
World of Rogues is set to conquer mobile gaming, with Rogues Studio announcing a forthcoming release for iOS and Android. Emphasizing a seamless, frictionless blockchain gaming experience on NEAR, the studio focuses on easy onboarding for non-crypto gamers.
Lava Network bolsters NEAR with modular APIs
The Lava Network is boosting the NEAR ecosystem through a partnership aimed at enhancing developer tools with modular APIs and incentivized public RPCs. By integrating NEAR support, Lava provides developers with a robust node network, ensuring speed and efficiency.
Encore Network empowers NEAR with user-centric data
Encore, a leading data collection platform, announced a huge step in data control. NEAR users now control their data along with terms of sharing. The goal is to slash customer acquisition costs for projects and spur revenue, marking a new chapter in data-driven user empowerment.
Key sessions and panels
The final day of NEARCON ‘23 highlighted governance, along with a special session between NEAR co-founder and CEO Illia Polosukhin and Polygon co-founder Jordy Baylina.
NEAR Governance Forum: shaping decentralized democracy
At the NEAR Governance Forum, leaders like Blaze from Cheddar and Alejandro Betancourt of the Transparency Commission discussed challenges in the NDC, emphasizing the need for high standards and community-driven progress. Topics included efficient governance models, the balance between autonomy and collaboration, and advancing NEAR’s decentralized democracy.
Illia dives deeper into Polygon and ZK with Jordi Baylina
NEAR’s Illia Polosukhin, alongside Polygon co-founder Jordi Baylina, dove into the collaboration between the two ecosystems. The two focused on zero-knowledge proofs for enhancing cross-chain interactions and unifying blockchain security. They talked about streamlining Layer 1 and Layer 2 operations, promoting a cohesive and interoperable blockchain network, and more.
Envisioning the future of decentralized democracy
During “What 2024 Looks Like for Decentralized Democracy” Blaze and Alejandro returned along with Yadira Blocker from the NEAR Foundation to break down cultural and operational shifts needed for effective governance, touching on the role of AI in streamlining decision-making processes. They also discussed the NDC’s past, present, and future.
The Littles bash at LX Factory closes out NEARCON ‘23
Day Three will culminate in a huge bash at LX Factory, sponsored by The Littles. Unwind and network against the backdrop of one of Lisbon’s most vibrant and hip nightlife districts. The closing party not only marks the end of an iconic NEARCON ‘23, but will be fertile ground for future collaborations and community bonding.
Not to mention a chance to win rewards and NFTs just by playing carnival games via The Littles Fun Pass app on NEAR. Win or lose, you’ll walk away with some cool blockchain-based swag.
As NEARCON ’23 wraps up, the collaborative spirit of the open web community is clear. The convergence of thought leaders, innovators, and enthusiasts in Lisbon made this year’s edition incredibly special. Thanks to every attendee, hacker, sponsor, and NEAR enthusiast for making NEARCON ‘23 so memorable, and see you at the LX Factory at 9 PM for the grand finale! |
```js
const accountId = context.accountId ?? props.accountId;
const keypomContract = "v2.keypom.near";
const nftContract = "nft.primitives.near";
const nftTokenId = "1";
const dropAmount = "10000000000000000000000";
Near.call([
{
contractName: keypomContract,
methodName: "create_drop",
args: {
public_keys: state.publicKeys,
deposit_per_use: dropAmount,
fcData: {
// 2D array of function calls. In this case, there is 1 function call to make for a key use
// By default, if only one array of methods is present, this array of function calls will be used for all key uses
methods: [
// Array of functions for Key use 1.
[{
receiverId: nftContract,
methodName: "nft_mint",
args: JSON.stringify({
// Change this token_id if it already exists -> check explorer transaction
token_id: nftTokenId,
metadata: {
title: "My NFT drop",
description: "",
media: "",
}
}),
accountIdField: "receiver_id",
// Attached deposit for when the receiver makes this function call
attachedDeposit: "10000000000000000000000"
}]
]
}
},
deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000,
gas: "100000000000000",
},
]);
``` |
---
title: 5.3 Protocol Politicians and Governance Design
description: The notion of ‘on-chain’ governance, and the protocol politics
---
# 5.3 Protocol Politicians and Governance Design
The focus of this lecture centers upon the notion of ‘on-chain’ governance, and the protocol politics of crypto-ecosystems and dApps. The context for this lecture is straightforward: With emergent DAO infrastructure, the rise of On-chain organizations, and a massive improvement in DAO tooling, protocols and dApps are making the decision to decentralize governance of their system out to the community based upon (1) Token weight, and / or (2) elected rulers from a variety of mechanisms. This is the beginning of the Age of Network Governance.
## The Age of Network Governance
When we talk about the age of network governance we are referring to a new relationship between users, investors, and builders, to the products they create in the crypto space. Traditionally, investors may have received equity and by default voting shares in a company. Users, may have been both user and product of the tech company, and builders may have fought to maintain ownership of ‘their baby’ for as long as they could before going public.
Within crypto-ecosystems, the game has changed. Usually, most dApps and protocols are designed open-source, and with an underlying token as a unit of value for a specific purpose on the protocol. As the protocols and products have evolved, it has led to the decentralized governance of the protocols and products. This governance usually surrounds a couple of key facets of the protocol:
* **Treasury Management:** For example, when Terra bought BTC to try to back up their reserves. Or when Aave voted to approve a new security audit mechanism from Chaos Labs.
* **Protocol Mechanics:** For example, transitioning ETH to PoS during the Merge. Or voting to make a base-token of a protocol a certain way. Changing rates of emission, and increasing or decreasing fees.
* **Blocking or Removing Certain Accounts:** This happened with Solana when a large whale attempted to liquidate his position, and the DAO moved swiftly to bar the address from selling.
![](@site/static/img/bootcamp/mod-em-5.3.1.png)
With a new product, the players involved (users, investors, and builders) are also on a new playing field: Now, value is shared inside of the system that the product has created, such that users, investors, and builders co-llaborate or conflict with one another in the direction of the open-source system. This in turn has led to the emergence of a new role in crypto - notably, the protocol politician.
## What is a protocol politician?
Bankless has [provided a clear overview of the emergence of protocol politics](https://newsletter.banklesshq.com/p/the-rise-of-the-protocol-politicians) and its implications: Protocol politicians are any participant of a dApp or protocol that has a vested interest in the future of the protocol. This can be via any combination of investment, participation, delegated participation, and so forth. These protocol politicians are not only actively involved in the day to day maintenance and management of a protocol, but they are also compensated for it - up to 600k a year in the case of Aave for example. The importance of protocol politicians, is outlined by Mason Nystrom from Messari:
[As Mason Nystrom from Messari Writes:](https://messari.io/article/the-latent-power-of-governance-tokens)
_“As crypto protocols grow in value, governance can become a meaningful mechanism to alter the state of the protocol. Because of this principle, the value of governance tokens is latent, but ever-present. The dormant power of governance tokens can be activated for multiple purposes whether 1) as a function or service required within the protocol 2) to control the assets of a protocol, or 3) to alter the existing parameters of a given network.”_
The the crucial questions surrounding the parameters of a protocol politician:
* Do they have skin in the game?
* Are they apolitical?
* Are they accountable to anyone?
* Are they captured by special interests?
Finally, the idea of _delegating_ tokens to someone to make decisions for you, is the final characteristic of a protocol politician. So while an investor or whale may have a large stake in tokens, they may not want to follow the day-to-day governance iterations of the protocol. Delegating tokens to an individual is the basis for an emergent politics [(of which Aave is probably the best example). ](https://twitter.com/aaveaave/status/1294309030408736770)
![](@site/static/img/bootcamp/mod-em-5.3.2.png)
And from these key questions, a specific governance framework can be created to safeguard the protocol from most urgent threats (special interests, accountability, etc.) On the flip side, and in parallel, this leads to new avenues of attack on a protocol:
![](@site/static/img/bootcamp/mod-em-5.3.3.png)
Or to put it concretely, we can take the very real example of a16z - a massive investment fund - stepping in at the last minute to alter a significant proposal on MakerDAO.
![](@site/static/img/bootcamp/mod-em-5.3.4.png)
What is the significance of this? That if the founders or builders are not thoughtful about network governance, from the beginning, the entire protocol or network can be usurped by a few large token holders later on - and for the rest of the protocol's existence: And this can be the case, despite the founders wishes, or the communities wishes.
## Why does this matter for projects?
These are questions that every investor should look to understand:
* How is the protocol or dApp intended to be governed over the long term?
* Is delegated governance possible?
* What is the scope of governance?
* Are all management keys signed over to the DAO or do the devs / core team maintain control of certain facets of the protocol?
* What is the plan to decentralize governance over time, who is responsible for creating the governance framework, and what is the process of launching the governance framework?
All of these questions relate to the core underlying proposition that: An open-source crypto-economic protocol is governed by the community of participants and not a small majority of creators and investors (as is traditional in Web2). While this can remain the case for some time, it is not in the nature of a protocol or ecosystem to generate significant network effects, permissionless innovation, and un-coordinated development, without the safeguard / assurance that the underlying protocol or dApp is itself governed in a decentralized and public manner.
On looking to the future of protocol politics, we can listen [to Ric Burton:](https://ricburton.substack.com/p/the-rise-of-protocol-politicians)
_“Imagine a monetary protocol with the power to affect global economies — a private, protocol-based central bank for open finance. How could such an institution exist without accruing political cruft at every open surface area of decision-making?_
_- Political parties_
_- Forks based on disputes_
_- Vote-buying markets_
_— Lobbyists & interest groups."_
|
---
sidebar_position: 1
---
# Essential Syntax
This document describes the essential syntax required for creating Components to run on the BOS Web Engine. All BOS developers should familiarize themselves with the contents of this document.
## Component Export
Every BWE component must have a valid export. This can be a named export where the name is `BWEComponent` or a default export. If you are not opinionated about your exports, we recommend following the example set by the boilerplate code generated in the sandbox.
## Component IDs
When embedding multiple instances of the same BWE Component at the same level within a parent Component, each child must be given an explicit ID in order for the engine to differentiate between them during renders. This is similar to the `key` prop in React, but is separately required by BOS Web Engine.
A very common use case where this is encountered is when rendering a `Component` within a `.map()` call on an array of data.
As a best practice, we recommend new Components be written with a meaningful `id` value to avoid potential collisions in the
future.
### Examples
Assuming we have an import of `import Child from near://bwe-demos.near/Child`:
---
```jsx
<Child />
```
✅
The automatically generated ID is sufficient to identify a single child Component.
---
```jsx
<Child />
<Child id="2nd" />
```
✅
The second Component has an explicit `id` value, preventing any collisions. While this does work, it would be much less brittle
if both child Components had unique `id` values.
---
```jsx
<Child id="1st" />
<Child id="2nd" />
```
✅✅
Ideal, makes future maintenance easier.
---
```jsx
<Child />
<Child />
```
❌
Without unique `id` values, child Components cannot be differentiated by the outer application.
---
<details>
<summary>More Details</summary>
<p>To ensure Components are uniquely addressable by the application, BOS Web Engine uses a Component's ancestors' path names as a prefix to create a base Component ID. So for a child Component `Child` under `Parent`, which in turn is a child under `Root`, the base Component ID would include a concatenation of `Child>Parent>Root`.</p>
<p>Rendering multiple instances of the same Component under the same Parent should be considered undefined behavior.</p>
</details> |
Octopus Network Seed Funding Round Complete
COMMUNITY
April 2, 2021
Octopus Network Announcement: Seed Funding Round Complete!
The Octopus Network Team recently announced the completion of a seed-funding round for building out the base level infrastructure of Octopus Network. The $3 million dollars fundraise includes capital from deep-crypto venture firms including:
D1 Ventures
SevenX Ventures
Puzzle Ventures
PNYX Capital
Electric Capital
Ascensive Assets
Origin Capital
ZMT Capital
Bixin
OKEx Block Dream Fund
Spark Digital
ChainX
Stafi
NGC Ventures
Prior to this seed round, Octopus had received a $1 million dollar strategic investment from the NEAR Foundation. In context this fundraise is a strong vote of confidence in both the future of appchains, as well as NEAR Protocol.
The Early Days of Appchains on NEAR: Octopus in Context
An Appchain is a decentralized Web3.0 application in the form of an independent blockchain. Octopus Network provides appchains with flexible on-demand shared security, out-of-the-box cross-chain interoperability, and infrastructure services including blockchain explorers, API endpoint, indexers, etc. In short, Octopus Network allows for projects to quickly and efficiently customize and launch their own blockchain, without needing to source all of the features required to maintain that blockchain.
By reducing the capital expenditure for publishing and launching an Appchain by two orders of magnitude – from millions of dollars to tens of thousands dollars – Octopus Network is preparing to unleash a new wave of innovation in Web3.0 applications.
On Octopus Network the next generation of Web 3.0 applications can develop in a cost-effective, scalable, and secure manner. The $3 million dollar seed round fundraise for Octopus is the first step of an inevitable software revolution. To stay up to date with Octopus Network and the many different appchains preparing to deploy on Octopus, follow the team on Discord and Twitter!
If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR documentation to get started.
|
NEAR joins FlamingoDAO 🦩
COMMUNITY
October 30, 2020
A new future for digital property is beginning — one that promises to help reduce the distortions of the first Internet wave and ensure greater compensation for creators across the globe. This is done through non-fungible tokens (NFTs), which are set to transform culture and serve as an anchor for the first generation of digital property.
NFTs are unique, non-interchangeable digital assets that live on a blockchain. Most blockchain enthusiasts were introduced to NFTs in 2017, when CryptoKitties became so popular it slowed down the entire Ethereum network. But NFTs in 2020 have grown into so much more than digital cats. Today, NFTs are music samples, digital paintings, memes, digital land, event tickets, etc. The list goes on. For the first time in history, digital creators have a way to properly monetize their assets and make a living.
The Flamingo DAO is a new initiative by The LAO that takes on the “hive mind” approach of decentralization to support the ever-growing NFT ecosystem. Flamingo is unique because it operates as a community-driven collective of members that will make decisions to support the NFT ecosystem. The LAO is behind the idea of Flamingo and already has experience supporting projects such as Aavegotchi and Shell Protocol.
The NEAR Foundation is thrilled to announce that it has joined the Flamingo DAO as a formal participant. NiMA Asghari will be the representative on behalf of the NEAR Community Council. As a collective, Flamingo will invest in digital properties and push the boundaries of NFTs, DeFi, fractionalization, metaverses, and much more. It will support several use cases, such as:
Acquiring NFTs and fractionalizing them;
Commissioning work from NFT creators;
Investing in digital artists;
Creating digital museums and galleries;
Supporting investments in core NFT projects.
NEAR is perfectly positioned to support NFTs. Already, popular NFT marketplace Mintbase is building on NEAR so its users can easily create stores and sell their digital assets. Mintbase and NEAR also launched the Createbase guild, where anyone who wants to experiment with NFTs on NEAR can join and apply for funding. Together, NEAR and Mintbase support creative projects up to 5000 USD (primarily in NEAR tokens) per month.
The NEAR Foundation is excited to be a part of the Flamingo DAO. This is the first in a series of community-oriented investments in DAOs and collective projects for NEAR, showcasing NEAR’s commitment to growing the NFT space. |
---
id: social
title: Social Interactions
---
import {WidgetEditor} from "@site/src/components/widget-editor"
NEAR components can natively communicate with the [SocialDB smart contract](https://github.com/NearSocial/social-db) (currently deployed at [social.near](https://nearblocks.io/address/social.near)).
The `SocialDB` is a contract that stores `key-value` pairs, and is used mostly to store social-related data, such as `posts`, `likes`, or `profiles`.
:::tip
Besides user data, the `SocialDB` contract stores **all existing NEAR components**.
:::
---
## Social.get
`Social.get` queries a key from the SocialDB contract and returns the data. The key being queried can contain wildcards.
For example:
- `alice.near/profile/**` will match the entire profile data of account alice.near.
- `alice.near/profile/*` will match all the fields of the profile, but not the nested objects.
- `alice.near/profile/name` will match only the name field of the profile.
- `*/widget/*` will match all the widgets of all the accounts.
<br />
<WidgetEditor>
```js
// Ask for the `profile` key of the influencer.testnet account
const profile = Social.get("influencer.testnet/profile/*");
// Ask a component from the influencer.testnet account
const widget = Social.get("influencer.testnet/widget/Greeter");
if(profile === null || widget === null) return "Loading ..."
return (
<div>
<p>Profile: {JSON.stringify(profile)}</p>
<p>Widgets: {JSON.stringify(widget)} </p>
</div>
);
```
</WidgetEditor>
<details markdown="1">
<summary> Parameters </summary>
| param | required | type | description |
|------------|--------------|--------------------|------------------------------|
| `patterns` | **required** | string / string[] | the path pattern(s) |
| `finality` | _optional_ | `"final"` / number | the block height or finality |
| `options` | _optional_ | object | the `options` object. |
:::info options object
- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds.
- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`.
:::
The block height or finality can be used to get the data at a specific block height or finality.
If the block height or finality is not specified, the data will be fetched at the `optimistic` finality (the latest block height).
For block height and finality `final`, instead of calling the NEAR RPC directly, the VM uses the Social API Server to fetch the data.
Social API server indexes the data for SocialDB and allows to fetch the data at any block height with additional options.
It also allows returning more data than an RPC call because it's not restricted by the gas limit.
In general, the API server also serves data faster than the NEAR RPC, because it doesn't execute the contract code in a virtual machine.
</details>
:::tip
While the data is fetching, `Social.get` returns `null`.
:::
---
## Social.getr
`Social.getr` is just a wrapper helper for `Social.get`, it appends `**` to each of the path pattern.
<WidgetEditor>
```js
const profile = Social.getr("influencer.testnet/profile");
return (
<div>
<p>Profile: {JSON.stringify(profile)}</p>
</div>
);
```
</WidgetEditor>
<details markdown="1">
<summary> Parameters </summary>
| param | required | type | description |
|------------|--------------|--------------------|------------------------------|
| `patterns` | **required** | string / string[] | the path pattern(s) |
| `finality` | _optional_ | `"final"` / number | the block height or finality |
| `options` | _optional_ | object | the `options` object. |
:::info options object
- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds.
- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`.
:::
</details>
---
## Social.keys
The `keys` method allows to get the list of keys that match a pattern. It's useful for querying the data without reading values.
It also has an additional `options` field that can be used to specify the return type and whether to return deleted keys.
<WidgetEditor height="80">
```js
const data = Social.keys(`influencer.testnet/profile/*`, "final");
return JSON.stringify(data)
```
</WidgetEditor>
<details markdown="1">
<summary> Parameters </summary>
`Social.keys` takes up to 3 arguments:
| param | required | type | description |
|------------|--------------|--------------------|------------------------------|
| `patterns` | **required** | string / string[] | the path pattern(s) |
| `finality` | _optional_ | `"final"` / number | the block height or finality |
| `options` | _optional_ | object | the `options` object. |
:::info options object
- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds.
- `return_type` _(optional)_: either `"History"`, `"True"`, or `"BlockHeight"`. If not specified, it will return the `"True"`.
- `return_deleted` _(optional)_: whether to return deleted values (as `null`). Default is `false`.
- `values_only` _(optional)_: whether to return only values (don't include objects). Default is `false`.
:::
</details>
:::tip
The Social API server supports custom options `return_type: "History"`. For each matching key, it will return an array containing all the block heights when the value was changed in ascending order.
It can be used for building a feed, where the values are overwritten.
:::
---
## Social.set
Takes a `data` object and commits it to SocialDB. The data object can contain multiple keys, and each key can contain multiple values.
Importantly, a user can only commit to **their own** space in `SocialDB` (e.g. `alice.near` can only write in `alice.near/**`), except if [**given explicit permission**](https://github.com/NearSocial/social-db#permissions) by the owner of another space.
Each time a user wants to commit data, they will be prompted to confirm the action. On confirming, the user can choose to not be asked again in the future.
<WidgetEditor>
```js
const onClick = () => {
Social.set({
post: {
main: JSON.stringify({
type: "md",
text: "I've read the docs!"
})
}
})
}
if(!context.accountId) return "Please login...";
return <>
<p> Save a message showing some love to the NEAR Docs </p>
<button onClick={onClick}> Save the Message </button>
</>
```
</WidgetEditor>
<details markdown="1">
<summary> Parameters </summary>
`Social.set` arguments:
| param | required | type | description |
|-----------|--------------|--------|----------------------------------------------------------------------------------------------------|
| `data` | **required** | object | the data object to be committed. Similar to `CommitButton`, it shouldn't start with an account ID. |
| `options` | _optional_ | object | optional object. |
:::info options object
- `force` _(optional)_: whether to overwrite the data.
- `onCommit` _(optional)_: function to trigger on successful commit. Will pass the
data that was written (including `accountID`).
- `onCancel` _(optional)_: function to trigger if the user cancels the commit.
:::
</details>
:::tip
By default `Social.set` will omit saving data that is already saved (e.g. if the user already liked a post, it won't save the like again). To force saving the data, pass the `force` option.
:::
---
## Social.index
NEAR Social readily provides an indexer - a service that listen to actions in SocialDB, and caches them so they can be retrieved without needing to interact with the contract.
The indexer is very useful, for example, to rapidly store and retrieve information on all comments for a post. Without the indexer, we would need to check all entries in the contract to see who answered, surely running out of GAS before completion.
<hr className="subsection" />
### Indexing an Action
To index an action we need to add the `index` key to the data being saved, within the `index` key we will save the `action` being indexed, alongside a `key` and a `value` that identifies this specific instance.
<WidgetEditor>
```js
// General form of an indexed action
// {
// index: {
// actionName: JSON.stringify({ key, value })
// }
// }
const onClick = () => {
Social.set({
index: {
readDocs: JSON.stringify({key: "docs", value: "like"})
} ,
})
}
return <>
{context.accountId ?
<>
<p> Index an action showing some love to the NEAR Docs </p>
<button onClick={onClick}> Index Action </button>
</> :
<p> Login to index an action </p>}
</>
```
</WidgetEditor>
In the example above we index a `docs` action. In this case the `action` is `docs`, and the `key` that identifies it is `"read"`.
<details markdown="1">
<summary> Standards </summary>
#### Indexing a Post
To index a post, the standard is to save the action `post`, with `{key: "main", value: {type: "md"}`.
```js
{
index: {
post: JSON.stringify({
key: "main",
value: {type: "md"}
})
}
}
```
#### Indexing a Like
To index a like, the standard is to save the action `like`, with `{key: object-representing-the-post, value: {type: "like" }}`
```js
{
index: {
like: JSON.stringify({
key: {type: 'social', path: 'influencer.testnet/post/main', blockHeight: 152959480 },
value: {type: "like"}})
}
}
```
</details>
<hr className="subsection" />
### Retrieving Indexed Actions
To retrieve indexed actions we use the `Social.index` method. It takes the `action` and the `key` as arguments, and returns an array of all the indexed values alongside the `blockHeight` in which they were indexed, and which user made the action.
<WidgetEditor>
```js
const readDocs = Social.index("readDocs", "docs")
return <>
<p> Number of indexed "readDocs" actions with key "docs": {readDocs.length} </p>
<b>Indexed actions</b>
{JSON.stringify(readDocs)}
</>
```
</WidgetEditor>
<details markdown="1">
<summary> Parameters </summary>
`Social.index` arguments:
| param | required | type | description |
|-----------|--------------|--------|--------------------------------------------------------------------------------------------|
| `action` | **required** | string | is the `index_type` from the standard, e.g. in the path `index/like` the action is `like`. |
| `key` | **required** | string | is the inner indexed value from the standard. |
| `options` | _optional_ | object | the `options` object. |
:::info options object
- `subscribe` _(optional)_: if true, the data will be refreshed every 5 seconds.
- `accountId` _(optional)_: If given, it should either be a string or an array of account IDs to filter values by them. Otherwise, not filters by account Id.
- `order` _(optional)_: Either `asc` or `desc`. Defaults to `asc`.
- `limit` _(optional)_: Defaults to `100`. The number of values to return. Index may return more than index values, if the last elements have the same block height.
- `from` _(optional)_: Defaults to `0` or `Max` depending on order.
:::
</details> |
```js
const tokenContract = "token.v2.ref-finance.near";
const tokenPriceResult = await fetch(
`https://indexer.ref.finance/get-token-price?token_id=${tokenContract}`
);
const tokenPriceValue = await tokenPriceResult.json();
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
<details>
<summary>Example response</summary>
<p>
```json
{
"token_contract_id": "token.v2.ref-finance.near",
"price": "0.08153090"
}
```
</p>
</details>
:::tip
Ref Finance has a method to [get all token prices at once](https://indexer.ref.finance/list-token-price).
:::
|
---
id: what-is
title: What are NEAR Components?
sidebar_label: What is a Component?
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {WidgetEditor} from "@site/src/components/widget-editor"
NEAR Components are a new way to build web applications. They are composable, reusable and decentralized.
![img](/docs/assets/welcome-pages/bos-landing.png)
:::tip
You can login to interact with the examples in this section.
:::
---
## Familiar to Web Developers
NEAR Components are built on top of [React Components](https://react.dev/), meaning that they:
- Handle input through the `props` variable
- Handle state through the [`useState`](https://react.dev/reference/react/useState) hook
- Handle side effects through the [`useEffect`](https://react.dev/reference/react/useEffect) hook
<WidgetEditor id="1">
```jsx
const name = props.name || "Maria";
const [count, setCount] = useState(1);
return (
<div>
<p> {count} cheers for {name}! </p>
<button onClick={() => setCount(count + 1)}>Cheers!</button>
</div>
);
```
</WidgetEditor>
In contrast with React, NEAR Components are not wrapped in a `function` or `class` definition.
Indeed, when writing a NEAR Component, you focus on writing the body of the component, which is a function that returns the JSX to be rendered.
---
## NEAR Native
NEAR Components can readily [interact with smart contracts](./anatomy/near.md) in the NEAR Blockchain. While `view` methods are free to query by anyone, `call` methods require the user to be logged in.
<WidgetEditor id="2">
```jsx
const counter = Near.view('counter.near-examples.testnet', 'get_num')
if(counter === null) return 'Loading...'
const add = () => {
Near.call('counter.near-examples.testnet', 'increment')
}
const subtract = () => {
Near.call('counter.near-examples.testnet', 'decrement')
}
return <>
<p> Counter: {counter} </p>
{!context.accountId &&
<p color="red"> Please login to interact with the contract</p>
}
{context.accountId &&
<>
<button onClick={add}> + </button>
<button onClick={subtract}> - </button>
</>
}
</>
```
</WidgetEditor>
---
## Social from the Get-Go
NEAR Components are easily integrated with [NEAR Social](https://near.social/), a social network built on NEAR.
<WidgetEditor id="3">
```js
const item = (blockHeight) => ({ type: 'social', path: 'influencer.testnet/post/main', blockHeight });
// retrieve indexed posts by influencer.testnet
const idx_posts = Social.index(
'post', 'main', { accountId: ['influencer.testnet'] }
);
if (idx_posts === null) return 'Loading...';
// retrieve likes for each post
const likes = idx_posts.map(
index => Social.index('like', item(index.blockHeight)).length
);
// retrieve data for each post
const post_data = idx_posts.map(
index => Social.get(`${index.accountId}/post/main`, index.blockHeight)
);
// defined "Like" function
const like = (blockHeight) => Social.set(
{index:{like: JSON.stringify({key: item(blockHeight), value: {type: 'like'}})}}
)
return <>
<h5>Posts from <i>influencer.testnet</i></h5>
{post_data.map((post, idx) =>
<div className="mt-3">
<div>{JSON.parse(post).text} - {likes[idx]} likes</div>
{context.accountId && <button className="btn btn-danger btn-sm" onClick={() => like(idx_posts[idx].blockHeight)}>Like</button>}
</div>
)}
</>
```
</WidgetEditor>
---
## Fully On-Chain & Easily Composable
Leveraging the cheap storage and computation of the NEAR Blockchain, NEAR Components' code is stored fully on-chain in the SocialDB smart contract (`social.near`).
<WidgetEditor height="40px">
```js
// retrieving the code of a stored component
return Social.get('influencer.testnet/widget/Greeter')
```
</WidgetEditor>
Once deployed, a component can be imported and used by any other component. Composing components as LEGO blocks allows you to build complex applications.
<WidgetEditor id="4" height="80px">
```js
// Rendering the component with props
return <Widget src="influencer.testnet/widget/Greeter"
props={{name: "Anna", amount: 3}} />;
```
</WidgetEditor>
---
## Multi-Chain by Design
NEAR Components can easily interact with Ethereum compatible blockchains, helping to easily create decentralized frontends for multi-chain applications.
<WidgetEditor id="5" height="100px">
```js
if (
state.chainId === undefined &&
ethers !== undefined &&
Ethers.send("eth_requestAccounts", [])[0]
) {
Ethers.provider()
.getNetwork()
.then((chainIdData) => {
if (chainIdData?.chainId) {
State.update({ chainId: chainIdData.chainId });
}
});
}
if (state.chainId !== undefined && state.chainId !== 1) {
return <p>Switch to Ethereum Mainnet</p>;
}
// FETCH LIDO ABI
const lidoContract = "0xae7ab96520de3a18e5e111b5eaab095312d7fe84";
const tokenDecimals = 18;
const lidoAbi = fetch(
"https://raw.githubusercontent.com/lidofinance/lido-subgraph/master/abis/Lido.json"
);
if (!lidoAbi.ok) {
return "Loading";
}
const iface = new ethers.utils.Interface(lidoAbi.body);
// FETCH LIDO STAKING APR
if (state.lidoArp === undefined) {
const apr = fetch(
"https://api.allorigins.win/get?url=https://stake.lido.fi/api/sma-steth-apr"
);
if (!apr) return;
State.update({ lidoArp: JSON.parse(apr?.body?.contents) ?? "..." });
}
// HELPER FUNCTIONS
const getStakedBalance = (receiver) => {
const encodedData = iface.encodeFunctionData("balanceOf", [receiver]);
return Ethers.provider()
.call({
to: lidoContract,
data: encodedData,
})
.then((rawBalance) => {
const receiverBalanceHex = iface.decodeFunctionResult(
"balanceOf",
rawBalance
);
return Big(receiverBalanceHex.toString())
.div(Big(10).pow(tokenDecimals))
.toFixed(2)
.replace(/\d(?=(\d{3})+\.)/g, "$&,");
});
};
const submitEthers = (strEther, _referral) => {
if (!strEther) {
return console.log("Amount is missing");
}
const erc20 = new ethers.Contract(
lidoContract,
lidoAbi.body,
Ethers.provider().getSigner()
);
let amount = ethers.utils.parseUnits(strEther, tokenDecimals).toHexString();
erc20.submit(lidoContract, { value: amount }).then((transactionHash) => {
console.log("transactionHash is " + transactionHash);
});
};
// DETECT SENDER
if (state.sender === undefined) {
const accounts = Ethers.send("eth_requestAccounts", []);
if (accounts.length) {
State.update({ sender: accounts[0] });
console.log("set sender", accounts[0]);
}
}
//if (!state.sender) return "Please login first";
// FETCH SENDER BALANCE
if (state.balance === undefined && state.sender) {
Ethers.provider()
.getBalance(state.sender)
.then((balance) => {
State.update({ balance: Big(balance).div(Big(10).pow(18)).toFixed(2) });
});
}
// FETCH SENDER STETH BALANCE
if (state.stakedBalance === undefined && state.sender) {
getStakedBalance(state.sender).then((stakedBalance) => {
State.update({ stakedBalance });
});
}
// FETCH TX COST
if (state.txCost === undefined) {
const gasEstimate = ethers.BigNumber.from(1875000);
const gasPrice = ethers.BigNumber.from(1500000000);
const gasCostInWei = gasEstimate.mul(gasPrice);
const gasCostInEth = ethers.utils.formatEther(gasCostInWei);
let responseGql = fetch(
"https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `{
bundle(id: "1" ) {
ethPrice
}
}`,
}),
}
);
if (!responseGql) return "";
const ethPriceInUsd = responseGql.body.data.bundle.ethPrice;
const txCost = Number(gasCostInEth) * Number(ethPriceInUsd);
State.update({ txCost: `$${txCost.toFixed(2)}` });
}
// FETCH CSS
const cssFont = fetch(
"https://fonts.googleapis.com/css2?family=Manrope:wght@200;300;400;500;600;700;800"
).body;
const css = fetch(
"https://pluminite.mypinata.cloud/ipfs/Qmboz8aoSvVXLeP5pZbRtNKtDD3kX5D9DEnfMn2ZGSJWtP"
).body;
if (!cssFont || !css) return "";
if (!state.theme) {
State.update({
theme: styled.div`
font-family: Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
${cssFont}
${css}
`,
});
}
const Theme = state.theme;
// OUTPUT UI
const getSender = () => {
return !state.sender
? ""
: state.sender.substring(0, 6) +
"..." +
state.sender.substring(state.sender.length - 4, state.sender.length);
};
return (
<Theme>
<div className="LidoContainer">
<div className="Header">Stake Ether</div>
<div className="SubHeader">Stake ETH and receive stETH while staking.</div>
<div className="LidoForm">
{state.sender && (
<>
<div className="LidoFormTopContainer">
<div className="LidoFormTopContainerLeft">
<div className="LidoFormTopContainerLeftContent1">
<div className="LidoFormTopContainerLeftContent1Container">
<span>Available to stake</span>
<div className="LidoFormTopContainerLeftContent1Circle" />
</div>
</div>
<div className="LidoFormTopContainerLeftContent2">
<span>
{state.balance ?? (!state.sender ? "0" : "...")} ETH
</span>
</div>
</div>
<div className="LidoFormTopContainerRight">
<div className="LidoFormTopContainerRightContent1">
<div className="LidoFormTopContainerRightContent1Text">
<span>{getSender()}</span>
</div>
</div>
</div>
</div>
<div className="LidoSplitter" />
</>
)}
<div
className={
state.sender ? "LidoFormBottomContainer" : "LidoFormTopContainer"
}
>
<div className="LidoFormTopContainerLeft">
<div className="LidoFormTopContainerLeftContent1">
<div className="LidoFormTopContainerLeftContent1Container">
<span>Staked amount</span>
</div>
</div>
<div className="LidoFormTopContainerLeftContent2">
<span>
{state.stakedBalance ?? (!state.sender ? "0" : "...")}
stETH
</span>
</div>
</div>
<div className="LidoFormTopContainerRight">
<div className="LidoAprContainer">
<div className="LidoAprTitle">Lido APR</div>
<div className="LidoAprValue">{state.lidoArp ?? "..."}%</div>
</div>
</div>
</div>
</div>
<div className="LidoStakeForm">
<div className="LidoStakeFormInputContainer">
<span className="LidoStakeFormInputContainerSpan1">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path
opacity="0.6"
d="M11.999 3.75v6.098l5.248 2.303-5.248-8.401z"
></path>
<path d="M11.999 3.75L6.75 12.151l5.249-2.303V3.75z"></path>
<path
opacity="0.6"
d="M11.999 16.103v4.143l5.251-7.135L12 16.103z"
></path>
<path d="M11.999 20.246v-4.144L6.75 13.111l5.249 7.135z"></path>
<path
opacity="0.2"
d="M11.999 15.144l5.248-2.993-5.248-2.301v5.294z"
></path>
<path
opacity="0.6"
d="M6.75 12.151l5.249 2.993V9.85l-5.249 2.3z"
></path>
</svg>
</span>
<span className="LidoStakeFormInputContainerSpan2">
<input
disabled={!state.sender}
className="LidoStakeFormInputContainerSpan2Input"
value={state.strEther}
onChange={(e) => State.update({ strEther: e.target.value })}
placeholder="Amount"
/>
</span>
<span
className="LidoStakeFormInputContainerSpan3"
onClick={() => {
State.update({
strEther: (state.balance > 0.05
? parseFloat(state.balance) - 0.05
: 0
).toFixed(2),
});
}}
>
<button
className="LidoStakeFormInputContainerSpan3Content"
disabled={!state.sender}
>
<span className="LidoStakeFormInputContainerSpan3Max">MAX</span>
</button>
</span>
</div>
{!!state.sender ? (
<button
className="LidoStakeFormSubmitContainer"
onClick={() => submitEthers(state.strEther, state.sender)}
>
<span>Submit</span>
</button>
) : (
<Web3Connect
className="LidoStakeFormSubmitContainer"
connectLabel="Connect with Web3"
/>
)}
<div className="LidoFooterContainer">
{state.sender && (
<div className="LidoFooterRaw">
<div className="LidoFooterRawLeft">You will receive</div>
<div className="LidoFooterRawRight">${state.strEther ?? 0} stETH</div>
</div>
)}
<div className="LidoFooterRaw">
<div className="LidoFooterRawLeft">Exchange rate</div>
<div className="LidoFooterRawRight">1 ETH = 1 stETH</div>
</div>
{false && (
<div className="LidoFooterRaw">
<div className="LidoFooterRawLeft">Transaction cost</div>
<div className="LidoFooterRawRight">{state.txCost}</div>
</div>
)}
<div className="LidoFooterRaw">
<div className="LidoFooterRawLeft">Reward fee</div>
<div className="LidoFooterRawRight">10%</div>
</div>
</div>
</div>
</div>
</Theme>
);
```
</WidgetEditor>
:::danger ETH Disabled in Docs
For a working example visit the [deployed NEAR Component](https://near.social/zavodil.near/widget/Lido).
:::
---
## Next Steps
Build and deploy your first components without leaving the browser. Go to https://near.org/sandbox , create an account and start building! |
Off to the Races: ZEST Launches on the NEAR Mainnet
COMMUNITY
August 24, 2020
The NEAR collective is excited to announce the launch of the first gaming DApp on the NEAR mainnet: the new ZEST Play Platform from the digital entertainment startup Virtually Human Studio (VHS), the creator of the popular racehorse community ZED.
As the real world merges with the digital, full, and direct ownership of your digital assets becomes increasingly important. Blockchain technology makes that possible, and the industry has seen a proliferation of non-fungible tokens (NFTs) as a result. These unique and non-interchangeable tokens come in the form of digital land, trading cards, kittens, art, and, in the case of ZED, racehorses.
Buy a digital racehorse in ZED’s marketplace
ZED allows you to buy and sell beautifully designed, poly-art horses. But there’s a lot more to it. You can race your horses and earn a profit while doing so, too. Races on ZED are open 24/7 and thousands of people have already bought and raced their horse on ZED. But, as VHS was building out features for ZED, they bumped into a problem that would come to frustrate a growing number of users.
ZED runs on Ethereum. Participating in a horse race only costs a few dollars of Ether, but Ethereum’s gas fees would sometimes spike up to hundreds of dollars. On top of that, transactions sometimes wouldn’t go through, costing people a gas fee without returning the desired result. Given the rising popularity of DeFi and Ethereum’s clogged network, this became an increasingly pressing problem for VHS.
VHS found a solution in NEAR. Along with its dynamically sharded blockchain design, NEAR has a predictable gas price that is significantly lower than Ethereum’s. Additionally, similar to how AWS and other cloud service providers work, NEAR allows developers to cover gas costs for its users, making the onboarding experience for new blockchain users significantly easier.
This falls in line with the philosophy behind the ZEST Play Platform. ZEST is an #extremelysexytoken that users can earn for free to play ZED without having to invest money. You don’t have to own or learn about NFTs to get in on the fun. It’s a smooth, easy onboarding experience.
It seems to be working too, as people have already reserved well over a million ZEST. Visit the ZEST Play Platform to earn free ZEST tokens. Over time, you’ll be able to redeem prizes with your tokens, including ZED NFTs that hold actual dollar value.
Peter DePaulo, Head of Developer Experience at NEAR says of the project, “The team at VHS moves faster than even the most thoroughbred racehorse, and we are excited for what else we can create with them. We are aligned with the idea that the development of good products should be user-first and market-driven. In essence, build what people actually want and use underpinning technology like NEAR to eliminate technical complexity. We are passionate about supporting creators like VHS with the tools to move at lighting speed and deliver experiences that exceed people’s expectations. That is what we do here at NEAR, and it’s what we plan to continue doing.”
About NEAR
NEAR Protocol makes building and deploying decentralized apps (and exchanging NFTs) easier, faster, and cheaper than any other blockchain.
Native usability is NEAR’s primary concern. Features such as its contract-based account model and NEAR Drops make NEAR significantly more usable for developers and end users. Additionally, NEAR has focused on bringing performance for applications. The dynamic sharding approach, called Nightshade, works on top of proof-of-stake BFT consensus (called Doomslug) and allows network throughput to scale as demand grows. It targets 1-second blocks so developers can build performant applications.
Find out more about NEAR Protocol on our website, follow us on Twitter, or join our community on Discord.
About VHS
Virtually Human is a studio exploring the boundaries of entertainment. They experiment with emerging technologies in gaming, sports, and digital collectibles, and are the creators of ZED and now the ZEST Play Platform. Follow ZED on Twitter or join their community on Discord or Telegram. |
NEAR at ETHCC: Horizon Pitch Contest, BOS Workshops, and More
COMMUNITY
July 16, 2023
As Day One at NEAR @ ETHCC concludes, there’s palpable growing excitement for what’s in store for tomorrow. Held at the beautiful Museum National D’Histoire Naturelle in Paris, the first day of workshops and sessions proved to be an exceptional success for Ethereum and BOS builders.
Day Two is gearing up to take the experience to a whole new level, with a primary focus on founders and their ventures.
Morning and Early Afternoon Sessions: Fostering Innovation
Day Two will kick off with a casual networking opportunity over café au laits and pastries. It’ll be a great way to get warmed up and connect builders, innovators, and visionaries within the NEAR ecosystem.
The first main event of the day will be a special workshop held by Matt Stephenson , Head of Cryptoeconomics at Pantera Capita, along with Pantera Principal, Ryan Barney. His insights on the opportunities and challenges within blockchain economics will deepen participants’ understanding of the critical economic principles underpinning blockchain ecosystems.
As the morning sessions conclude, the afternoon will kick off by delving into the world of interoperability, onboarding, and value generation with Vik Pandey from NEAR Foundation. Vik has been actively involved in the development of the BOS, focusing on interoperability, open-source technologies, and blockchain success efforts.
During his session, “Interoperability, Onboarding, and Value Generation with the BOS,” Vik will share insights from his work, highlighting the ways in which the BOS fosters innovation and impact in the Open Web.
Late Afternoon Highlights: Regulatory Discussions and Horizon Workshop
Next on the agenda is a panel of experts moderated by Mya Shofany, regulatory lead at NEAR Foundation. The discussion will delve into regulatory considerations in blockchain, and tackle some of the most critical issues facing Web3 founders in the current regulatory landscape.
The panel will be followed by one of the day’s most anticipated events — the Horizon afternoon. This session will be a deep dive into the cutting-edge ideas poised to redefine the blockchain world, spearheaded by NEAR’s new Web3 accelerator arm.
As Day Two winds down, participants can enjoy relaxed networking during the Horizon Happy Hour. Here, NEAR and Ethereum enthusiasts can reflect on the day’s learnings, forge new connections, and unwind over drinks and appetizers.
If you would like to browse the official schedule, head to near.org.ethcc
Throughout the two days of NEAR @ ETHCC, participants are not just learning about the Blockchain Operating System (BOS), they’re experiencing it firsthand. Day Two promises a packed schedule of learning, building, and networking opportunities.
For those who couldn’t join us on Day One, you can catch up on the sessions uploaded on the NEAR Protocol YouTube channel. Prepare for Day Two by soaking up the insights shared by our experts.
Stay connected with us for more updates and insights from NEAR @ ETHCC as we continue to explore the limitless possibilities of the Blockchain Operating System (BOS).
|
NEAR Foundation PR Roundup for June
NEAR FOUNDATION
July 3, 2023
As June comes to a close, summer in the NEAR ecosystem is heating up with a wave of new announcements, events, media appearances, and more. Not to mention a few notable celebrities bringing some star power into NEAR’s orbit. Here’s a rundown of all the newsworthy NEAR happenings over the past month.
Sammy Hagar and Guy Fieri jump into NFTs on NEAR
In the US, Grammy-winning musician Sammy Hagar and celebrity chef Guy Fieri joined the NEAR ecosystem, teaming up with NEAR on-ramp Trident3 to launch an NFT loyalty program. The Santo Spirits Club loyalty program, as reported by Coindesk and Decrypt, will enable tequila fans to earn on-chain tiered perks and an opportunity to win a virtual tasting with the duo.
Mirae Asset, MARBLEX, and Vortex boost South Korea
Over in Asia, NEAR Foundation continued to make inroads in South Korea. Mirae Asset, a subsidiary of Asia’s largest financial group, announced a partnership to research Web3’s role in global business. Per Bloomberg, Mirae Asset will collaborate with NEAR Foundation to strengthen the Web2/3 business network and identify opportunities for real-world blockchain value creation.
Meanwhile, Blockchain Reporter broke that Marblex – a Korean blockchain infrastructure provider for high-quality gaming – will integrate NEAR protocol with Marblex’s gaming universe, enhancing user convenience and Web3 adoption. NEAR will integrate with MARBLEX’s WARP Bridge, taking advantage of NEAR’s high scalability and speed to improve the gaming experience in Web3. The partnership will also enable joint marketing initiatives and events, boosting awareness of the global blockchain gaming market.
Then there’s Vortex Gaming, a Web3 subsidiary of Inven, the largest game media community in Korea. Coverage by European Gaming reported that Vortex will leverage NEAR protocol to integrate a gaming community encompassing Web2 and Web3 by building innovative infrastructure for gaming developers. The NEAR Foundation and Inven will also collaborate on marketing and business development, adding to NEAR’s exciting Web3 gaming ecosystem.
Skoda launches metaverse for auto fans in India
Czech Automobile Manufacturer Skoda entered the Metaverse in the world’s most populous country, giving users an opportunity to explore, collect and own digital art pieces on NEAR. The platform, as reported by Cointelegraph and Entrepreneur India, will enable NFT owners to access exclusive perks and rewards, while allowing owners to trade digital artwork in the future.
SailGP christens The Dock for decentralized fandom
In more partnership news, the Global racing league SailGP and Oracle announced the launch of “The Dock”, a decentralized fan engagement platform powered by Oracle and NEAR’s ongoing partnership to bridge the worlds of Web2 and Web3. As reported by SailWeb, The Dock will revolutionize how fans follow SailGP, increasing engagement through exclusive content and enabling fans to earn points, redeemable for exciting rewards including VIP access to SailGP events and more.
Alibaba Cloud and Women in Web3 headline Collision
The NEAR ecosystem took over Toronto this month, showcasing the best of BOS at Collision 2023, one of the world’s biggest tech conferences. During the event, the NEAR Foundation announced a groundbreaking partnership with Alibaba, enabling developers across Asia to launch new NEAR validators with Alibaba Cloud’s infrastructure as a service.
The partnership was covered in myriad outlets such as Coindesk, Journal du Coin, and BTC Echo. Partnering with Alibaba means the NEAR ecosystem will have access to Remote Procedure Calls (RPC) and enable users to interact with NEAR’s Blockchain Operating System while using Alibaba Cloud’s infrastructure.
The NEAR Foundation also released the Women in Web3 Changemakers List 2023, celebrating the achievements of extraordinary women throughout the Web3 ecosystem. As reported by Tech Funding News, the ten women were selected by the public and hail from all corners of the globe, following hundreds of nominations from the Web3 community.
Leadership viewpoints on media and social fairness
Illia Polosukhin, Founder of NEAR and CEO of Pagoda, took the time to write a thought leadership piece in Blockworks about crypto’s potential to transform how we interact with the media. Illia sets out the emerging problem with the status quo: bad actors are beginning to utilize generative AI to dramatically scale up misinformation campaigns.
However, Illia explains that blockchain-based “sign-and-trace” systems can enable the public to reliably source and validate real news stories, with a legitimate trail of sources available online.
CEO of NEAR Foundation Marieke Flament also penned an article for London’s leading daily business paper CityAM about using Web3 to build a fair and inclusive digital world. “Too often technology has only benefited the few: those who have money, those who have power, or those of a certain gender, ethnicity, or skin color.
But this doesn’t need to be the case,” she explained. “Technology can and should be in the service of all people. But to achieve this, we will need a change in perspective, something that Web3 can help us achieve.”
Marieke also talked about blockchain, Web3, and BOS on a podcast hosted by the editor Journal du Coin – France’s leading crypto media outlet, and for a video interview with Fintech Finance at the Paris Fintech Forum.
That’s all for this month. If we missed anything or want to share anything for next month’s roundup, get in touch! |
NEAR Teams With Google Cloud to Accelerate Web3 Startups
DEVELOPERS
October 4, 2022
NEAR Foundation is excited to announce a new partnership between Google Cloud and NEAR Protocol. Going forward, Google Cloud will provide technical support for NEAR grant recipients. Open and developer-friendly, Google Cloud will support devs as they build and scale their Web3 projects and dApps.
If you’re developing on NEAR, this is great news—the partnership will supercharge blockchain innovations. Developers will even more easily create without limits as they build dApps and help onboard the masses into Web3.
“We are thrilled to be collaborating with those who pioneered the Internet as we know it,” says Marieke Flament, CEO of the NEAR Foundation. “This partnership marks a new chapter for us as we continue to offer the best support possible for the next generation of visionaries choosing to build on the NEAR protocol.”
Powering NEAR developers with Google Cloud
In the last year, NEAR has grown exponentially thanks to its super-fast, incredibly secure, and infinitely scalable protocol. There are now over 20 million accounts, 200 million transactions to date, and 300,000 to 400,000 transactions per day on the NEAR network. Building upon the momentum of NEARCON 2022, which showcased the NEAR ecosystem’s vibrancy, 800 projects are now building on the protocol.
How will the hundreds of projects currently building on NEAR benefit from the Google Cloud partnership?
Google Cloud provides the infrastructure for NEAR’s Remote Procedure Call (RPC) node provider to Pagoda, NEAR’s Web3 startup platform. This allows developers to deploy code quickly, securely, and seamlessly. Pagoda helps developers easily and rapidly launch dApps on NEAR through a library of pre-audited templates and auto-generated contract user interfaces.
“We will be supporting NEAR and giving Web3 developers the most secure, reliable, and sustainable cloud infrastructure on which they can build and scale,” Carlos Arena, Director of Digital Assets at Google Cloud. “We continue to support tomorrow’s leaders in creating new products and services on blockchain-based platforms.”
For more information on how Google Cloud is working to support Web3 innovation, check out Google Cloud’s Digital Assets blog. |
---
id: chain-signatures
title: What are Chain Signatures?
sidebar_label: What are Chain Signatures?
---
Chain signatures enable NEAR accounts, including smart contracts, to sign and execute transactions across many blockchain protocols.
This unlocks the next level of blockchain interoperability by giving ownership of diverse assets, cross-chain accounts, and data to every single NEAR account.
![chain-signatures](/docs/assets/welcome-pages/chain-signatures-overview.png)
_Diagram of a chain signature in NEAR_
:::info Looking for code?
To get started using Chain Signatures in your project see **[Create a Chain Signature](../../2.build/1.chain-abstraction/chain-signatures.md)**.
:::
:::caution
This technology is currently in `alpha` and should only be used in a `testnet` environment.
:::
---
## How It Works
Controlling accounts and their assets on other blockchain platforms is made possible thanks to the interaction between three elements:
1. [**Derivation Paths**](#derivation-paths-one-account-multiple-chains) - A deterministic way to derive foreign addresses from one NEAR account
2. [**Multichain Smart Contract**](#multichain-smart-contract) - Receives requests to sign a transaction for other blockchains
3. [**Multiparty Computation Service**](#multi-party-computation-service) Third-party service providing signatures to the contract
<hr class="subsection" />
### Derivation Paths: One Account, Multiple Chains
Chain Signatures link NEAR accounts to addresses in other blockchain using [Additive Key Derivation](https://eprint.iacr.org/2021/1330) (a simple mechanism for deriving many subkeys from a single master key). These keys are generated using `derivation paths` (or `paths` for short).
A `derivation path` is simply a string (e.g. `ethereum-1`, `ethereum-2`, etc) that in conjunction with the NEAR account derives a unique address on the target blockchain.
For example, we can derive multiple Ethereum addresses from `example.near` by using different paths:
1. `example.near` + `ethereum-1` = `0x1b48b83a308ea4beb845db088180dc3389f8aa3b`
2. `example.near` + `ethereum-2` = `0x99c5d3025dc736541f2d97c3ef3c90de4d221315`
3. `example.near` + `...` = `0x...`
It is important to note that this allows us to discover the **public address** of the foreign account that we can control. To actually control the foreign account, we need to request signatures from the MPC service.
:::tip
In practice, the external address is deterministically derived using the NEAR address (`example.near`), the path (`ethereum-1`) and the MPC service's public key
:::
:::info
See [**Create a Chain Signature - how the derivation is implemented**](../../2.build/1.chain-abstraction/chain-signatures.md#1-deriving-the-foreign-address) for an example implementation
:::
<hr class="subsection" />
### Multichain Smart Contract
A deployed multichain smart contract is used to request signatures for transactions on other blockchains.
This contract has a `sign` method that takes two parameters:
1. The `payload` (transaction) to be signed for the target blockchain
2. The `path` that identifies the account you want to use to sign the transaction.
For example, a user could request a signature to `send 0.1 ETH to 0x060f1...` **(transaction)** using the `ethereum-1` account **(path)**.
After a request is made, the `sign` method starts recursively calling itself to wait while the [MPC signing service](#multi-party-computation-service-mpc) signs the transaction.
Once the signature is ready, the contract gains access to it and returns it to the user. This signature is a valid signed transaction that can be readily sent to the target blockchain to be executed.
<details>
<summary> A Contract Recursively Calling Itself? </summary>
NEAR smart contracts are unable to halt execution and await the completion of a process. To solve this, one can make the contract call itself again and again checking on each iteration to see if the result is ready.
**Note:** Each call will take one block which equates to ~1 second of waiting. After some time the contract will either return a result that an external party provided or return an error running out of GAS waiting.
</details>
:::info
See [**Create a Chain Signature - requesting the signature**](../../2.build/1.chain-abstraction/chain-signatures.md#3-requesting-the-signature) for an example implementation
:::
<hr class="subsection" />
### Multi-Party Computation Service
The essence of Multi-Party Computation (MPC) is to enable independent parties to perform shared computations on private information without revealing secrets to each other. In practice, this system can be used with blockchain platforms to safely sign a transaction on behalf of a user without ever having to expose a private key.
NEAR's MPC service is comprised of several independent nodes, **none of which can sign by itself**, but instead create **signature-shares** that are **aggregated through multiple rounds** to **jointly** sign a transaction.
This service continuously listens for signature requests (i.e. users calling the `sign` method on the `multichain` smart contract) and when a call is detected the MPC service:
1. Asks its nodes to jointly derive a signature for the `payload` using the account identified by the `path`
2. Once complete, call the `multichain` contract to store the resulting `Signature`
:::info A Custom MPC Service
Generally, MPC signing services work by sharing a master key, which needs to be re-created each time a node joins or leaves.
NEAR's MPC service allows for nodes to safely join and leave, without needing to re-derive a master key
:::
:::tip
Want to learn more about the mathematics that enable MPC? [**Check this awesome article**](https://www.zellic.io/blog/mpc-from-scratch/)
:::
---
## Concluding Remarks
Chain Signatures are a powerful tool that allows NEAR accounts to control accounts on other blockchains. This is a fundamental step towards enabling true ownership of cross-chain data and assets.
For the user, the process is made completely **on chain**, since they only need to make a call to a smart contract and wait for the response.
Thanks to `derivation paths`, a single NEAR account can control **multiple accounts** on different blockchains, and thanks to the MPC service, the user can be sure that **nobody but themselves** can request signatures for those accounts.
|
---
id: welcome
title: Security
---
Here you will find information on how to keep your smart contract and decentralized applications secure.
:::tip
Please take some time to go through this section, it will help you to keep your dApp safe
:::
---
## 🐞 Bug Bounty Program
NEAR has a [revamped bug bounty program](./bounty.md), use it if you find any security errors in the protocol or mainstream apps.
## ✅ Security Checklist
Make sure to keep your smart contract safe by running through our [security checklist](checklist.md).
## 🛡️ Security Concepts
Learn important security concepts to keep your dApp safe and sound. Read about:
- Keeping [callbacks safe](./callbacks.md).
- Understanding [frontrunning](./frontrunning.md).
- Understanding [sybil attacks](./sybil.md).
- Understanding [reentrancy attacks](./reentrancy.md).
- Making sure the owner of an account is [the one calling](./one_yocto.md).
- Understanding the complexity of [generating random numbers](./random.md).
- Protecting from a [small deposit attacks](./storage.md) draining your account. |
---
sidebar_position: 2
title: Sending Native Tokens
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# Sending $NEAR
You might want to send tokens from a contract for many reasons.
- The contract uses something like the [Storage Standard](https://nomicon.io/Standards/StorageManagement) and needs to return deposits to users when they unregister.
- Users pay into the contract and the contract later pays these fees to the maintainers, redistributes them to users, or disburses them to some cause the users vote on.
- And more!
Blockchains give us programmable money, and the ability for a smart contract to send tokens lies at the heart of that ability.
NEAR makes this easy. Transferring NEAR tokens is the simplest transaction you can send from a smart contract. Here's all you need:
```js
let amount = BigInt(1_000_000_000_000_000_000_000_000); // 1 $NEAR as yoctoNEAR
let to = "alice.near";
NearPromise.new(to).transfer(amount);
```
In the context of a full contract and function call, this could look like:
```js
import { NearPromise, NearBindgen } from "near-sdk-js";
@NearBindgen({})
export class Contract {
pay({ amount, to }) {
return NearPromise.new(to).transfer(amount);
}
}
```
Most of this is boilerplate you're probably familiar with by now – imports, setting up [`NearBindgen`](../contract-structure/near-bindgen.md), etc. Some interesting details related to the transfer itself:
- The `pay` method defined here accepts JSON as input, and numbers in JS [cannot be larger than `2^53-1`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER), so for compatibility with deserializing JSON to JS, the integer is serialized as a string. Since the `transfer` method takes a value in [yocto](https://en.wikipedia.org/wiki/Yocto-)NEAR, it's likely to need numbers much larger than `2^53-1`.
- Returning the `NearPromise`: This allows NEAR Explorer, near-cli, near-api-js, and other tooling to correctly determine if a whole chain of transactions is successful. If your function does not return `Promise`, tools like near-cli will return immediately after your function call. And then even if the `transfer` fails, your function call will be considered successful.
Using near-cli or near-cli-rs, someone could invoke this function with a call like:
<Tabs className="language-tabs" groupId="code-tabs">
<TabItem value="near-cli">
```bash
near call <contract> pay '{"amount": "1000000000000000000000000", "to": "example.near"}' --accountId benjiman.near
```
</TabItem>
<TabItem value="near-cli-rs">
```bash
near contract call-function as-transaction <contract> pay json-args '{"amount": "1000000000000000000000000", "to": "example.near"}' prepaid-gas '30 TeraGas' attached-deposit '0 NEAR' sign-as benjiman.near network-config testnet sign-with-keychain send
```
</TabItem>
</Tabs>
|
```rust
// Validator interface, for cross-contract calls
#[ext_contract(ext_nft_contract)]
trait ExternalNftContract {
fn nft_token(&self, token_id: TokenId) -> Promise;
}
// Implement the contract structure
#[near_bindgen]
impl Contract {
pub fn nft_token(&self, token_id: TokenId) -> Promise {
let promise = ext_nft_contract::ext(self.nft_contract.clone())
.nft_token(token_id);
return promise.then( // Create a promise to callback query_greeting_callback
Self::ext(env::current_account_id())
.nft_token_callback()
)
}
#[private] // Public - but only callable by env::current_account_id()
pub fn nft_token_callback(&self, #[callback_result] call_result: Result<Token, PromiseError>) -> Option<Token> {
// Check if the promise succeeded
if call_result.is_err() {
log!("There was an error contacting NFT contract");
return None;
}
// Return the token data
let token_data: Token = call_result.unwrap();
return Some(token_data);
}
}
``` |
How NEAR Went Carbon Neutral
COMMUNITY
November 1, 2021
Climate change, like the pandemic, is a global crisis that increasingly demands the world’s attention. A global imperative, it will require much collective work across many industries and markets to help mitigate its effects. Which makes the 2021 United Nations Climate Change Conference (COP26) a critical one.
Silicon Valley isn’t usually singled out for its carbon footprint, but the reality is that each company plays a role in a much larger carbon consumption whole. If you’re a web-based startup, then you’re on the electrical grid — that means your platform is almost certainly powered by fossil fuels.
From inception, NEAR has focused on a computational alternative to PoW. In this system, known as Proof-of-Stake (PoS), there are no miners. Instead, validators stake a given token amount to allow themselves to take part. PoS blockchains incentivise communities to own and control the network. Only then can they validate blocks and collect a block award.
PoS is integral to NEAR’s core values of simplicity, scalability, and security, which will help redefine business, creativity, and community. Since we launched amidst growing concern over climate change, we’ve been actively applying these values to help others reimagine the world, and do it in a carbon neutral way.
Functionally, NEAR’s PoS , what we call Nightshade, allows the platform to realize its ambition of being simple, scalable, and secure. But on a social and ecological level, sharding allows NEAR to deliver on its carbon neutral commitment.
Let’s dive into NEAR Protocol’s sharding system, and explore a few other initiatives NEAR has been taking on its journey to carbon neutrality.
Why Proof-of-Stake enables the Carbon Neutral shift
Proof-of-Work (PoW) blockchain platforms have in recent years attracted much attention for the electrical power needed to run their mining computations. Indeed, PoW lies at the heart of crypto’s energy debate.
In PoW, a massive amount of mining gear is put to work on the computations needed to produce blocks. Miners — many of them large operations with a bunch of gear — compete for block rewards. Over time, PoW mining becomes more difficult, requiring more gear to perform more time-consuming computations, all of it leading to escalating amounts of energy consumption.
With Proof-of-Stake, a network architecture used by NEAR and some other platforms, we have a novel and exciting way of making crypto carbon neutral. As a computational alternative to PoW, there is no mining or arms race. Instead of miners, PoS uses validators that have to commit a given amount of tokens before they can be eligible to take part in the network.
If we’re talking energy efficiency, PoS-based blockchains are orders of magnitude better than PoW platforms, like Bitcoin. Ethereum is currently planning on transitioning to PoS in the next few years.
NEAR’s PoS ecosystem is already up and running, giving the community the opportunity to build on a climate neutral blockchain, today.
Nightshade: A key to Carbon Neutrality
A year after our mainnet launch, NEAR has already attracted a robust community of developers and users. While our throughput (network capacity) makes for a fast, scalable, and budget-friendly alternative to Bitcoin and Ethereum, the NEAR platform’s capacity won’t stop with the mainnet.
As promised, NEAR’s Nightshade will expand throughput via sharding, a scaling technology that divides computation across “shards” running in parallel. Nightshade allows each transaction to be far more energy efficient than PoW platforms, since the sharding approach allows for scaling without a corresponding uptick in energy consumption.
How, you might ask? With NEAR’s Nightshade, each transaction is processed on a shard instead of by every node in the network. Alongside PoS, this significantly reduces blockchain energy consumption, thus reducing the blockchain’s carbon footprint.
NEAR’s other Carbon Neutral initiatives
The NEAR platform’s climate change efforts go beyond PoS and sharding. As part of making the ecosystem climate neutral, NEAR asked South Pole, a leading Zurich-based project developer and global climate solutions provider, to audit NEAR’s carbon footprint. We also asked for guidance on how to reduce our carbon footprint where possible, and if not, provide ways for NEAR to offset its remaining carbon.
South Pole’s audit included NEAR Foundation’s carbon footprint, the Core Collective (all employees and contractors working on the protocol), and all validators. The firm found that NEAR Protocol generates 174 tons of CO2 annually, making it 200,000 times more energy efficient than Bitcoin. Much of this is due to NEAR’s application of PoS technology instead of PoW. As noted above, growth in blockchain throughput means that our carbon footprint will only grow marginally in the coming years.
What this means for the future of blockchain
NEAR’s PoS and Nightshade architecture is the future of blockchain. But many other exciting advances and possibilities are on the horizon, especially as expanded throughput leads to more adoption and app development. Just recently, Open Forest Protocol, a forestation tracking solution built on NEAR.
We foresee, in the near future (no pun intended), many more dApp developers launching projects on the NEAR ecosystem that deal directly with environmental sustainability.
The blockchain industry is already seeing projects focused on tracking the provenance of recycling initiatives. We will also see more blockchain-based validations of supply chains, giving local producers of goods fairer, more sustainable profits for their families and communities.
DeFi will also play a major role in climate action. Imagine a world where individuals from across the globe can help finance climate change projects in wonderfully decentralized ways, bypassing both bureaucratic red tape and any resistance or hesitance from centralized financial institutions and corporations.
We want the fast-growing NEAR community to reimagine the world.
Collectively, the community has the power and means to affect local and global change through blockchain innovation. |
---
id: hype-indexer
title: Hype Indexer
sidebar_label: Hype Indexer
---
:::info
NEAR QueryAPI is currently under development. Users who want to test-drive this solution need to be added to the allowlist before creating or forking QueryAPI indexers.
You can request access through [this link](http://bit.ly/near-queryapi-beta).
:::
## Overview
This indexer creates a new row in a pre-defined `posts` or `comments` table created by the user in the GraphQL database for every new post or comment found on the blockchain that contains either "PEPE" or "DOGE" in the contents. This is a simple example that shows how to specify two tables, filter blockchain transaction data for a specific type of transaction and its contents, and save the data to the database.
:::tip
This indexer can be found by [following this link](https://near.org/#/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=bucanero.near/hype-indexer).
:::
## Defining the Database Schema
The first step to creating an indexer is to define the database schema. This is done by editing the `schema.sql` file in the code editor. The schema for this indexer looks like this:
```sql
CREATE TABLE
"posts" (
"id" TEXT NOT NULL,
"account_id" VARCHAR NOT NULL,
"block_height" DECIMAL(58, 0) NOT NULL,
"block_timestamp" DECIMAL(20, 0) NOT NULL,
"receipt_id" VARCHAR NOT NULL,
"content" TEXT NOT NULL,
CONSTRAINT "posts_pkey" PRIMARY KEY ("id")
);
CREATE TABLE
"comments" (
"id" SERIAL NOT NULL,
"post_id" TEXT NOT NULL,
"account_id" VARCHAR NOT NULL,
"block_height" DECIMAL(58, 0) NOT NULL,
"block_timestamp" DECIMAL(20, 0) NOT NULL,
"receipt_id" VARCHAR NOT NULL,
"content" TEXT NOT NULL,
CONSTRAINT "comments_pkey" PRIMARY KEY ("id")
);
```
This schema defines two tables: `posts` and `comments`. The `posts` table has columns:
- `id`: a unique identifier for each row in the table
- `account_id`: the account ID of the user who created the post
- `block_height`: the height of the block in which the post was created
- `block_timestamp`: the timestamp of the block in which the post was created
- `receipt_id`: the receipt ID of the transaction that created the post
- `content`: the content of the post
The `comments` table has columns:
- `id`: a unique identifier for each row in the table
- `post_id`: the ID of the post that the comment was made on
- `account_id`: the account ID of the user who created the comment
- `block_height`: the height of the block in which the comment was created
- `block_timestamp`: the timestamp of the block in which the comment was created
- `receipt_id`: the receipt ID of the transaction that created the comment
- `content`: the content of the comment
## Defining the indexing logic
The next step is to define the indexing logic. This is done by editing the `indexingLogic.js` file in the code editor. The logic for this indexer can be divided into two parts:
1. Filtering blockchain transactions for a specific type of transaction
2. Saving the data from the filtered transactions to the database
### Filtering Blockchain transactions
The first part of the logic is to filter blockchain transactions for a specific type of transaction. This is done by using the `getBlock` function. This function takes in a block and a context and returns a promise. The block is a Near Protocol block, and the context is a set of helper methods to retrieve and commit state. The `getBlock` function is called for every block on the blockchain.
The `getBlock` function for this indexer looks like this:
```js
import { Block } from "@near-lake/primitives";
async function getBlock(block: Block, context) {
const SOCIAL_DB = "social.near";
function base64decode(encodedValue) {
let buff = Buffer.from(encodedValue, "base64");
return JSON.parse(buff.toString("utf-8"));
}
function get_near_social_posts_comments(
block_type = block,
DB = SOCIAL_DB,
decodeFunction = base64decode
) {
const nearSocialPostsComments = block_type
.actions()
.filter((action) => action.receiverId === DB)
.flatMap((action) =>
action.operations
.map((operation) => operation["FunctionCall"])
.filter((operation) => operation?.methodName === "set")
.map((functionCallOperation) => ({
...functionCallOperation,
args: decodeFunction(functionCallOperation.args),
receiptId: action.receiptId, // providing receiptId as we need it
}))
.filter((functionCall) => {
const accountId = Object.keys(functionCall.args.data)[0];
return (
Object.keys(functionCall.args.data[accountId]).includes("post") ||
Object.keys(functionCall.args.data[accountId]).includes("index")
);
})
);
return nearSocialPostsComments;
}
const nearSocialPostsComments = get_near_social_posts_comments();
... // Further filtering for posts/comments that contain "PEPE" or "DOGE" in the contents and saving the data to the database is done in the next section
}
```
Again, like with the [`posts-indexer`](./posts-indexer.md) or the [`feed-indexer`](./feed-indexer.md), this filter selects transactions that are of type `FunctionCall` to the `set` method on the contract `social.near` on the network. In addition, it searches for `post` or `index` string in the data for the call.
### Saving the data to the Database
The second part of the logic is to save the data from the filtered transactions to the database. This section also performs the filtering of transactions for posts and comments that contain "PEPE" or "DOGE" in the contents.
The logic for this looks like:
```js
... // Logic for filtering blockchain transactions is above
if (nearSocialPostsComments.length > 0) {
const blockHeight = block.blockHeight;
const blockTimestamp = Number(block.header().timestampNanosec);
await Promise.all(
nearSocialPostsComments.map(async (postAction) => {
const accountId = Object.keys(postAction.args.data)[0];
console.log(`ACCOUNT_ID: ${accountId}`);
const isPost =
postAction.args.data[accountId].post &&
Object.keys(postAction.args.data[accountId].post).includes("main");
const isComment =
postAction.args.data[accountId].post &&
Object.keys(postAction.args.data[accountId].post).includes("comment");
if (isPost) {
const isHypePost =
postAction.args.data[accountId].post.main.includes("PEPE") ||
postAction.args.data[accountId].post.main.includes("DOGE");
if (!isHypePost) {
return;
}
console.log("Creating a post...");
const postId = `${accountId}:${blockHeight}`;
await createPost(
postId,
accountId,
blockHeight,
blockTimestamp,
postAction.receiptId,
postAction.args.data[accountId].post.main
);
}
if (isComment) {
const commentString = JSON.parse(
postAction.args.data[accountId].post.comment
);
const isHypeComment =
commentString.includes("PEPE") || commentString.includes("DOGE");
if (!isHypeComment) {
return;
}
console.log("Creating a comment...");
const postBlockHeight =
postAction.args.data[accountId].post.blockHeight;
const postId = `${accountId}:${postBlockHeight}`;
await createComment(
accountId,
postId,
blockHeight,
blockTimestamp,
postAction.receiptId,
commentString
);
}
})
);
}
... // Definitions for createPost and createComment are below
```
#### `createPost`
Creating a post is done by using the [`context.db.Posts.insert()`](../../../2.build/6.data-infrastructure/query-api/context.md#insert) function:
```js
async function createPost(
postId,
accountId,
blockHeight,
blockTimestamp,
receiptId,
postContent
) {
try {
const postObject = {
id: postId,
account_id: accountId,
block_height: blockHeight,
block_timestamp: blockTimestamp,
receipt_id: receiptId,
content: postContent,
};
await context.db.Posts.insert(postObject);
console.log("Post created!");
} catch (error) {
console.error(error);
}
}
```
#### `createComment`
Creating a comment is done by using the [`context.db.Comments.insert()`](../../../2.build/6.data-infrastructure/query-api/context.md#insert) function:
```js
async function createComment(
accountId,
postId,
blockHeight,
blockTimestamp,
receiptId,
commentContent
) {
try {
const commentObject = {
account_id: accountId,
post_id: postId,
block_height: blockHeight,
block_timestamp: blockTimestamp,
receipt_id: receiptId,
content: commentContent,
};
await context.db.Comments.insert(commentObject);
console.log("Comment created!");
} catch (error) {
console.error(error);
}
}
```
## Querying data from the indexer
The final step is querying the indexer using the public GraphQL API. This can be done by writing a GraphQL query using the GraphiQL tab in the code editor.
For example, here's a query that fetches `posts` and `comments` from the _Hype Indexer_, ordered by `block_height`:
```graphql
query MyQuery {
<user-name>_near_hype_indexer_posts(order_by: {block_height: desc}) {
account_id
block_height
content
}
<user-name>_near_hype_indexer_comments(order_by: {block_height: desc}) {
account_id
block_height
content
}
}
```
Once you have defined your query, you can use the GraphiQL Code Exporter to auto-generate a JavaScript or NEAR Widget code snippet. The exporter will create a helper method `fetchGraphQL` which will allow you to fetch data from the indexer's GraphQL API. It takes three parameters:
- `operationsDoc`: A string containing the queries you would like to execute.
- `operationName`: The specific query you want to run.
- `variables`: Any variables to pass in that your query supports, such as `offset` and `limit` for pagination.
Next, you can call the `fetchGraphQL` function with the appropriate parameters and process the results.
Here's the complete code snippet for a NEAR component using the _Hype Indexer_:
```js
const QUERYAPI_ENDPOINT = `https://near-queryapi.api.pagoda.co/v1/graphql/`;
State.init({
data: []
});
const query = `query MyHypeQuery {
<user-name>_near_hype_indexer_posts(order_by: {block_height: desc}) {
account_id
block_height
content
}
<user-name>_near_hype_indexer_comments(order_by: {block_height: desc}) {
account_id
block_height
content
}
}`
function fetchGraphQL(operationsDoc, operationName, variables) {
return asyncFetch(
QUERYAPI_ENDPOINT,
{
method: "POST",
headers: { "x-hasura-role": `<user-name>_near` },
body: JSON.stringify({
query: operationsDoc,
variables: variables,
operationName: operationName,
}),
}
);
}
fetchGraphQL(query, "MyHypeQuery", {}).then((result) => {
if (result.status === 200) {
if (result.body.data) {
const data = result.body.data.<user-name>_near_hype_indexer_posts;
State.update({ data })
console.log(data);
}
}
});
const renderData = (a) => {
return (
<div key={JSON.stringify(a)}>
{JSON.stringify(a)}
</div>
);
};
const renderedData = state.data.map(renderData);
return (
{renderedData}
);
```
:::tip
To view a more complex example, see this widget which fetches posts with proper pagination: [Posts Widget powered By QueryAPI](https://near.org/edit/roshaan.near/widget/query-api-feed-infinite).
:::
|
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs groupId="nft-contract-tabs" className="file-tabs">
<TabItem value="Paras" label="Paras">
```js
import { Wallet } from './near-wallet';
const CONTRACT_ADDRESS = "marketplace.paras.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'storage_deposit',
args: {
receiver_id: "bob.near"
},
contractId: CONTRACT_ADDRESS,
gas: 300000000000000, // attached GAS (optional)
deposit: 9390000000000000000 // attached deposit in yoctoNEAR (optional)
});
await wallet.callMethod({
method: 'nft_approve',
args: {
token_id: "1e95238d266e5497d735eb30",
account_id: "marketplace.paras.near",
msg: {
price: "200000000000000000000000",
market_type: "sale",
ft_token_id: "near"
}
},
contractId: "nft.primitives.near"
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
Method `nft_approve` of a NFT contract also calls the `nft_on_approve` method in `marketplace.paras.near` as a callback.
</TabItem>
<TabItem value="Mintbase" label="Mintbase">
```js
import { Wallet } from './near-wallet';
const CONTRACT_ADDRESS = "simple.market.mintbase1.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'deposit_storage',
args: {
autotransfer: true
},
contractId: CONTRACT_ADDRESS,
gas: 300000000000000, // attached GAS (optional)
deposit: 9390000000000000000 // attached deposit in yoctoNEAR (optional)
});
await wallet.callMethod({
method: 'nft_approve',
args: {
args: {
token_id: "3c46b76cbd48e65f2fc88473",
account_id: "simple.market.mintbase1.near",
msg: {
price: "200000000000000000000000"
}
},
},
contractId: "nft.primitives.near"
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
Method `nft_approve` of a NFT contract also calls the `nft_on_approve` method in `simple.market.mintbase1.near` as a callback.
:::tip
Check how to also do this using the [`Mintbase JS`](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/sdk/list)
:::
</TabItem>
</Tabs>
|
---
id: minting-nft-frontend
title: Minting NFT Front-end
sidebar_label: Minting Front-end
---
import {Github} from "@site/src/components/codetabs"
# NFT Minting Front-end
> In this tutorial you'll learn how to create a simple NFT front-end and mint a "Go Team" NFT on the NEAR blockchain straight from your web browser.
## App Overview
The app is fairly simple: the user signs in and hits the <kbd>Mint NFT</kbd> button. Once the user hits the mint button, a "Go Team" NFT is minted and sent to their NEAR Wallet.
![Front-end](/docs/assets/nfts/nft-mint-frontend.png)
## Smart Contract code
The code for the NFT smart contract can be found in the [Zero to Hero NFT tutorial](/tutorials/nfts/introduction)'s [GitHub repository](https://github.com/near-examples/nft-tutorial/tree/main/nft-contract/src), under the `main` branch.
The contract methods used in this application are as follows:
- `nft_mint`: Function used to mint tokens.
- `check_token`: Custom function created to check for the existence of a token. This helps to ensure one token per user.
## Front-end
The front-end of the contract was implemented using `create-near-app`. [React Bootstrap](https://react-bootstrap.github.io/) was used for the styling of the application.
To bootstrap your React front-end, run the following command on your terminal:
```sh
npx create-near-app --frontend react --contract rust
```
Then, simply import the contract files from the `main` branch, and you'll have the needed structure to run the application.
### Start
Upon mounting the application's components, the app checks for the existence of a non-fungible token.
<Github language="js" start="24" end="46" url="https://github.com/near-examples/nft-tutorial-frontend/blob/master/src/App.js" />
If no prior NFT has been minted, the mint button will be available for use.
### Mint button
Here is the function behind the mint button. The meta data has been filled out for the user already:
- `token_id` is set by the user's account id,
- and the `media` link is hard-coded to a `goteam-gif.gif` hosted on IPFS.
<Github language="js" start="7" end="23" url="https://github.com/near-examples/nft-tutorial-frontend/blob/master/src/Components/MintingTool.js" />
After hitting the <kbd>Mint NFT</kbd> button the user will be able to check out the newly minted NFT at [wallet.testnet.near.org](https://testnet.mynearwallet.com//?tab=collectibles), under the Wallet's `Collectibles` tab.
## Final remarks
You can find the complete application repository [on GitHub](https://github.com/near-examples/nft-tutorial-frontend) to clone and run.
In the configuration folder you can see that this smart contract has been deployed to `nft-frontend-simple-mint.blockhead.testnet`:
<Github language="js" start="1" end="2" url="https://github.com/near-examples/nft-tutorial-frontend/blob/master/src/config.js" />
You can also check out the [explorer link here](https://testnet.nearblocks.io/address/nft-frontend-simple-mint.blockhead.testnet) to see how many individuals have been minting their own _Go Team_ NFTs. _**Happy Minting!**_
:::tip
Clone and run this example from https://github.com/near-examples/nft-tutorial-frontend
:::
|
# Promises API
```rust
promise_create(account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64) -> u64
```
Creates a promise that will execute a method on account with given arguments and attaches the given amount.
`amount_ptr` point to slices of bytes representing `u128`.
###### Panics
- If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
###### Returns
- Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_then(promise_idx: u64,
account_id_len: u64,
account_id_ptr: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64) -> u64
```
Attaches the callback that is executed after promise pointed by `promise_idx` is complete.
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
###### Returns
- Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_and(promise_idx_ptr: u64, promise_idx_count: u64) -> u64
```
Creates a new promise which completes when time all promises passed as arguments complete. Cannot be used with registers.
`promise_idx_ptr` points to an array of `u64` elements, with `promise_idx_count` denoting the number of elements.
The array contains indices of promises that need to be waited on jointly.
###### Panics
- If `promise_ids_ptr + 8 * promise_idx_count` extend outside the guest memory with `MemoryAccessViolation`;
- If any of the promises in the array do not correspond to existing promises panics with `InvalidPromiseIndex`.
- If called in a view function panics with `ProhibitedInView`.
###### Returns
- Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_results_count() -> u64
```
If the current function is invoked by a callback we can access the execution results of the promises that
caused the callback. This function returns the number of complete and incomplete callbacks.
Note, we are only going to have incomplete callbacks once we have `promise_or` combinator.
###### Normal execution
- If there is only one callback `promise_results_count()` returns `1`;
- If there are multiple callbacks (e.g. created through `promise_and`) `promise_results_count()` returns their number.
- If the function was called not through the callback `promise_results_count()` returns `0`.
###### Panics
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_result(result_idx: u64, register_id: u64) -> u64
```
If the current function is invoked by a callback we can access the execution results of the promises that
caused the callback. This function returns the result in blob format and places it into the register.
###### Normal execution
- If promise result is complete and successful copies its blob into the register;
- If promise result is complete and failed or incomplete keeps register unused;
###### Returns
- If promise result is not complete returns `0`;
- If promise result is complete and successful returns `1`;
- If promise result is complete and failed returns `2`.
###### Panics
- If `result_idx` does not correspond to an existing result panics with `InvalidResultIndex`.
- If copying the blob exhausts the memory limit it panics with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
###### Current bugs
- We currently have two separate functions to check for result completion and copy it.
---
```rust
promise_return(promise_idx: u64)
```
When promise `promise_idx` finishes executing its result is considered to be the result of the current function.
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
###### Current bugs
- The current name `return_promise` is inconsistent with the naming convention of Promise API.
```rust
promise_batch_create(account_id_len: u64, account_id_ptr: u64) -> u64
```
Creates a new promise towards given `account_id` without any actions attached to it.
###### Panics
- If `account_id_len + account_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
###### Returns
- Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_batch_then(promise_idx: u64, account_id_len: u64, account_id_ptr: u64) -> u64
```
Attaches a new empty promise that is executed after promise pointed by `promise_idx` is complete.
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If `account_id_len + account_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
###### Returns
- Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_batch_action_create_account(promise_idx: u64)
```
Appends `CreateAccount` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R48
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_deploy_contract(promise_idx: u64, code_len: u64, code_ptr: u64)
```
Appends `DeployContract` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R49
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If `code_len + code_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_function_call(promise_idx: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64)
```
Appends `FunctionCall` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R50
_NOTE: Calling `promise_batch_create` and then `promise_batch_action_function_call` will produce the same promise as calling `promise_create` directly._
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_transfer(promise_idx: u64, amount_ptr: u64)
```
Appends `Transfer` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R51
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_stake(promise_idx: u64,
amount_ptr: u64,
bls_public_key_len: u64,
bls_public_key_ptr: u64)
```
Appends `Stake` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R52
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If the given BLS public key is not a valid BLS public key (e.g. wrong length) `InvalidPublicKey`.
- If `amount_ptr + 16` or `bls_public_key_len + bls_public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_add_key_with_full_access(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64)
```
Appends `AddKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R54
The access key will have `FullAccess` permission, details: [/Proposals/0005-access-keys.md#guide-level-explanation](click here)
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
- If `public_key_len + public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_add_key_with_function_call(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64,
allowance_ptr: u64,
receiver_id_len: u64,
receiver_id_ptr: u64,
method_names_len: u64,
method_names_ptr: u64)
```
Appends `AddKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-156752ec7d78e7b85b8c7de4a19cbd4R54
The access key will have `FunctionCall` permission, details: [/Proposals/0005-access-keys.md#guide-level-explanation](click here)
- If the `allowance` value (not the pointer) is `0`, the allowance is set to `None` (which means unlimited allowance). And positive value represents a `Some(...)` allowance.
- Given `method_names` is a `utf-8` string with `,` used as a separator. The vm will split the given string into a vector of strings.
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
- if `method_names` is not a valid `utf-8` string, fails with `BadUTF8`.
- If `public_key_len + public_key_ptr`, `allowance_ptr + 16`, `receiver_id_len + receiver_id_ptr` or
`method_names_len + method_names_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_delete_key(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64)
```
Appends `DeleteKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R55
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
- If `public_key_len + public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
---
```rust
promise_batch_action_delete_account(promise_idx: u64,
beneficiary_id_len: u64,
beneficiary_id_ptr: u64)
```
Appends `DeleteAccount` action to the batch of actions for the given promise pointed by `promise_idx`.
Action is used to delete an account. It can be performed on a newly created account, on your own account or an account with
insufficient funds to pay rent. Takes `beneficiary_id` to indicate where to send the remaining funds.
###### Panics
- If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
- If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
- If `beneficiary_id_len + beneficiary_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
- If called in a view function panics with `ProhibitedInView`.
|
The Rainbow Bridge Is Live
COMMUNITY
April 6, 2021
Today the NEAR team is excited to announce that the Rainbow Bridge is live and ERC-20 tokens can now bridge to the NEAR blockchain and back to Ethereum.
In today’s blockchain landscape, many protocols and applications are increasingly going multi-chain. This allows developers and users to take advantage of the assets, composability, and community of Ethereum, as well as the higher throughput, lower fees, and shorter confirmation times of next-gen chains like NEAR Protocol.
Using the Rainbow Bridge today, developers can utilize Ethereum assets on NEAR, and NEAR assets on Ethereum. Soon, they will be able to access any application state from either chain, and eventually, any chain. Users bridging fungible tokens to NEAR can take advantage of NEAR’s one-to-two second transaction times, low transaction fees usually under one cent, and comparably low bridge transfer fees.
Innovation across the decentralized finance (DeFi) and non-fungible token (NFT) spaces has increased demand on the Ethereum network and escalated transaction fees to record-high levels. The Rainbow Bridge allows users to seamlessly migrate assets to NEAR’s developer-friendly and low-cost platform, circumventing high gas fees without compromising on speed.
Current Ethereum users without a NEAR account can easily onboard to NEAR using the NEAR Faucet for Ethereum users, hosted by Paras, and MetaMask. Simply by logging into MetaMask and proving that their account has a balance higher than 0.05 ETH, anyone can claim a NEAR account and start using the Rainbow Bridge right away.
The industry’s biggest tokens are now on NEAR
The first phase of the Rainbow Bridge opens the gates for assets to flow freely between NEAR and Ethereum blockchains while enabling users to bridge any ERC-20 token now. The following popular tokens with common ERC-20 functionality will now be able to interoperate with NEAR, including but not limited to:
Stablecoins like USDT (Tether), DAI, and TUSD
Wrapped assets like WBTC and WETH
DEX tokens like UNI and 1INCH
Lending tokens like AAVE and COMP
Service company tokens like HT (Huobi) and CRO (Crypto.com)
Users can send these ERC-20 assets directly from MetaMask or other Web3 wallets to NEAR wallets and apps, and vice versa.
Check out the dashboard with bridged assets in almost real time powered by Dune Analytics.
Inside the Rainbow Bridge
The Rainbow Bridge is a trustless, permissionless, and generic protocol for connecting blockchains. The bridge protocol removes the need to trust anyone except the security of the connected chains. Anyone can deploy a new bridge, use an existing bridge, or join the maintenance of an existing bridge without getting approval from anyone else.
The Rainbow Bridge is also generic in that it allows any information that is cryptographically provable on NEAR to be usable in Ethereum contracts and vice versa – including the ability to read the state and schedule calls with callbacks on the other chain. This means, for example, that a user can vote with their ETH balance in a NEAR DAO without sending a transaction on Ethereum.
The nature of the Rainbow Bridge remains fully decentralized and adaptable to any future protocol changes on either side. For more details about the architecture of the Rainbow Bridge, read the technical deep dive here.
How the Rainbow Bridge Works
As with the rest of the development experience on the NEAR platform, the bridge is built to be accessible and easy for all users, thanks to an intuitive design and the ETH Faucet for onboarding directly from MetaMask. (See the demo video to watch the Rainbow Bridge in action.) The cost and speed of using the Rainbow Bridge is mostly dependent on the current costs and speed of using the Ethereum network itself.
Once on NEAR, transactions will confirm in 1-2 seconds and cost under one cent in most cases. Since the Bridge requires transactions on Ethereum for NEAR <> Ethereum, the following costs are expected. Sending assets from Ethereum to NEAR takes about six minutes (20 blocks) and for ERC-20 costs about $10 on average. Sending assets from NEAR back to Ethereum currently takes a maximum of sixteen hours (due to Ethereum finality times) and costs around $60 (due to ETH gas costs and at current ETH price). These costs and speeds will improve in the near future.
The Rainbow Bridge launch marks an important first step in NEAR’s interoperability roadmap. Because the Rainbow Bridge is a generic protocol for communication between smart contract chains, it can be tuned to work with other chains and open up further combination possibilities. Since NEAR offers faster and cheaper transactions, it may be favorable for users of other chains to interact with Ethereum assets on NEAR, rather than bridging directly to Ethereum.
The next major step in NEAR’s interoperability roadmap will be the Ethereum Virtual Machine (EVM), which will launch in Q2 of 2021. EVM support will provide a fully compatible environment for developers to launch existing Ethereum code on NEAR.
Try the Rainbow Bridge Today
Users who bridge to NEAR can use Pulse, a stablecoin-denominated prediction markets platform powered by Flux Protocol; Paras, an NFT trading platform for digital cards; and Ref.Finance, an experimental community-built AMM that allows for swaps between any bridged tokens.
The Rainbow Bridge is available to everyone and does not require special permission to deploy, maintain, or use. To start transferring ERC-20 tokens and experience the high-speed, low-cost advantages of NEAR now…
—
If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR docs to get started. Join the NEAR community via our Discord or Telegram channels and don’t forget to follow us on Twitter.
All product and company names herein may be trademarks of their registered owners.
Disclaimer: This article is provided for informational purposes only. It is not intended to be used as legal, tax, investment, financial, or other advice. |
NEAR’s June Town Hall Highlights: Live from Consensus
COMMUNITY
June 22, 2022
June has been a groundbreaking month for the NEAR ecosystem, with major announcements and platform enhancements coming at breakneck speed. NEAR’s June Town Hall encapsulated much of that excitement. It was also the first-ever live Town Hall from Coindesk’s Consensus conference in Austin, Texas.
NEAR’s June Town Hall was one for special guests and appearances. NEAR co-founder Illia Polosukhin gave a special State of NEAR address, while the foundation introduced a new NEAR CMO. And superstar actress Mila Kunis also joined to discuss the Armored Kingdom fantasy metaverse being built on NEAR.
Here’s everything you need to know about NEAR’s live June Town Hall from Consensus, Austin.
The State of NEAR address
Things kicked off with NEAR co-founder Illia Polosukhin, who shared thoughts on ecosystem progress and where things are likely headed. He noted some exciting milestones, including that NEAR is currently the second fastest-growing Web3 developer ecosystem in the world.
“Over the past 12 months, the protocol had 19 upgrades on the network without skipping a beat,” Polosukhin continued. “The focus of the team has been on stability and performance, making sure that we’re continuously running under any circumstances.”
He went on to share some positive news in the area of developer experience. Thechunk-only producers feature is now complete, and major WASM performance improvements make a JavaScript virtual machine (VM) possible. Illia also confirmed the impending rollout of a JavaScript Software Development Kit (SDK). This feature will make it possible for any JavaScript developer to ship code directly into NEAR.
“With the improvements over the past year, we’ve been able to achieve fully compatible JavaScript running on NEAR with smart contracts,” Polosukhin explained. “This means any JavaScript or web developer can now come in and build on NEAR. This is really exciting because we’ll see lots of experimentation happening.”
Marieke Flament, NEAR Foundation CEO, bookended the State of NEAR address with a deep dive into recent ecosystem successes. Flament noted that in June alone, both the NEAR Balkans Regional Hub NEAR Hacker House launched.
Watch Illia’s and Marieke’s talk here.
NEAR introduces a new Chief Marketing Officer
Next up, NEAR’s new CMO Jack Collier introduced himself to the community. He then provided an overview of some significant announcements coming out of Consensus.
“Over the last four weeks since I joined NEAR, I’ve spent most of my time meeting and listening to people within the ecosystem and beyond, including many people here at Consensus,” Collier said. “What’s really struck me is just how passionate, vibrant and diverse our ecosystem is. I’m hugely excited to be joining the NEAR Foundation and be a part of taking Web3 mainstream.”
Collier then moved on to the three major announcements coming out of Consensus. First, he unveiled Armored Kingdom, a new major entertainment franchise built on NEAR. This immersive science fiction-fantasy world encompasses trading card games, animation, comic books, and film. Armored Kingdom founders include acclaimed artists and producers from the US and India, as well as renowned Hollywood actress Mila Kunis.
Jack alsoannounced that SWEAT recently broke the 10 million wallets created mark—a sign that the movement economy is in full swing on NEAR.
“It’s a huge milestone in bringing Web3 to the masses and reinventing how people can generate value for themselves in a move-to-earn economy,” Collier said.
Finally, Collier announced that the privacy-first browser Brave will be leveraging Aurora to launch its own Brave wallet that will bridge the Ethereum and NEAR communities. This integration will mean that Brave users can buy, sell, and store Aurora tokens directly in their Brave wallet.
“With the new wallet, there will be a host of Web3 functionality supported such as NFTs and swaps,” noted Collier. “All of which will be under the protection of a privacy-preserving, in-browser wallet.”
See Jack’s full talk here.
NEARCon and Other Upcoming Events
Live events in the NEAR ecosystem will continue to ramp up after Consensus. Yadira Blocker, Experiential Marketing and Events Lead at the foundation, joined the Town Hall highlight upcoming events. This includes an even bigger and better NEARCon in Lisbon as well as NEAR’s presence at EthCC, Paris.
“At NEARCon we’ll be doubling in size this year,” Blocker explained. “e’re going to be at a gorgeous waterfront warehouse right across from the Time Out market. We’ll be featuring everything from protocol news, upgrades, updates, and dev technical workshops. We’ve also opened up the call for speakers, so head over nearcon.org and get your application submitted!”
And as for EthCC, Blocker announced that Aurora will be a sponsor at this year’s event. At EthCC, Aurora founder Alex Shevchenko will host a session on one of the stages. The NEAR ecosystem will also host a co-working lounge similar to the one at ETHDenver, but with a Parisian flair. Close to the venue, the lounge will be place for NEARians to work, connect, or simply take a break from EthCC.
Catch Yadira’s full talk here.
Panel with Mila Kunis and the Armored Kingdom team
Perhaps the most thrilling portion of NEAR’s June Town Hall was a live panel with Mila Kunis and the Armored Kingdom creative team. Hosted by tech columnist and metaverse thought leader Cathy Hackl, it included producers Sharad Devarajan, Lisa Sterbakov, and Lindsey McInerney.
Kunis began by explaining that she developed a passion for video and board games early in life. After a successful foray into NFTs, she decided to challenge the gaming industry with Armored Kingdom.
“We want to create IP and a world that has a multi-use to it,” Kunis explained. “The idea behind Armored Kingdom is that it’s based in story, character, and theme. So we’re putting out the comic book, which will serve as the origin story for all of our species and who they are. Then there’s going to be the card gaming element which will be dropping in a couple of months where players can duel each other, followed by armors and toolboxes, and eventually an animated series. We really are building out an amazing multiverse in Armored Kingdom.”
Sharad Devarajan, co-founder and CEO of Liquid Comics, said that when Kunis came to him with the vision behind Armored Kingdom, he immediately jumped at the chance to become involved with the project.
“I think a lot of people are creating stories very linearly. They’ll create a TV show, film, or comic and then license that to other partners,” Devarajan said. “But the goal and mission of this are re-thinking all of the pieces from the ground up.”
“The future of the metaverse is going to be some sort of unique storytelling combination where we take people into worlds,” he added. “And that’s what was so amazing about what Mila shared with me: thinking about things world-first and how the narrative would enhance every part of the gameplay.”
Kunis added that the main reason the team chose NEAR for Armored Kingdom was its accessibility.
“We didn’t want to alienate the normies or for it to feel like it’s an elitist game only for people that understand Web3, crypto, or NFTs,” Kunis explained. “We want this to be a game that a 20-year-old can play just as easily as a 35-year-old stay-at-home mom. And that’s the thing with NEAR—the UI is incredibly easy.”
Sterbakov and McInerney added that NEAR’s commitment to sustainability, long-term vision, and developer-friendly experience contributed to the decision to build on NEAR.
“My dream is to create a world in Armored Kingdom that’s rich, that can be mined from and be built from,” Kunis concluded. “The ultimate plan would be that, hopefully, people in Web3 will join the community and they themselves do things with it. And that’s the beautiful thing about Web3 is that Armored Kingdom can launch itself into other aspects that people can build on top of.”
Watch Mila and the panel here.
Consensus on the ground with David Morrison
Community lead David Morrison took to the floor to gather insights on ecosystem developments, project funding, and education.
“We started in August 2018. The crypto market was going down and continued to go down. And so compared to where we were then, right now is not a bear market. At the same time, I think that any kind of shakeout or correction is good in a way. It allows people to focus on creating sustainable, long-term models and businesses.”
Illia Polosukhin, NEAR co-founder
“As compared with other organizations in Web3, I’ve found that the NEAR foundation is especially bullish on diversity and equity inclusion. Not just as something that you check off a box, but as something that’s really integral to creating a decentralized future.”
Nicole Tay, Funding Strategy and Communications Lead, NEAR Foundation
“I think some of the projects that are really exciting that we’re working on within the NEAR ecosystem, and that we’ve recently supported are Mintbase and some of the projects they’ve been building in the NFT space. Not to mention Paras, a secondary marketplace, which has been exciting.”
Josh Daniels, Head of Funding, NEAR Foundation
“Apart from the great tech that NEAR has, I think the welcoming community plays a huge role in terms of inclusivity. I think it goes to the culture of what NEAR is trying to create, from the Foundation perspective percolating all the way down to communities. NEAR is inspiring a lot of people to play the hand-holding role and be the mentor that you never had in your life.”
Shreyas Kutty, Education Lead, NEAR Foundation |
NEAR Community Update: January 25, 2019
COMMUNITY
January 25, 2019
Everybody approaches blockchain from a slightly different entry point. Some are crypto natives who have ridden these waves before while others are still distracted by the PR disaster of the ICO bubble. Education is one of the most important components of building a great community so we figured the best place to start is by explaining what *we* do at NEAR in plain English. Check it out on our blog.
Beyond education, the other major conversation which has informed our strategy is the one around usability, end-user experience and developer experience. Crossing the next chasm of adoption requires us to build something people actually want and that their users will actually use.
As part of that, we’d like to ask your help: if you’re a developer and/or entrepreneur who is considering developing (or already are developing) on a blockchain, please help us build the platform you actually want by taking the 2-minute Blockchain Developer Survey.
I promise it’s less painful than trying to use a DApp today.
Don’t mess with the EOS hashtag army… ?♂
Community and Events
We’ve always operated under the philosophy that it’s best to ship and iterate. While we haven’t released an official TestNet yet, we’re at the stage where we’re welcoming curated feedback on the platform. We’ll be reaching out to more and more developer communities over the upcoming weeks to test drive the platform and its tooling, including the first (official) external-facing workshop next Tuesday in SF.
In the thread of user experience research, this week we held a workshop on designing onboarding flows for DApps. It resurfaced a number of clear takeaways for protocol design but mostly continued to hammer home how important it is to allow developers to hide tokens and wallets from end-users until later in the user’s journey. That’s music to our ears.
Recent Highlights
[SF] Blockchain 101 Onramp: The Design of Blockchain-Based Apps (DApps) (Video, Slides)
Upcoming Events
[SF] Jan 29: Sneak Peak Workshop: TestNet Test Drive with NEAR Protocol
[Online] Jan 29–30: Decentralized Summit (with Erik Trautman)
[SF] Feb 6: Blockchain 101 Onramp: DApp Development Basics
[Denver] Feb 15–17: Judging the Eth Denver hackathon (with Illia Polosukhin)
[SF] Feb 27: Blockchain 101 Onramp: Best Practices for Developing DApps
Alex presenting on sharding at GraphCon in SF today
Writing and Content
Again, if you’re looking for a plain-English explanation of what we do, check out the aforementioned explainer post.
We’ve continued the “Whiteboard Series with NEAR” in Episode 3: Jun Li from Ontology on our YouTube channel.
Engineering Highlights
We are getting ready to unveil the DevNet, so a lot of clean up & documentation work has been done:
Launched the documentation website, which hosts quick starts, tutorials and API docs for node and JS/Python libraries.
Major improvements to nearlib.js. Deployed it to NPM and CDN.
Putting finishing touches on TxFlow consensus simulation, which we will be releasing together with the paper and blog post next week.
Refactored networking, simplifying the code and reducing the number of external dependencies (e.g. complex rust-libp2p which doesn’t match our requirements).
Added default JSON serialization for structs/classes in smart contracts on the compiler level to AssemblyScript. Continue expanding the standard library.
Created default account creation flow. Built an example in-browser wallet app for DevNet & TestNet.
The first version of block explorer is up to help debug DevNet and in future TestNet.
Keep assembling TestNet: running TxFlow and producing blocks between a fixed set of verifiers.
How You Can Get Involved
If you want to stay up to date with what we’re building at NEAR, follow us on Twitter for updates, join the conversation on Discord.
https://upscri.be/633436/ |
Building New Worlds for Artists with NFTs: Paras + NEAR
COMMUNITY
February 5, 2021
NEAR’s decentralized unrestricted MainNet continues to support a range of projects and decentralized applications across open web use cases. Paras – an NFT trading card marketplace launched in December 2020 – is the latest addition to a user-centric ecosystem of projects building on the NEAR platform.
700+ transactions
70+ artists earning $25K+ in 2 months
80+ collectors
$35K+ trading volume
Empowering Digital NFT Artists on Paras with NEAR
Paras co-founders Rahmat “Riqi” Albariqi and Afiq Shofy started out to create a decentralized social media site. After some months of experiments, they discovered NFTs, or non-fungible tokens—a cryptographic asset where each unit represents something unique and indivisible. Intrigued by the potential for provable digital ownership and sales, they decided to build a platform where digital artists could create and thrive.
To keep up with the pace of innovation in the NFT space, one of the hottest topics in crypto today, Riqi and Afiq knew they had to develop and launch fast. Getting from the first testnet experiments to full MainNet launch took just three months, a testament to NEAR’s seamless developer experience. The pure build time of the application was four weeks, once they understood the basics of how to build on NEAR.
Launched in December 2020, Paras is a digital art card marketplace built on NEAR that offers artists more control of their creations and digital scarcity for collectors—using NEAR as the medium of exchange between creators and collectors. The name Paras (pronounced Pa-RAS) translates to “face” or “persona,” and “equal,” in Bahasa Indonesian. The vision for Paras is to create a space for artists to cultivate and act on compounded momentum.
Marketplace trading cards on Paras.id
Paras’ artists have collectively made more than $25,000 (USD equivalent) already, in just two months since launching the platform. Paras has facilitated a trading volume of $35,000+ from 700+ transactions, with 80+ active collectors and 70+ artists onboarded. Because the minting fees are so low on NEAR, the barrier to entry for digital artists is very low, and an artist can mint a card without thinking about the minting cost. This means they can sell their cards for as low as $1 or $5, lowering the barrier to entry for participation in the marketplace. This opens the NFT world to new artists and collectors alike.
On Paras, Artists Can Sell Art While Creating Complex Worlds
“We are big on collector’s cards and their surrounding worlds—like YuGiOh and Pokémon. We aim to create a framework where artists can do the same in NFT format. On Paras, artists can expand their portfolios and reach new audiences.” –Riqi, Paras co-founder
On Paras, artists mint and sell limited-edition NFT trading card collections – so each NFT is part of an ever-expanding world created by each artist. NFT creators can grow their audience base directly without middlemen, test the market, and expand their collections collaboratively with the Paras community. They are looking for long-term collaborations and sustainable approaches to expanding their digital art businesses. This framework allows artists to hyperfocus on building the colorful stories behind each card’s representation. For example, artist Fetus Squid launched a batch of digital art trading cards to fund the creation of his novel.
Fetus Squid’s collection of Fantasy Trading Cards on Paras.id
Paras does weekly artist invitations, so there are a limited number of artworks issued on the platform at any given time. After an artist is whitelisted, they can start minting right away. 400+ registered wallets are ready to grab the artist’s card collectibles, so they can begin building a collector fanbase by selling at low prices or in multiples and still make a profit—thanks to the very low cost of minting and storage on NEAR. The long-term hope for cultivating artist careers on Paras is that building collections will evolve into creating their own IP universes in the realm of Pokémon or YuGiOh.
For collectors, the 3D, interactive visual representation of the art cards sets Paras apart from other NFT marketplaces. Paras’ eye-catching cards pop on the page and have an undeniably rich style even within the fixed size of the trading card art format. The native format of a Paras digital art card mimics real-world trading cards with a portrait ratio of 64:89—and Paras recently added .gif support alongside .png, .jpg, .jpeg.
Join the Lunar New Year Celebration
Excited to try Paras as an artist or an NFT collector? Starting on February 5, Paras + NEAR are running a Lunar New Year Celebration! Artists can mint a Lunar New Year-themed NFT card collection for the Year of the Ox and collectors who purchase the NFTs get a chance to win NEAR prizes. Follow along on Twitter @NearProtocol and @ParasHQ for more specifics and calls for participation.
If you’re curious about building on NEAR, head over to our developer program and join the conversation on our Discord. Keep up to date on future releases by subscribing to our newsletter for the latest news on NEAR. |
---
id: js-lake-indexer
title: JS basic tutorial
sidebar_label: JS basic tutorial
---
# NEAR Lake indexer basic tutorial
:::info Source code for the tutorial
[`near-examples/near-lake-raw-printer-js`](https://github.com/near-examples/near-lake-raw-printer-js): source code for the tutorial on how to create an indexer that prints block height and number of shards
:::
Recently we have [published a JavaScript version of the NEAR Lake Framework](https://www.npmjs.com/package/near-lake-framework) on npmjs.org
We want to empower you with a basic tutorial on how to use the JavaScript Library. Let's get started!
## Requirements
Before we get started, please, ensure you have:
- [nodejs](https://nodejs.org/en/download/) installed
## Create a project
Create an indexer project:
```bash
mkdir near-lake-raw-printer-js && cd near-lake-raw-printer-js
```
Now we're going to call `npm init`, we can continue with the default values pressing Enter on every question in the interactive mode:
```bash
npm init
```
```
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/near/projects/near-lake-raw-printer-js/package.json:
{
"name": "near-lake-raw-printer-js",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
```
`package.json` is ready. Let's install `near-lake-framework`
## Install dependencies
Install `near-lake-framework`
```bash
npm install near-lake-framework --save
```
Install `typescript` as dev dependency
```bash
npm install typescript --save-dev
```
## Setup TypeScript
Now we can create `tsconfig.json` for TypeScript settings:
```bash
touch tsconfig.json
```
Paste the content to the file:
```json title=tsconfig.json
{
"compilerOptions": {
"lib": [
"ES2018",
"dom"
]
}
}
```
Now let's add the `scripts` section to the `package.json`
```json
"scripts": {
"start": "tsc && node index.js"
}
```
After that your `package.json` should look similar to:
```json title=package.json
{
"name": "near-lake-raw-printer",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "tsc && node index.js"
},
"dependencies": {
"near-lake-framework": "^1.0.1"
},
"devDependencies": {
"typescript": "^4.6.4"
}
}
```
Now let's create `index.ts`
```bash
touch index.ts
```
Open `index.ts` in your favorite editor to start coding.
## Import `near-lake-framework`
In the `index.ts` file let's import the necessary dependencies:
```ts
import { startStream, types } from 'near-lake-framework';
```
We've imported the main function `startStream` which will be called to actually run the indexer, and `types` that hold the `LakeConfig` type we need to contruct.
## Create a config
To get indexer running we need to start it with a config. We need to create an instance of `LakeConfig`
```ts
const lakeConfig: types.LakeConfig = {
s3BucketName: "near-lake-data-mainnet",
s3RegionName: "eu-central-1",
startBlockHeight: 63804051,
};
```
## Create indexer handler
Indexer will be streaming the [`StreamerMessage`](/build/data-infrastructure/lake-data-structures/toc) instances we need to handle according to our needs.
In `near-lake-framework` JS library the handler have to be presented as a callback function. This function have to:
- be asynchronous
- accept an argument of type [`StreamerMessage`](/build/data-infrastructure/lake-data-structures/toc)
- return nothing (`void`)
Creating the callback:
```ts
async function handleStreamerMessage(streamerMessage: types.StreamerMessage): Promise<void> {
//
}
```
For this tutorial our requirement is to log the block height and the numer of shards. That's simple:
```ts
async function handleStreamerMessage(streamerMessage: types.StreamerMessage): Promise<void> {
console.log(`
Block #${streamerMessage.block.header.height}
Shards: ${streamerMessage.shards.length}
`);
}
```
## Starting the stream
And the last thing to write is the call to `startStream` with the config and pass the callback function.
```ts
(async () => {
await startStream(lakeConfig, handleStreamerMessage);
})();
```
That's it. Now we can compile the code and run it
## Compile and run
:::danger Credentials
To be able to access the data from [NEAR Lake](/tools/realtime#near-lake-indexer) you need to provide credentials. Please, see the [Credentials](../running-near-lake/credentials.md) article
:::
We've added the `start` command to the `scripts`, so the compilation and run should as easy as
```bash
npm run start
```
You should see something like the following:
```bash
Block #63804051 Shards: 4
Block #63804052 Shards: 4
Block #63804053 Shards: 4
Block #63804054 Shards: 4
Block #63804055 Shards: 4
Block #63804056 Shards: 4
Block #63804057 Shards: 4
Block #63804058 Shards: 4
Block #63804059 Shards: 4
Block #63804060 Shards: 4
```
You can stop the indexer by pressing CTRL+C
## What's next?
You can play around and change the content of the callback function [`handleStreamerMessage`](#create-indexer-handler) to handle the data differently.
You can find the [source code for this tutorial on the GitHub](https://github.com/near-examples/near-lake-raw-printer-js).
|
NEAR Community Update: March 27th, 2020
COMMUNITY
March 27, 2020
Welcome (back) to NEAR community update,
This month has been a doozy. We have community and contributors from around the world: Havana, Russia, Ukraine, Berlin, NYC, Texas, Montana, Italy, North Carolina, Denver, Spain, Africa, India, etc. Now, more than ever is the time for community and action.
We’ve been meeting every week to share local updates, ideas, and to talk about building solutions to the spillover challenges from the rapid changes we’re experiencing globally. If you want to have a chat, listen, or join the next virtual hang please join our Discord or Telegram and drop us a message.
NEAR Coffee Chat
NEW NEAR example applications
We’re excited to showcase our examples page at https://near.dev. We’ve got a number of simple smart contracts that will boost new developers building projects. Each example demonstrates various capabilities of NEAR from basic NEAR Wallet login to cross-contract calls. These examples are written in Rust and AssemblyScript and tagged by technology and category. We’ll be building more examples and would love to add user-contributed examples as well!
Check-out our example applications
To provide the lowest barrier to entry we’re using Gitpod, a service that spins up a development environment with the example running. The workflow is simple: visit the examples page, select one from the grid and click the “Open in Gitpod” button. You may use the online IDE in Gitpod to alter, build, deploy, and test right in the browser. After trying an example in the Gitpod sandbox, the next natural step is to clone the repository and work locally. Each example has a “Browse on Github” button for that. Happy coding!
ARterra’s simulated sport games
ARterra is a fan engagement platform that elevates engagement by rewarding fans with NFT tokens, coins, and AR gaming rewards. Flux and ARterra have partnered to bring custom markets to esports simulations including Madden and 2K.
Check-out the tweet here!
Engineering Update
We have enhanced the user experience of our CLI tool NEAR shell, which now features a smoother login flow. Just run ‘near login’ as normal and you’ll see how easy it has become. Additionally, we’re upgrading some tooling such that we’ll now require NodeJS version 12. Makes sure to upgrade with ‘npm install near-shell -g’.
The last outstanding feature, namely garbage collection of old states, is undergoing thorough review:
Part of it, responsible for maintaining refcounts on blocks, is already added;
We are working on backward compatibility and migration tests;
Network metrics are recorder here.
Other than that we are full speed stabilizing and fixing issues, e.g:
Addressing the memory leak in the Reed Solomon library we use; and
Fixing tx forwarding on epoch boundaries.
How You Can Get Involved
Join the NEAR Contributor Program. If you would like to host events, create content or provide developer feedback, we would love to hear from you! To learn more about the program and ways to participate, please head over to the website.
If you’re just getting started, learn more in The Beginner’s Guide to NEAR Protocol or read the official White Paper. Stay up to date with what we’re building by following us on Twitter for updates, joining the conversation on Discord and subscribing to our newsletter to receive updates right to your inbox.
|
---
title: Referral Programs
sidebar_label: Referral Programs
sidebar_position: 2
---
# Referral Programs
:::info on this page
* Understanding the importance of referrals
* Setting up a referral program
* Logistics of Program and Parameters
* Bonus Payment Terms
:::
It is never easy to put together the best team for your project. One way to encourage your employees to recruit is to reward them through qualified candidate referrals.
**Details are for Core Contributors**
Decide your criteria for eligibility. Do you want your contractors to benefit from a referral bonus scheme?
Conventionally, the below roles are usually excluded from such bonus schemes.
* Leadership and Executive Team members
* Direct Managers and/or Hiring Managers of their direct open position
* The Recruiting Team
While these groups are not eligible for the referral bonus, they should still be encouraged to refer qualified candidates.
**What referrals (applicants) qualify for bonus eligibility**
Below are some examples of qualifying referrals:
* Anyone that has not applied, been referred to, or worked at your company (or a subsidiary or spinout) for at least a year.
* Allow no cap on the number of referrals an employee can make during their tenure at the company.
**How to refer a candidate**
Consider using a vendor or recruiter to keep track of and assess referrals, but a simple form with a selection of open positions should do.
* Users choose a job from the list for referral. If you think they might be good for several different jobs, simply choose one and write a note to the recruiter outlining the other jobs as well. The recruiter can then assess the referral's information and make sure they end up in the best job or jobs.
**Logistics of Program and Parameters**
* A referral reflects on the employee who is vouching for them. As such, they should be well qualified for the requirements of the position and espouse the Ecosystem Core Values.
* If two or more employees refer to the same candidate, only the first referrer will be eligible to receive a referral bonus.
* When submitting your referral, this is your only opportunity to sell the candidate to the Recruiting Team as to why you think they would be a good fit in the specific position.
* Please do not follow up with the Recruiting Team and/or hiring manager about candidate or process status. You can check "Follow Referral" under the Name & Company section in Greenhouse to receive notifications when/if your referral is moved to a different stage or has their status changed. If you influence the hiring process and/or decision in any way this will immediately exclude you from a referral bonus.
* The referral will be contacted to interview or rejected from the queue within 5 business days.
* The Recruiting Team does not personally contact every referral, so please set the correct expectations with your referral that feedback will come from the Recruiting Team as a whole, via the Greenhouse email system.
**Bonus Payment Terms**
* The referral bonus could be in USD + the equivalent in your company’s tokens, or the entire amount (USD + Tokens) in tokens.
* The referral bonus will be paid out on the next regularly scheduled paycheck following the date of the successful completion of the new hire’s 90-day introductory period.
* The referral bonus is taxable, and all regular payroll taxes will be withheld. Contractors are responsible for paying taxes on the referral bonus.
* The referring employee must be an employee of NEAR (or its subsidiaries) at the end of the referral’s 90-day introductory period to receive the bonus.
* Referrers are still eligible for rewards even if a candidate is hired at a later date (within one year) or gets hired for another position. |
---
id: crosscontract
title: Cross-Contract Calls
---
import {CodeTabs, Language, Github} from '@site/src/components/codetabs'
Cross-contract calls allow your contract to interact with other deployed contracts. This is useful for:
1. Querying information from another contract.
2. Executing a method in another contract.
#### Cross-Contract Calls are **Independent**
The method in which you make the call and the method in which you receive the result are different.
#### Cross-Contract Calls are **Asynchronous**
There is a delay between the call and the callback in which everyone can still interact with your contract.
---
## Snippet: Querying Information
While making your contract, it is likely that you will want to query information from another contract. Below, you can see a basic example in which we query the greeting message from our [Hello NEAR](../quickstart.md) example.
<CodeTabs>
<Language value="js" language="ts">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/src/contract.ts"
start="17" end="39" />
</Language>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/lib.rs"
start="22" end="51" />
<Github fname="external.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/external.rs"
start="2" end="12" />
</Language>
</CodeTabs>
---
## Snippet: Sending Information
Calling another contract passing information is also a common scenario. Bellow you can see a method that interacts with the [Hello NEAR](../quickstart.md) example to change its greeting message.
<CodeTabs>
<Language value="js" language="ts">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/src/contract.ts"
start="41" end="64" />
</Language>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/lib.rs"
start="53" end="80" />
<Github fname="external.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/external.rs"
start="2" end="12" />
</Language>
</CodeTabs>
---
## Promises
Cross-contract calls work by creating two promises in the network:
1. A promise to execute code in the external contract (`Promise.create`).
2. A promise to call back a **different** method in your contract with the result (`Promise.then`).
Both promises take the same arguments:
<CodeTabs>
<Language value="js" language="ts">
```ts
NearPromise.new("external_address").functionCall("method", JSON.stringify(arguments), DEPOSIT, GAS);
```
</Language>
<Language value="rust" language="rust">
```rust
external_trait::ext("external_address")
.with_attached_deposit(DEPOSIT)
.with_static_gas(GAS)
.method(arguments);
```
</Language>
</CodeTabs>
- The address of the contract you want to interact with
- The method that you want to execute
- The (**encoded**) arguments to pass to the method
- The amount of GAS to use (deducted from the **attached Gas**)
- The amount of NEAR to attach (deducted from **your contract’s balance**)
:::tip
Notice that the callback could be made to **any** contract. This means that, if you want, the result could be potentially handled by another contract.
:::
:::caution
The fact that you are creating a Promise means that both the cross-contract call and callback will **not execute immediately**. In fact:
- The cross-contract call will execute 1 or 2 blocks after your method finishes **correctly**.
- The callback will then execute 1 or 2 blocks after the **external** method finishes (**correctly or not**)
:::
---
## Callback Method
If your method finishes correctly, then eventually your callback method will execute. This will happen whether the external contract finishes **successfully or not**. We repeat, if your original method finishes correctly, then your callback will **always execute**.
In the callback method you will have access to the result, which contains two important arguments:
- `status`: Telling if the external method finished successfully or not
- `buffer`: Having the value returned by the external method (if any)
:::tip
The callback methods in your contract must be public, so it can be called when the second promise executes. However, they should be only callable by **your contract**. Always make sure to make it private by asserting that the `predecessor` is `current_account_id`. In rust this can be achieved using the `#[private]` decorator.
:::
### Checking Execution Status
<CodeTabs>
<Language value="js" language="ts">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/src/contract.ts"
start="31" end="38" />
</Language>
<Language value="rust" language="rust">
<Github fname="lib.rs"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/lib.rs"
start="67" end="74" />
</Language>
</CodeTabs>
### Successful Execution
In case the call finishes successfully, the resulting object will have a `status` of 1, and the `buffer` will have the encoded result (if any). In order to recover the result you need to decode it from the resulting `buffer`:
<CodeTabs>
<Language value="js" language="ts">
<Github fname="contract.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-ts/src/contract.ts"
start="31" end="31" />
</Language>
<Language value="rust" language="rust">
<Github fname="lib.ts"
url="https://github.com/near-examples/cross-contract-calls/blob/main/contract-simple-rs/src/lib.rs"
start="47" end="49" />
</Language>
</CodeTabs>
### Failed Execution
If the external method fails (i.e. it panics), then your callback will be **executed anyway**. Here you need to **manually rollback** any changes made in your
contract during the original call. Particularly:
1. If the contract attached NEAR to the call, the funds are sent back to **the contract's account**.
2. If the original method made any state changes (i.e. changed or stored data), they **won't be automatically reverted**.
:::warning
If your original method finishes correctly then the callback executes **even if the external method panics**. Your state will **not** rollback automatically,
and $NEAR will **not** be returned to the signer automatically. Always make sure to check in the callback if the external method failed, and manually rollback any
operation if necessary.
:::
---
## Security Concerns
While writing cross-contract calls there is a significant aspect to keep in mind: all the calls are **independent** and **asynchronous**. In other words:
- The method in which you make the call and method for the callback are **independent**.
- There is a **delay between the call and the callback**, in which people can still interact with the contract
This has important implications on how you should handle the callbacks. Particularly:
1. Make sure you don't leave the contract in a exploitable state between the call and the callback.
2. Manually rollback any changes to the state in the callback if the external call failed.
We have a whole [security section](../security/callbacks.md) dedicated to these specific errors, so please go and check it.
:::warning
Not following these basic security guidelines could expose your contract to exploits. Please check the [security section](../security/callbacks.md), and if still in doubt, [join us in Discord](https://near.chat).
:::
|
---
sidebar_label: "NEAR Data Flow"
---
# NEAR Data Flow
<iframe
width="100%"
height="500"
src="https://www.youtube.com/embed/VSBJ-A69Km4"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
:::info Data flow
In this video we give a quick overview on the main concept of how the data flows across the NEAR Protocol blockchain.
:::
NEAR Protocol blockchain data flow might be a bit tricky at a glance. But it is pretty straightforward and follows well-defined rules. In this article, we are going to have a closer look at how the data flows in NEAR Protocol blockchain.
In fact, any blockchain flow can be represented as an infinity timeline that has a start but has no end.
![Blocks Timeline](/docs/flow/01-timeline.png)
And a block appears on that timeline with some interval. Each of these blocks holds the information about the previous one, thus, creating a *chain of blocks*.
NEAR Protocol has a sharded nature, meaning that more than one parallel network, called a [Shard](../../2.build/6.data-infrastructure/lake-data-structures/shard.mdx), can be live at any moment. And each Shard produces a chunk of a block at a given interval. A Block in NEAR Blockchain is a collection of the block chunks from all shards. Block chunk is shortened to [Chunk](../../2.build/6.data-infrastructure/lake-data-structures/chunk.mdx) in NEAR Protocol documentation.
Returning to the data flow itself. The best we can do is to imagine tracks like we could see in audio/video editing apps. Each Shard has its own set of tracks. The top track is for Chunks. They appear no matter what at a given interval, for NEAR Blockchain the interval is about one second. Chunks are being produced even if nothing is happening on the blockchain.
![Timeline as tracks](/docs/flow/02-tracks.png)
But what do we mean by saying something is happening? We mean that something has triggered some changes in the blockchain. And the most well-known method to trigger any changes is to send a [Transaction](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx) to the blockchain with instructions of what we want to change and who has requested those changes.
A transaction needs to be constructed, signed and sent to the blockchain. Once it is executed we expect to have a result - [ExecutionOutcome](../../2.build/6.data-infrastructure/lake-data-structures/execution_outcome.mdx). Oh, that is simple. But it’s not really accurate for NEAR Blockchain.
![Transaction execution](/docs/flow/03-tx-outcome-receipt.png)
In the beginning there is a [Transaction](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx), it contains instructions we want to be executed on the blockchain. Transaction is sent to NEAR Blockchain.
And yes, it is executed there immediately BUT the immediate result of the transaction execution is always just *an acknowledgement that it will be executed on the chain;* this internal execution request is known as [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx). You can think of the [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx) as an internal transaction that exists to pass information across shards.
Let’s get back to the tracks to look at the example.
Assuming we have two accounts living on different [Shards](../../2.build/6.data-infrastructure/lake-data-structures/shard.mdx) **alice.near** and **bob.near**. **alice.near** creates a [Transaction](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx) to send a few tokens to **bob.near**. The [Transaction](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx) is immediately executed and the [ExecutionOutcome](../../2.build/6.data-infrastructure/lake-data-structures/execution_outcome.mdx) for the [Transaction](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx) is always a [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx).
But this [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx) cannot be executed here, because **bob.near** doesn’t live on the same Shard as **alice.near**, so **the Receipt must be executed on the receiver’s Shard**. So the Receipt is moving to the Shard where **bob.near** belongs to.
On the destination Shard the Receipt is executed and the process is considered as done.
:::info The explanation here is simplified
Please refer to the [Token transfer](token-transfer-flow.md) flow article
:::
So the final scheme will look like:
![Complete scheme of sending tokens from an account from one Shard to an account on another](/docs/flow/04-send-nears-flow.png)
## Summary
We have learnt the main principles of how data is flowing in NEAR Protocol. We have found out that [Transactions](../../2.build/6.data-infrastructure/lake-data-structures/transaction.mdx) execute and the [ExecutionOutcome](../../2.build/6.data-infrastructure/lake-data-structures/execution_outcome.mdx) of the Transaction is always a [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx).
Now we know that [Receipt](../../2.build/6.data-infrastructure/lake-data-structures/receipt.mdx) is a main internal asset for NEAR Protocol blockchain and it has a power of traveling between [Shards](../../2.build/6.data-infrastructure/lake-data-structures/shard.mdx). We learnt the NEAR Data flow on a simple example. Of course in real life with more complex transactions, that involve cross-contract calls, there will be more Receipts and ExecutionOutcomes.
We hope this article is useful and you will be able to build your dApps and indexers easily with the knowledge of how data if flowing in NEAR Protocol.
|
```bash
near call primitives.sputnik-dao.near add_proposal '{"proposal": {"description": "My first proposal", "kind": { "Transfer": {"token_id": "", "receiver_id": "bob.near", "amount": "10000000000000000000000000"}}}}' --deposit 0.1 --gas 300000000000000 --accountId bob.near
``` |
NEAR’s May Town Hall Highlights
COMMUNITY
June 2, 2022
In the NEAR galaxy, May has been a month for creatives, coders, community, and everything in between. NEAR’s May Town Hall was a perfect reflection of those themes, from a record-setting number of NEAR wallets being surpassed to a slew of IRL events like the inaugural Miami Hacker House.
And since May was NFT month, NEAR Foundation CEO Marieke Flament hosted a Town Hall panel going beyond the hype of NFTs. The community also saw one of the first projects from the Terra ecosystem accept the open invitation to migrate over to NEAR.
Here’s everything that went down at the NEAR Town Hall, May edition.
NEAR growth milestones and announcements
May was a groundbreaking month for user growth on the protocol, with NEAR surpassing the 10 million wallets created mark. Flament noted that since the partnership announcement with move-to-earn project Sweatcoin, over 6 million wallets have been created.
“To put things in perspective, Bitcoin has 68 million active wallets, Ethereum 71 million, Solana two million, and Avalanche one million,” Flament commented. “We see this as an important platform to enable active, engaged users and shows phenomenal ecosystem growth over the last few months.”
Flament also pointed out a slew of recent announcements from Aurora, NEAR’s Ethereum Virtual Machine (EVM). In May, Aurora initiated a $90 million developer fund to boost DeFi on the NEAR Protocol. Aurora also launched the Aurora Plus, a new membership platform providing a suite of benefits to developers who join.
Listen to Marieke’s talk here.
NEAR events: Permissionless and Miami Hacker House
Next, May Town Hall attendees were treated to a recap of notable NEAR events that took place throughout the past month. Changwe Mutakasha, a business development consultant for the NEAR Foundation, gave his impressions of NEAR’s presence at the Permissionless conference in Miami, Florida.
“Despite market conditions, the overall mood of the conference was positive with high awareness of NEAR,” Mutakasha recounted. “Many projects approached us organically, including a few that actually confirmed they are moving to NEAR from other L1s.”
NEAR’s presence at Permissionless also included co-founder Illia Polosukhin participating in a DeFi panel with founders from Polygon, Optimism, and Arbitrum. And at the conclusion of the first day of Permissionless, NEAR hosted a happy hour with over 150 attendees and more than 600 on the waiting list. Mutakasha then ceded the floor to ecosystem lead Cameron Dennis, who led the NEAR Hacker House Miami initiative that took place around the same time.
“We had a ton of submissions and people from all over the world traveled to Miami to participate,” Dennis said. “People would not only learn basic stuff, but also dive deeper into certain topics like NEAR accounts, key management, and building subgraphs.”
Overall, there were about 300 people who attended the Hacker House Miami, which included dancing, good food, and even a full-time masseuse. All attendees, speakers, and sponsors will also be admitted into the NEAR Hacker House DAO, to be announced shortly. Dennis pointed out that the Hacker House was critical in allowing the developer community to meet in real life, and that the next one will take place during Consensus in Austin, Texas in June.
Hear Changwe and Cameron’s remarks here.
NFT projects in focus for NEAR Grants
On the education and funding fronts, NFTs were front and center for the May Town Hall. Sharif Abushadi, head of NEAR Education, noted that NEAR Certified Developer certificates will now be shipping in the form of NFTs. He also previewed the latest NFT-focused episode of “TL;DR with Ben” on NEAR University. The series will cover core Web3 and blockchain concepts in plain language.
Abushadi then shared some notable NFT projects that were recipients of NEAR Grants in May. The first was UniqArt, a Music NFT project founded by an entrepreneur in India who’s focusing on engaging artists in that region. Built on NEAR, UniqArt recently onboarded 50 musicians, including a top Punjabi artist. NEAR is also funding the CURA fellowship project to further the generative art ecosystem and community.
Sherif concluded his segment by previewing upcoming fellowships and NFT projects. They included NEARBooks, a proposed marketplace for buying and selling books in NFT format, and NEAR-f-tickets, which will allow people to buy tokenized versions of event tickets. And, of course, the highly anticipated play-to-earn NFT game Burrito Battle, with players fighting mini mules for rewards and bragging rights.
Tune into Sherif’s talk here.
Terra community invitation and Regional Hubs
In light of recent events, the NEAR Foundation decided to initiate a substantial fund and extend an open invitation to all developers, projects, and founders who wish to migrate from Terra over to NEAR. Nicky Chalabi, from the foundation’s ecosystem team, reiterated NEAR’s ongoing commitment to providing resources to the Terra community. She then introduced the founder of a move-to-earn project that has already migrated to NEAR.
The project is called Tracer, and founder Jacob explained that the goal is to build a sustainable move-to-earn experience that doesn’t suffer from the common tokenomics flaws that have plagued other projects in the space.
“We started on Terra and, searching for other migration points, felt that our best option was to go to NEAR,” Jacob said. “So we landed on NEAR and are now trying to build the most playable and sustainable move-to-earn project on Web3 with our composable, 3D NFTs.”
The Town Hall also featured several exciting developments in various NEAR Regional Hubs. The Balkans Regional Hub made its presence felt at the recent BlockSplit conference in Croatia, the biggest Web3 conference in the Balkans to date. Ida Pandur, general manager of the Balkans Regional Hub, added that over 100 people attended NEAR meetups adjacent to BlockSplit.
But perhaps the biggest Regional Hub news in May was the launch of the Kenya Regional Hub. Founded in partnership with the local NEAR Guild Sankore, the new hub is being headed up by Kevin Imani and a four-person team. Imani provided a detailed update on the Regional Hubs activities and strategy in attracting students, conducting pitch competitions, and marketing channels to reach quality blockchain enthusiasts.
Tune into Kevin’s talk here.
Panel on going beyond the hype of NFTs
The Town Hall wrapped up with an NFT panel hosted by Eli Tan from CoinDesk. A diverse array of individuals, creators, and projects gave their take on where NFTs are heading, how NFTs can empower creators, and innovative use cases for NFTs and DAOs.
Clarion North, Tamago
“What excites me about NFTs from the music side of things is the ability to be transparent. It doesn’t matter what Rolling Stone magazine has to say or if the government has an opinion. You can have some form of immutable authentication that everybody in the world can actually hold and accept as value.”
Chloe Lewis, Marma J Foundation
“What I like to do is experiment with AstroDAO and what DAOs can do on NEAR, whether it’s purchasing an NFT or adding a new minter. But the idea is that we have these tools on NEAR to allow people to come in. So when you ask me why am I building on NEAR, it’s the ease of allowing new people to come on board. So as we onboard the next billion people onto NFTs and the blockchain, it can be done in a safe, transparent, and user-friendly way.
Asya Abdrahaman, The Kin DAO
“We started NFTs for Good to launch many homeless and displaced people into income. We started on Open Sea, teaching NFT Bible Study to our communities, and from there we met NEAR Protocol. We felt like it was a nice address to have, and that the NEAR community is very regenerative and cares about the environment. If we’re going to be walking the walk, we should be on a blockchain that’s making similar strides in terms of sustainability.”
Nate Grier, Mintbase
“We’re on NEAR and super excited to be where we’re at. We love Open Sea, but we see it as kind of like the stock market. What we’re trying to build is more of a digital railway system for NFT creators. We’re more interested in the farmer’s markets, with people firing up their own incremental niche markets using our interface or even their own.”
Sophia Adampour, Verse Gallery
“What we’re emphasizing is that blockchain is the only approach to put consumers at the center. So we’re starting out with an NFT gallery and an artist royalty program. And we’re not just reaching out to artists and creators, but to everyone that’s interested in this technology. The Metaverse and NFTs are two super hyped words right now, so having Verse Gallery as a space where the metaverse meets reality is bringing all sorts of new people into art and NFTs.” |
```js
const keypomContract = "v2.keypom.near";
const ftContract = "ft.primitives.near";
const dropAmount = "10000000000000000000000";
Near.call([
{
contractName: keypomContract,
methodName: "create_drop",
args: {
public_keys: state.publicKeys,
deposit_per_use: dropAmount,
ftData: {
contractId: ftContract,
senderId: accountId,
// This balance per use is balance of human readable FTs per use.
amount: "1"
// Alternatively, you could use absoluteAmount, which is dependant on the decimals value of the FT
// ex. if decimals of an ft = 8, then 1 FT token would be absoluteAmount = 100000000
},
},
deposit: "23000000000000000000000", // state.publicKeys.length * dropAmount + 3000000000000000000000,
gas: "100000000000000"
},
]);
``` |
# Source Metadata
## [NEP-330](https://github.com/near/NEPs/blob/master/neps/nep-0330.md)
Version `1.1.0`
## Summary
The contract source metadata is a standard interface that allows auditing and viewing source code for a deployed smart contract. Implementation of this standard is purely optional but is recommended for developers whose contracts are open source.
## Motivation
There is no trivial way of finding the source code or author of a deployed smart contract. Having a standard that outlines how to view the source code of an arbitrary smart contract creates an environment of openness and collaboration.
Additionally, we would like for wallets and dApps to be able to parse this information and determine which methods they are able to call and render UIs that provide that functionality.
The initial discussion can be found [here](https://github.com/near/NEPs/discussions/329).
## Rationale and alternatives
There is a lot of information that can be held about a contract. Ultimately, we wanted to limit it to the least amount fields while still maintaining our goal. This decision was made to not bloat the contracts with unnecessary storage and also to keep the standard simple and understandable.
## Specification
Successful implementations of this standard will introduce a new (`ContractSourceMetadata`) struct that will hold all the necessary information to be queried for. This struct will be kept on the contract level.
The metadata will include two optional fields:
- `version`: a string that references the specific commit hash or version of the code that is currently deployed on-chain. This can be included regardless of whether or not the contract is open-sourced and can also be used for organizational purposes.
- `link`: a string that references the link to the open-source code. This can be anything such as Github or a CID to somewhere on IPFS.
- `standards`: a list of objects (see type definition below) that enumerates the NEPs supported by the contract. If this extension is supported, it is advised to also include NEP-330 version 1.1.0 in the list (`{standard: "nep330", version: "1.1.0"}`).
```ts
type ContractSourceMetadata = {
version: string|null, // optional, commit hash being used for the currently deployed wasm. If the contract is not open-sourced, this could also be a numbering system for internal organization / tracking such as "1.0.0" and "2.1.0".
link: string|null, // optional, link to open source code such as a Github repository or a CID to somewhere on IPFS.
standards: Standard[]|null, // optional, standards and extensions implemented in the currently deployed wasm e.g. [{standard: "nep330", version: "1.1.0"},{standard: "nep141", version: "1.0.0"}].
}
type Standard {
standard: string, // standard name e.g. "nep141"
version: string, // semantic version number of the Standard e.g. "1.0.0"
}
```
In order to view this information, contracts must include a getter which will return the struct.
```ts
function contract_source_metadata(): ContractSourceMetadata {}
```
## Reference Implementation
As an example, say there was an NFT contract deployed on-chain which was currently using the commit hash `39f2d2646f2f60e18ab53337501370dc02a5661c` and had its open source code located at `https://github.com/near-examples/nft-tutorial`. This contract would then include a struct which has the following fields:
```ts
type ContractSourceMetadata = {
version: "39f2d2646f2f60e18ab53337501370dc02a5661c"
link: "https://github.com/near-examples/nft-tutorial",
standards: [
{
standard: "nep330",
version: "1.1.0"
},
{
standard: "nep171",
version: "1.0.0"
},
{
standard: "nep177",
version: "2.0.0"
}
]
}
```
If someone were to call the view function `contract_metadata`, the contract would return:
```bash
{
version: "39f2d2646f2f60e18ab53337501370dc02a5661c"
link: "https://github.com/near-examples/nft-tutorial",
standards: [
{
standard: "nep330",
version: "1.1.0"
},
{
standard: "nep171",
version: "1.0.0"
},
{
standard: "nep177",
version: "2.0.0"
}
]
}
```
An example implementation can be seen below.
```rust
/// Simple Implementation
#[near_bindgen]
pub struct Contract {
pub contract_metadata: ContractSourceMetadata
}
// Standard structure
type Standard {
standard: string, // standard name e.g. "nep141"
version: string // semantic version number of the Standard e.g. "1.0.0"
}
/// Contract metadata structure
pub struct ContractSourceMetadata {
pub version: String,
pub link: String,
pub standards: Vec<Standard>
}
/// Minimum Viable Interface
pub trait ContractSourceMetadataTrait {
fn contract_source_metadata(&self) -> ContractSourceMetadata;
}
/// Implementation of the view function
#[near_bindgen]
impl ContractSourceMetadataTrait for Contract {
fn contract_source_metadata(&self) -> ContractSourceMetadata {
self.contract_source_metadata.get().unwrap()
}
}
```
## Future possibilities
- By having a standard outlining metadata for an arbitrary contract, any information that pertains on a contract level can be added based on the requests of the developer community.
|
---
title: 4.1 What is a Non-Fungible Token (NFT)?
description: Defining and understanding NFTs
---
# 4.1 What is a Non-Fungible Token (NFT)?
_“NFTs are a transportation technology, transaction technology, and ownership technology for intangible assets. **Most of the world-is non-fungible**. A part from financial products, most of the world is non-fungible. The largest asset class in the world is non-fungible. The only fungible things are some forms of money and securities. Are we going to tokenize real world assets? Sure. And most of them are non-fungible. We are going to start with things that are natively digital, NFTs started with collectables, art, and others.” - [A16z Podcast on NFTs](https://web3-with-a16z.simplecast.com/episodes/nfts-use-cases-art-tech-adoption-mainstreaming-kWvgrvhO)._
“_In the physical world, we own items. In fact, the majority of the things we interact with are owned independently. As we migrate into the digital world, why would we not do the same? In other words, digital ownership of unique assets and events, is a logical and necessary next step in the maturation of the internet. Of course we want to own our digital items! Why in the world would we cede that ground to a third party?!” - mk-ultra.near_
Many people are familiar today with non-fungible tokens (NFTs). Usually it has to do with some type of profile picture project (PFP), or a digital community using PFP’s like the Bored Ape Yacht Club.
The Promise of Web3 is a radical overhaul of how value is accrued, managed, directed, and accessed. In conceptualizing NFT’s we are going to be zooming in specifically on the nature of value, and how tokenization of non-fungible value (value that is unique) is positioned to converge smoothly with how ‘digital’ the average person is beginning to live. To start from the very, very basics, we can differentiate fungible value, from non-fungible value.
**Fungible Value / Tokens:** Value that is identical with itself, irrespective of how many parts it is segmented into. Examples of fungible value are tokens and currencies! One NEAR is One NEAR - and it doesn't differentiate the NEAR you have from the NEAR I might have.
**Non-Fungible Value / Tokens:** A tokenized representation of a unique form of value. The non-fungibility of the asset is created by the contract itself. Whether the contract wraps an image, a video, specific data, access to a link, or a ticket that can be redeemed for something - is determined by the creator of the asset. However unlike tokens or currency, each and every non-fungible asset is uniquely identified and inconvertible with one another.
## Why are non-fungible tokens important?
Many people have had a lot of trouble ‘getting’ NFT’s because they are missing the bigger macro trends taking place. Punk6529 outlines his framework for making sense of NFT’s in a manner that is original and extremely accurate for how one can look to leverage this technology for the future:
## Two Frameworks for Understanding NFTs
### Framework 1: NFT’s as a Transportation and Financial Technology for Intangible Assets:
_“NFT’s as a transportation technology, carrier technology, financial technology, and transaction technology for intangible assets. Intangible assets are a gigantic category of societal assets. This means it's a new asset class. The explicit number is $77 trillion dollars of intangible assets on the books. This is larger than most of the global money supply and Gold ($10 trillion). We can use NFT’s to move around any of these intangible assets. Social convention determines the place of the token - if the artist and collectors agree the token represents the piece of art, it is enough. Social convention is all that is needed.”_
The main takeaways from Punk’s description of framework one centers on the notion of existing value, having trouble getting out into a domain whereby it can be traded, leased, or utilized in cohort with other forms of value. There are 77 trillion dollars of intangible assets, none of which can be easily moved around. NFT’s are an emergent technology to move such assets around. What is required to do this, is simply a change in social convention to recognize that the assets represent the rights and abilities put into them. So for example, an Artist and a collector must agree that the ownership of the token in the wallet, gives legal rights to move the piece of art. Or a broadcaster that a clip from a sports match gives ownership to re-monetize online. And so forth. The most important thing about this first framework is that it is a way of ‘opening up’ existing intangible value locked around the world today.
### Framework 2: NFT’s as a New Class of Value, for Hitherto Un-valuable Assets
_“Most of the world is non-fungible. Other than financial products, everything else is non-fungible. Your house is non-fungible. Your office is non-fungible. The largest asset class in the world is real-estate. Your car is not fungible. Nothing is fungible. The only things that are fungible are some forms of money, and some securities. Are we going to tokenize real world assets? Yes and most of them are not going to be fungible tokens.”_
The second framework for making sense of NFT’s is the idea of creating entirely new forms of value, through the tokenization of non-fungible value in the world. According to Punk, this is largely overlooked today by both entrepreneurs and investors: _Most of the world is non-fungible!_ From items like houses and cars, to intangible realities like time and focus. The thesis of the second framework is that as the world becomes more digital - and capable of digitizing representations and facets of the physical world, that non-fungible value is poised to expand drastically as much of our world of value is non-fungible.
With these two frameworks, we can get into the details of the _what_ and _how_ of NFT’s.
## Understanding Non-Fungible Tokens (NFTs): The What and the How.
The unspoken presupposition of the product _non-fungible token_, is that we are taking _something_ of value and we are uniquely tokenizing it as a way of attaching value to it. More specifically, the value attached is a result of scarcity or exclusivity - as a non-fungible token there is a finite amount of whatever _something _we have tokenized. And that scarcity makes it limited. If the underlying _something _is of interest to many people, then it follows that the value of making it digitally scarce is proportionately high.
For a nice conceptual overview we can say the following: The _what _can be any of the following (note these are not mutually exclusive and there will be overlap between the different types):
* **Any form of media or content - from the source.** Art, Music, an Article, a news clip, a highlight reel, etc.
* **A financial instrument or financial position**. A bundle of assets (to create a basket, or loan), a house, a commodity, or a stake on a network that is yielding assets.
* **A future opportunity.** Tickets for an event! A VIP dinner with a celebrity.
* **The promise of a future opportunity.** Becoming eligible to become selected to receive a ticket! Get access to a community that gives away special investor deals.
* **A benefit.** Immediate discount on your next purchase. Special VIP privileges when you attend an event. A free beverage next time you buy something at Starbucks.
* **Proof of participation.** A badge showing you attended this summit, sporting event, or seminar.
* **Proof of behavior or time commitment.** A badge for contributions to a team or project. A representation of how many games you watched. A identifier of in-person attendance to sports events.
* **Past behavior.** A certificate of completion. Recognition of being on a team. Recognition of scoring a goal, or being a scorer of points in a sport. Recognition of having gotten a penalty. Multimedia of your past performance.
* **Future behavior.** A free trip to the Bahamas. Eligibility to play in a D1 event since you passed the drug test. Access to a super-power in a video game. Ability to play as a specific character. Unlock for wearing a real-world item.
* **As a Reference of Ongoing Behavior. With the metadata being updated in the NFT.** The state of your sports career and game to game performance. The revenue and data from a day of sales at a sporting event. Your workout performance in the gym over a season.
* **Proof of accomplishment.** A diploma, award, belt of accomplishment in a martial arts sport, digital ID of your fastest pitch.
* **Access**. Into the locker room. Into the VIP lounge. Into the Media area. Into the special fans club.
* **Rights to use or incorporate.** As a professional player being used in a game for instance - to be able to take a piece of media of yourself and provide rights for others to use in their content or games.
* **Any type of recorded data, from a user or indicative of a user.** Number of times the user has played a game. Number of assets traded. Number of streams watched. Essentially we are taking the user behavior and wrapping it in a token representative of what that behavior has been. This is a more specified version of ‘past behavior’ specifically as it relates to the data of users.
And now we can line up all of these _what’s_, and get into the weeds of _how_ they can be used:
* **Wrap It (Enclose the Value):** My image can be purchased and there is a finite amount of copies. My song can only be listened to, if you own the NFT for it.
* **Imbue Value:** Only with the NFT, are you eligible to lock it up and receive rewards from it.
* **Fractionalize It:** The yield instrument can then be splintered into 1,000 pieces, and individually bought or sold as portions.
* **Earn From It: (Royalties)** My article is re-sold or re-purchased for 10 years, and I earn 2% each time, irrespective of the price it is sold for.
* **Gate / Protect:** You can only read this content, access this video, or comment on this post, with a scarce NFT.
* **Push other Tokens Into It / Provide A Benefit To Something:** Holding the NFT gives you access to certificates, discounts, or other received benefits sent only to NFT holders, based upon prior agreements.
* **Represent or Indicate: (Time Scarce NFTs)** You are given the NFT only after you have done activity X, spent time Y, or succeeded in event A.
Usually at this point, is when the head is spinning, because it is so incredibly mind-boggling that we can wield software to entirely change, identify, and reward behavior.
This, broadly speaking, is the conceptual framework you should have in mind, going forward, as we think about this emerging asset class or product in Web3. And neither the _What_ nor the _How_ is exhaustive! These are open dynamic categories that will evolve with the world in the future.
## Understanding the Long-Term Value Proposition of NFTs
When we step back and look at the roll-out of non-fungible value systems, there are two clear macro trends determining this process:
### 1. Going Digital
Going digital refers to the process by which humans are spending more and more of their time in a digital reality (for example, looking at a screen). The macro trend suggests however, that this experience will broaden to encompass more and more of our lives, while also becoming more immersive and comfortable. As a result, the day to day human experience will be spending more and more time in the digital realm - and as Punk suggests - _we are going to want to have our stuff in that realm!_
_“I am not just a user where I can get kicked out of their database at any point in time. We can be thrown out with zero recourse at any point in time. With NFT’s you don’t have to be guests for digital options…The internet is becoming more immersive and more integrated. And we will be spending more time there. In which case we will want to have our stuff there. Most of that stuff, other than our money, is going to be non-fungible, it is now solved how we should own it.” (16:05)_
Notice the direction of this macro trend that facilitates the long-term value proposition of NFT’s centers on the movement of the human individual from the physical into the digital.
### 2. Expanding From Digital to Physical
Conversely, the second macro trend, centers not on the human being per se, but rather the process by which NFT’s diffuse outwards into the world. This macro trend - similarly taking place with DeFi - begins with natively digital objects (like digital art and collectables), from which it can progressively expand outwards into In-game objects, brands and communities, fashion, and so forth. To paraphrase Punk:
_We will start with things that are natively digital. NFT’s started with collectables, and then they expand from there. In-game objects. Brands and communities. Fashion. More generalized IP, blue-prints, designs - metaverse objects. Physical objects. We are only at the very, very beginning. There is no particular point where this ends._
Opposite from the first trend, the second trend sees the applicability and access to NFT’s diffusing outwards from the digital realm to increasingly sophisticated physical items.
## Conclusion
Taken altogether, the two macro trends would suggest a convergence in the coming decade, from which the user is optimally prepared to handle non-fungible value in a digital environment, and the technology is sufficiently mature and diffused, from which it encompasses an ever-increasing amount of the physical world. This would apply - in line with the frameworks above - to both existing intangible assets, as well as hitherto un-valuable non-fungible items, which can now become tokenized.
|
```js
const accountId = context.accountId ?? props.accountId;
const keypomContract = "v2.keypom.near";
const nftContract = "nft.primitives.near";
const dropAmount = "10000000000000000000000";
Near.call([
{
contractName: keypomContract,
methodName: "create_drop",
args: {
public_keys: state.publicKeys,
deposit_per_use: dropAmount,
nft: {
// Who will be sending the NFTs to the Keypom contract
sender_id: accountId,
// NFT Contract Id that the tokens will come from
contract_id: nftContract,
},
},
deposit: "23000000000000000000000" // state.publicKeys.length * dropAmount + 3000000000000000000000,
gas: "100000000000000",
},
]);
``` |
---
sidebar_position: 6
sidebar_label: "Access keys and login 2/2"
title: "Implementing the login button"
---
import {Github} from "@site/src/components/codetabs"
import loggingIn from '/docs/assets/crosswords/logging-in.png';
import explorerTransfer from '/docs/assets/crosswords/chapter-2-explorer-transfer.jpg';
# Add the login functionality
## Plan
We're going to add a login button that uses `near-api-js` to login with NEAR.
Below is the workflow of logging in:
<img src={loggingIn} alt="Three steps to logging in. 1. click the login button we will build. 2. It creates a private key in the browser local storage. 3. Redirected to NEAR Wallet where you sign, creating a new key"/><br/><br/>
1. User clicks the login button
2. `near-api-js` creates a private key in the browser
3. A redirect to NEAR Wallet occurs, passing the public key. NEAR Wallet (often) has a full-access key capable of the `AddKey` action. The user follows a wizard, ultimately authorizing the creation of a new key.
## Adding the button
In the `src` directory we'll look at:
- `index.js`
- `App.js`
We won't go over every change, but instead point to the new logic.
First we set up a `WalletConnection` object from our JavaScript library:
<Github language="js" start="12" end="20" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/1d64bf29c3376a18c71e5c5a075e29824d7a55f5/src/index.js" />
It's then used in React:
```js
const signIn = () => {
walletConnection.requestSignIn(
nearConfig.contractName,
'', // title. Optional, by the way
'', // successUrl. Optional, by the way
'', // failureUrl. Optional, by the way
);
};
const signOut = () => {
walletConnection.signOut();
…
};
…
return (
<div id="page">
<h1>NEAR Crossword Puzzle</h1>
<div id="crossword-wrapper">
<div id="login">
{ currentUser
? <button onClick={signOut}>Log out</button>
: <button onClick={signIn}>Log in</button>
}
</div>
…
</div>
</div>
);
```
Once logged in, that `WalletConnection` object will be tied to the logged-in user, and they'll use that key to sign transactions and interact with the contract.
:::info Transactions that redirect to NEAR Wallet
In our improved crossword puzzle, the function-call access key for the logged-in user will be signing a transaction to submit their solution.
You may notice, however, that sometimes you'll be redirected to NEAR Wallet, and other times you aren't.
This goes back to an earlier rule we mentioned: function-call access keys cannot send NEAR. They cannot perform the `Transfer` Action.
If a function call requires even 1 yoctoNEAR, NEAR Wallet (or any other wallet containing a full-access key) is required to sign the transaction.
:::
## Call the contract function from JavaScript
The frontend code contains a check to see if the user has completed the crossword puzzle successfully. In there we'll add logic to call the `submit_solution` function on the smart contract.
```js
// Send the 5 NEAR prize to the logged-in winner
let functionCallResult = await walletConnection.account().functionCall({
contractId: nearConfig.contractName,
methodName: 'submit_solution',
args: {solution: seedPhrase, memo: "Yay I won!"},
gas: DEFAULT_FUNCTION_CALL_GAS, // optional param, by the way
attachedDeposit: 0,
walletMeta: '', // optional param, by the way
walletCallbackUrl: '' // optional param, by the way
});
if (functionCallResult && functionCallResult.transaction && functionCallResult.transaction.hash) {
// Display a link the NEAR Explorer
console.log('Transaction hash for explorer', functionCallResult.transaction.hash)
}
```
:::tip try…catch blocks
It's not a bad idea to wrap these type of calls in try…catch blocks to properly handle any errors that come from the blockchain.
These errors can be quite helpful to the developer and the end user.
:::
## Fetch the puzzle, finish up
In the previous chapter, the frontend had a hardcoded file containing information about the clues for a simple crossword puzzle. In this chapter, we've given the coordinates and details about the clues, but the frontend needs to fetch this information.
We're going to modify the logic surrounding our view-only call to `get_unsolved_puzzles` on the contract. This method now returns the clue information, so we've implemented a function that puts it in the proper format for React to construct the crossword puzzle.
This is a tutorial about Rust smart contract development, so we won't focus on the details of this, but know we've added the function `mungeBlockchainCrossword`. This allows us to keep adding custom crossword puzzles and have the frontend be dynamic.
We'll also make other minor changes like adding a page for when there are no puzzles available, and adding a loading screen.
## Run the React app
If you've been following this guide closely, you'll likely just need to start the React app with:
env CONTRACT_NAME=crossword.friend.testnet npm run start
As a helpful reminder, below has the steps necessary to recreate the subaccount, build the contract, deploy the subaccount, and call methods on the contract:
```bash
# Go into the directory containing the Rust smart contract we've been working on
cd contract
# Build (for Windows it's build.bat)
./build.sh
# Create fresh account if you wish, which is good practice
near delete crossword.friend.testnet friend.testnet
near create-account crossword.friend.testnet --masterAccount friend.testnet
# Deploy
near deploy crossword.friend.testnet --wasmFile res/crossword_tutorial_chapter_2.wasm --initFunction new --initArgs '{"owner_id": "crossword.friend.testnet"}'
# Add the crossword puzzle
near call crossword.friend.testnet new_puzzle '{"solution_hash":"d1a5cf9ad1adefe0528f7d31866cf901e665745ff172b96892693769ad284010","answers":[{"num": 1,"start": {"x": 1,"y": 1},"direction": "Down","length": 5,"clue": "NFT market on NEAR that specializes in cards and comics."},{"num": 2,"start": {"x": 0,"y": 2},"direction": "Across","length": 13,"clue": "You can move assets between NEAR and different chains, including Ethereum, by visiting ______.app"},{"num": 3,"start": {"x": 9,"y": 1},"direction": "Down","length": 8,"clue": "NFT market on NEAR with art, physical items, tickets, and more."},{"num": 4,"start": {"x": 3,"y": 8},"direction": "Across","length": 9,"clue": "The smallest denomination of the native token on NEAR."},{"num": 5,"start": {"x": 5,"y": 8},"direction": "Down","length": 3,"clue": "You typically deploy a smart contract with the NEAR ___ tool."}]}' --accountId crossword.friend.testnet
# Return to the project root and start the React app
cd ..
env CONTRACT_NAME=crossword.friend.testnet npm run start
```
## For kicks
For fun, try interacting with the smart contract using the React frontend and the CLI. We can check the status of the puzzle using the CLI, solve the puzzle with the frontend, and check the status again.
Before and after solving the puzzle, run this command:
```bash
near view crossword.friend.testnet get_puzzle_status '{"solution_hash": "d1a5cf9ad1adefe0528f7d31866cf901e665745ff172b96892693769ad284010"}'
```
This will return our enum `PuzzleStatus`. Before solving the puzzle it should print:
```json
'Unsolved'
```
and after:
```json
{ Solved: { memo: 'Yay I won!' } }
```
After you solve the crossword puzzle you'll see a screen with a link to NEAR Explorer to look at the details of the transaction. Notice we have our `Transfer` Action in there:
<figure>
<img src={explorerTransfer} alt="Screenshot from the NEAR Explorer highlighting a place in the transaction where 5 NEAR is sent to mike.testnet"/>
</figure>
<br/>
---
That's it for this chapter! As a reminder the full code is available at:
https://github.com/near-examples/crossword-tutorial-chapter-2
|
---
id: introduction
title: Introduction
---
While developing your smart contract you will want to test that it works as it is supposed to, and moreover, does so securely. In NEAR we have developed tools to help you carry out such tests. Basically, there are two types of tests you can perform:
1. **Unit Tests** to test methods individually. They are written in the contract's language and are executed locally.
2. **Integration Tests** to test how your contract behaves in a realistic environment. You can write them in Rust or Typescript, and execute in a local Sandbox or the NEAR testnet.
We recommend all developers to implement both types of tests, since each is suitable to detect different types of errors and make your code intentional. Furthermore, we strongly recommend to first release all projects on testnet, and give users time to try them before releasing them on mainnet.
---
## Setting Up Testing
Testing a smart contract involves using different pieces of software depending on which type of test you are performing. In order to save you from the trouble of setting them up, we recommend you copy the structure from one of our [example projects](https://github.com/near-examples). |
---
id: near
title: NEAR Protocol
sidebar_label: NEAR Protocol
---
For the beginners, it’s always better to start with [documentation](/concepts/welcome), and NEAR has an excellent one. Here, we only focus on basic concepts which are necessary to understand later chapters, so an entire guideline could be understood without prior NEAR knowledge.
## Accounts & Transactions
NEAR's account system is very powerful and differs substantially from other blockchains, like Bitcoin or Ethereum. Instead of identifying users by their public/private key pairs, it defines accounts as first-class entities. This has a few important implications:
- Instead of public keys, users can use readable account names.
- Multiple key pairs with [different permissions](../protocol/access-keys.md) can be used. This provides a better security model for users, since loss of one key pair doesn’t compromise an entire account and has a quite limited impact.
- Hierarchical accounts structure is supported. This is useful if we want to manage multiple smart contracts under one parent account.
- Accounts/public keys are created using transactions, since they are stored on the blockchain.
More information on NEAR accounts can be [found in the docs](../protocol/account-model.md).
But an account by itself won’t get us anywhere, its [transactions](../protocol/transactions.md) that make things happen. In NEAR, we have only one transaction type, but the transaction itself may have different actions included. For most practical purposes, transactions will have a single action included, so for simplicity we’ll use “action” and “transaction” terms interchangeably further down the road. Each transaction always has sender and receiver accounts (and it is cryptographically signed by the sender’s key). The following transaction (action) types are supported:
- CreateAccount/DeleteAccount, AddKey/DeleteKey - accounts and key management transactions.
- Transfer - send NEAR tokens from one account to another. The basic command of any blockchain.
- Stake - needed to become a validator in a Proof-of-Stake blockchain network. We won’t touch this topic in this guideline, more information [can be found here](https://near-nodes.io/validator/staking-and-delegation).
- DeployContract - deploy a smart contract to a given account. An important thing to remember - one account can hold only one contract, so the contract is uniquely identified by the account name. If we issue this transaction to an account which already has a deployed contract, a contract update will be triggered.
- FunctionCall - the most important action on the blockchain, it allows us to call a function of a smart contract.
Smart Contracts on NEAR are written in Rust or JavaScript, and compiled into [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly). Each contract has one or more methods that can be called via a FunctionCall transaction. Methods may have arguments provided, so each smart contract call includes the following payload: account id, method name, and arguments.
There are 2 ways to call a method on a smart contract:
1. Issue a FunctionCall transaction. This will create a new transaction on a blockchain which may modify a contract state.
2. Make a smart contract view call. NEAR blockchain [RPC nodes](https://near-nodes.io/intro/node-types#rpc-node) provide a special API that allow execution of methods that do not modify contract state (readonly methods).
The second method should always be used whenever possible since it doesn’t incur any transaction cost (of course, there is some cost of running a node, but it’s still much cheaper than a transaction; public nodes are available which can be used free of charge). Also, since there’s no transactions, we don’t need an account to make a view call, which is quite useful for building client-side applications
## Gas and Storage
As we already discussed, users should pay computational costs for each transaction. This cost is called “gas” and is measured in [gas units](../protocol/gas.md) (this is an established term in the blockchain world). Each time a transaction is posted, an amount of gas is attached to it to cover the cost. For simple transactions, gas can be calculated ahead of time to attach an exact amount. For FunctionCall transactions, however, exact cost is impossible to automatically calculate beforehand, so the usual approach is to attach a large enough amount of gas to cover the cost, and any excess will get automatically refunded.
![image](/docs/assets/web3/web3-7.png)
But why do we need separate gas units, why not just pay directly with NEAR tokens? It’s necessary to accommodate for changing infrastructure costs - as the network evolves over time, cost of gas units may change, but the amount of gas required for a transaction will remain constant.
However, computational cost is not everything - most smart contracts also need storage. The storage cost in NEAR is quite different from gas.
First of all, it’s not cheap - while gas is very cheap and its cost will be almost unnoticeable by the users, storage is very expensive. As a consequence, the storage budget should be carefully calculated and only necessary data stored on the blockchain. Any auxiliary data (that is not necessary to the contract operations) should be stored off-chain (possible solutions will be covered in later chapters).
The second important difference - storage is not bought, but leased (in NEAR, it’s called staking). When a smart contract wants to store some data, storage cost is computed and the appropriate amount of NEAR tokens is “locked” on the account. When data is removed, tokens are unlocked. And unlike gas, these tokens are locked on the smart contract’s account, so the user doesn’t directly pay for it.
But what if we want users to pay for the storage (or just pay some fee for using a smart contract)? So far, the only way we’ve seen to transfer a token is a Transfer transaction. It turns out, a FunctionCall transaction also allows us to transfer tokens alongside the call (this is called a deposit). Smart Contracts can verify that an appropriate amount of tokens has been attached, and refuse to perform any actions if there’s not enough (and refund any excess of tokens attached).
In combination, gas fee and deposit attachments enable creation of contracts that need zero cost from developers to support and can live on blockchain forever. Even more, 30% of gas fees spent on the contract execution will go to a contract’s account itself (read more [here](https://near.org/blog/near-protocol-economics/#:~:text=a%20new%20entity.-,Contract%20rewards,-As%20one%20of)), so just by being used it will bring some income. To be fair, due to the cheap gas cost this will make a significant impact only for most popular and often-called contracts, but it’s nice to have such an option nonetheless.
One last gotcha about storage - remember that smart contracts themselves are also just a code stored on a blockchain, so a DeployContract transaction will also incur storage fees. Since smart contracts code can be quite big, it’s important to optimize their size. A few tips on this:
- Don’t build Rust code on Windows, it produces quite big output. Use WSL or build on other OSes.
- Optimize smart contracts code for size - [more info here](/sdk/rust/contract-size).
More details on the storage model can be [found in the docs](../storage/storage-staking.md).
## Clients Integration
So far, we’ve discussed how to call smart contracts in a client-agnostic way. However, in the real world, calls we’ll be performed from a client side - like web, mobile or a desktop application.
As we’ve learned from previous chapters, each transaction should be signed using a key. And since keys are managed by a wallet, each application should integrate with it. At the time of this writing, there’s only one officially supported [NEAR Wallet](https://wallet.near.org/). It is a web application, so integration happens using HTTP redirects. This is relatively straightforward to do in web applications (JavaScript SDK is available), but for mobile or desktop applications it may require deep linking or other more advanced approaches.
The general flow for transactions signing looks like this:
![image](/docs/assets/web3/web3-9.png)
Each time we want to post a transaction, the client redirects the user to a wallet, where the transaction is approved and wallet returns a signed transaction back to the client (via redirect). This is a quite secure way of signing, since the private key is not exposed to the client, but constant redirects might quickly get annoying for users, especially if we just want to call smart contract functions that incur only small gas fees. That’s why NEAR introduced [two types of access keys](../../1.concepts/protocol/access-keys.md) - full keys and functional call keys. Full access keys, as the name implies, can be used to sign any types of transactions. Functional call keys, on the other hand, aim to solve this UX problem. They are tied to a specific contract, and have a budget for gas fees. Such a key can’t be used to sign transactions that transfers NEAR tokens (payable transactions), and can only be used to cover gas fees, that’s why it’s not so security-critical and can be stored on the client. Because of this, we can create a simplified signing flow for non-payable transactions. First of all, a login flow to obtain a Functional Call key is used.
![image](/docs/assets/web3/web3-10.png)
The client generates a new key pair and asks a wallet to add it as a functional call key for a given contract. After this, a login session is established and considered alive until the client has the generated key pair.
To provide the best user experience usage of both keys is combined - type of signing is determined based on a transaction type (payable or non-payable). In case of a payable transaction, flow with wallet redirection is used, otherwise simplified local signing flow (using a stored function call key) is applied:
<div align="center">
<img src="/docs/assets/web3/web3-11.png" alt="image" width="300" />
</div>
It’s important to note that it’s possible to generate a Full Access key using the same key addition flow as for the Functional Call key, but this is very dangerous since compromise of such key will give full control over an account. Applications that want to work with Full Key directly should be designed with extreme care, especially in the matters of security.
## Cross-contracts calls
Throughout this section, we’ve discussed how to call a smart contract from a client. But a single smart contract can only take us so far. The true power is achieved when smart contracts are working in concert and communicating with each other. To achieve this, NEAR provides cross-contract calls functionality, which allows one contract to call methods from another contract. The general flow looks like this:
![image](/docs/assets/web3/web3-12.png)
Looks simple enough, but there are few gotchas:
- In order to provide a call status (success or failure) and a return value to the calling contract, a callback method should be called, so there’s no single activation of ContractA. Instead, an entry method is called first by the user, and then a callback is invoked in response to cross-contract call completion.
- Transaction status is determined by the success or failure of a first function call. For example, if a ContractB.methodB or ContractA.methodACb call fails, the transaction will still be considered successful. This means that to ensure proper rollbacks in case of expected failures, custom rollback code must be written in the ContractA.methodACb, and the callback method itself must not fail at all. Otherwise, smart contract state might be left inconsistent.
- Cross-contract calls must have gas attached by the calling contract. Total available gas is attached to a transaction by a calling user, and distributed inside the call chain by contracts. For example, if 15TGas are attached by the user, ContractA may reserve 5TGas for itself and pass the rest to ContractB. All unspent gas will be refunded back to the user.
![image](/docs/assets/web3/web3-13.png)
- NEAR tokens can also be attached to cross contract calls, but they work differently from the gas. Attached deposit is taken directly from the predecessor account. It means even if a user hasn’t attached any deposit, a contract still can attach tokens, which will be taken from its account. Also, since cross-contract call failure doesn’t mean transaction failure, there are no automatic refunds. All refunds should be done explicitly in the rollback code.
![image](/docs/assets/web3/web3-14.png)
A few notes on failure modes - since smart contracts run on a decentralized environment, which means they are executed on multiple machines and there is no single point of failure, they won’t fail because of environment issues (e.g. because a machine suddenly lost power or network connectivity). The only possible failures come from the code itself, so they can be predicted and proper failover code added.
In general, cross-contract call graphs can be quite complex (one contract may call multiple contracts and even perform some conditional calls selection). The only limiting factor is the amount of gas attached, and there is a hard cap defined by the network of how many gas transactions may have (this is necessary to prevent any kind of DoS attacks on the Network and keep contracts complexity within reasonable bounds).
## Data Structures, Indexers and Events
We’ve already discussed the storage model on NEAR, but only in abstract terms, without bringing the exact structure, so it’s time to dive a bit deeper.
Natively, NEAR smart contracts store data as key-value pairs. This is quite limiting, since even simplest applications usually need more advanced data structures. To help in development, NEAR provides [SDK for smart contracts](https://github.com/near/near-sdk-rs), which includes data structures like [vectors, sets and maps](../../1.concepts/storage/data-collections.md#rust-collection-types-rust-collection-types). While they are very useful, it’s important to remember a few things about them:
- Ultimately, they are stored as binary values, which means it takes some gas to serialize and deserialize them. Also, different operations cost different amounts of gas ([complexity table](../../1.concepts/storage/data-collections.md#big-o-notation-big-o-notation-1)). Because of this, careful choice of data structures is very important. Moving to a different data structure later will not be easy and would probably require data migration.
- While very useful, vectors, maps and sets won’t match the flexibility and power of classical relational databases. Even implementations of simple filtering and searching might be quite complex and require a lot of gas to execute, especially if multiple entities with relations between them are involved.
- They are limited to a single contract. If data from multiple contracts is required, aggregation should be performed using cross-contract calls or on a client side, which is quite expensive in terms of gas and time.
To support more complex data retrieval scenarios, smart contract data should be put in a more appropriate store, like a relational database. [Indexers](../../4.tools/indexer4explorer.md) are used to achieve this. In a nutshell, indexer is just a special kind of blockchain node that processes incoming transactions and puts relevant data into a database. Collected data can be exposed to a client using a simple API server (e.g. REST or GraphQL).
![image](/docs/assets/web3/web3-15.png)
In order to simplify creation of indexers, [NEAR Indexer Framework](/concepts/advanced/near-indexer-framework) has been created. However, even with a framework available, extracting data from a transaction may not be an easy task, since each smart contract has its unique structure and data storage model. To simplify this process, smart contracts can write structured information about outcome into the logs (e.g. in the JSON format). Each smart contract can use its own format for such logs, but the general format has been standardized as [Events](https://nomicon.io/Standards/EventsFormat).
Such architecture is very similar to Event Sourcing, where blockchain stores events (transactions), and they are materialized to a relational database using an indexer. This means the same drawbacks also apply. For instance, a client should be designed to accommodate indexing delay, which may take a few seconds.
As an alternative to building your own indexer with a database and an API server, [The Graph](https://thegraph.com/en/) can be used instead, which currently has [NEAR support in beta](https://thegraph.com/docs/en/supported-networks/near/). It works using the Indexer-as-a-Service model, and even has decentralized indexing implementation.
## Development tools
By now, we should be familiar with necessary concepts to start developing WEB 3.0 applications, so let’s explore the development tools available.
First of all, we need a development and testing environment. Of course, we could theoraticaly perform development and testing on the main blockchain network, but this would not be cheap. For this reason, NEAR provides [several networks](../../1.concepts/basics/networks.md) that can be used during development:
- testnet - public NEAR network which is identical to mainnet and can be used for free.
- localnet - you can deploy your personal NEAR network on your own environment. Because it’s owned by you, data and code can be kept private during development. More info on how you can run your own node can be [found here](https://near-nodes.io/validator/running-a-node). Alternatively, you can bootstrap an entire testing infrastructure in Docker on your local machine using Kurtosis - [guide is here](../../2.build/2.smart-contracts/testing/kurtosis-localnet.md).
- workspaces - you can start your own local network to perform e2e testing. More info [here](../../2.build/2.smart-contracts/testing/integration-test.md).
Once we’ve chosen a network to use, we need a way to interact with it. Of course, transactions can be constructed manually and posted into [node’s API](/api/rpc/setup). But [this is tedious](https://github.com/near-examples/transaction-examples) and isn’t fun at all. That’s why, NEAR [provides a CLI](../../4.tools/cli.md) which automates all of the necessary actions. It can be used locally for development purposes or on build machines for CI/CD scenarios.
In order to manage accounts on the NEAR network, [Wallet](https://wiki.near.org/overview/tokenomics/creating-a-near-wallet) can be used. It can show an effective account balance and active keys.
![image](/docs/assets/web3/web3-16.png)
On the image above, “Reserved for storage” are tokens locked by a smart contract to cover current storage requirements, and “Reserved for transactions” represents the amount of tokens locked to cover gas cost by Functional Call keys.
Currently, there’s no UI to connect sub-accounts into a wallet. Instead, they should be imported via a specially constructed direct link:
```
https://testnet.mynearwallet.com/auto-import-secret-key#YOUR_ACCOUNT_ID/YOUR_PRIVATE_KEY
```
(you should provide a private key of a full access key for the account in question, so make sure this link is used securely).
Last, but not least, blockchain transactions can be viewed using NEAR Explorer. It provides insights into transaction execution and outcome. Let’s look at [one example](https://testnet.nearblocks.io/txns/ABh4zQ5aZ3CGhpQzstL16TAB8TvqPbiirJG1uTPJVxTt).
First of all, we can see general transaction information - sender, receiver, status. After this, we can see gas usage information:
- Attached gas - total gas provided for the transaction.
- Gas used - actual gas spend.
- Transaction fee - gas used multiplied to current gas price, shows an actual cost of a transaction in NEAR tokens.
Also, Deposit Value shows the amount of NEAR tokens transferred from sender to receiver.
![image](/docs/assets/web3/web3-17.png)
Below this, we can inspect transaction actions (recall, that transactions may have multiple actions). In this case, we have a single FunctionCall action with arguments:
![image](/docs/assets/web3/web3-18.png)
At the end, transaction execution details, including token transfers, logs, cross-contract calls and gas refunds are provided. One thing that we haven’t covered yet is shown here - [receipts](../protocol/transactions.md#receipt-receipt). For most practical purposes they are just a transaction implementation detail. They are quite useful in a transaction explorer to understand how a transaction was executed, but aren’t really relevant outside of it.
![image](/docs/assets/web3/web3-19.png)
## Contract upgrades
During the development, and sometimes even in production, updates to a contract’s code (or even data) are needed. That’s why different contract upgrades mechanisms have been created.
While developing the contract, we recommend just creating a new account each time you need to deploy a contract (the [create-account](../../4.tools/cli.md#near-create-account) command in NEAR CLI exists for this). With such an approach, you will start with a clean state each time.
However, once we move to a more stable environment, like testing or production, more sophisticated methods are needed. Redeployment of code is quite simple: we just issue another `DeployContract` transaction, and NEAR will handle the rest. The biggest challenge is to migrate contract state - [several approaches are possible](../../2.build/2.smart-contracts/release/upgrade.md#migrating-the-state), but all of them involve some kind of migration code.
But we can take our upgrade strategy one step further. In the previous strategies, developers are fully in control of code upgrades. This is fine for many applications, but it requires some level of trust between users and developers, since malicious changes could be made at any moment and without the user’s consent (as it [sometimes happens](https://www.bleepingcomputer.com/news/security/dev-corrupts-npm-libs-colors-and-faker-breaking-thousands-of-apps/) in npm world). To solve this, a contract update process itself can also be decentralized - this is called [Programmatic Updates](../../2.build/2.smart-contracts/release/upgrade.md#programmatic-update). The exact strategy may vary, but the basic idea is that the contract update code is implemented in a smart contract itself, and a Full Access key to the contract account is removed from a blockchain (via DeleteKey transaction). In this way, an update strategy is transparent to everyone and cannot be changed by developers at will.
## Further reading
For a deep dive into NEAR, the following links will be useful:
- [NEAR docs](https://docs.near.org)
- [Rust Smart Contract docs](/sdk/rust/introduction)
- [Smart Contract quick start guide](../../2.build/2.smart-contracts/quickstart.md)
- [NEAR Protocol Specification](https://nomicon.io/)
- [How to build a dApp on NEAR](../../3.tutorials/examples/guest-book.md)
|
# Scenarios
In the following sections we go over the common scenarios that runtime takes care of.
- [Financial Transaction](FinancialTransaction.md)
- [Cross-Contract Call](CrossContractCall.md)
|
NEAR Enhances Decentralization with Validator Upgrade
DEVELOPERS
January 7, 2022
Since the NEAR Mainnet launch in October 2020, the network has seen a steady increase in the number of validators, with many more wanting to participate. Nevertheless, the extremely high threshold of 3.6M $NEAR has made it challenging for new validators to join the network. So much so, the NEAR Foundation has, at times, supported validators with substantial delegations in order to allow for some of the 60 validators to remain active on Mainnet.
That is why, in December 2021, the NEAR Protocol team released the updated validator selection algorithm. The new selection algorithm now allows for up to 100 validator nodes on the Mainnet, and reduces the validators’ barrier to entry by bringing down the seat price from 3.6 million $NEAR to 67,000. This lowered seat price makes it easier for them to join the active validator set and to maintain their seats.
Additionally, the NEAR Foundation aims to limit delegation amounts to a maximum of 100,000 NEAR per validator, as part of its continuous commitment to building a fully decentralized network.
NEAR Delegation Role
Historically, the NEAR Foundation has used delegation to bootstrap network decentralization by helping new validators enter the active set and build their following but it wasn’t intended to be a long term grant. Current validators on NEAR Mainnet who had received historical delegation from NEAR Foundation should expect to see current delegations from NEAR Foundation to be withdrawn in the next 48 hours as part of this change.
This will be followed by the NEAR Foundation delegating up to 100,000 NEAR to validators who had been selected to receive delegation by submitting their delegation application up to December 13, 2021. This new wave of delegation will take place during the coming weeks.
This change is only the beginning of a number of ecosystem-wide initiatives that will continue increasing the number of validators and improving network decentralization. With the upcoming launch of phase 1 of sharding in early 2022, we expect another 200 validators to join Mainnet.
NEAR has always been, and will always be committed to building a secure, scalable, and decentralized network to help onboard the world into Web3. To take advantage of the upcoming expansion, there are other opportunities for NEAR Foundation delegation, including participating in the validator governance progress.
Please consider joining the NEAR Validator governance process by participating in the NEAR Validator Advisory Board general election in early 2022. Stay tuned for more announcements. |
```js
import { Wallet } from './near-wallet';
const TOKEN_CONTRACT_ADDRESS = "token.v2.ref-finance.near";
const wallet = new Wallet({ createAccessKeyFor: TOKEN_CONTRACT_ADDRESS });
await wallet.viewMethod({
method: 'ft_metadata',
args: {},
contractId: TOKEN_CONTRACT_ADDRESS
});
```
<details>
<summary>Example response</summary>
<p>
```json
{
"spec": "ft-1.0.0",
"name": "Ref Finance Token",
"symbol": "REF",
"icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A",
"reference": null,
"reference_hash": null,
"decimals": 18
}
```
</p>
</details>
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |
NEAR Foundation Transparency Report: Q1 2023
NEAR FOUNDATION
April 6, 2023
Hello, NEAR World! Welcome to NEAR Foundation’s newly reformatted “Transparency Report”. Published quarterly, NEAR Foundation’s Transparency Report explores the NEAR Foundation’s progress towards its OKRs, as well as the latest technology news and updates from the NEAR ecosystem.
NEAR Foundation is kicking off the new Transparency Report with the Q1 edition. It features a NEAR Foundation Treasury report and a variety of exciting updates on the recently announced Blockchain Operating System (BOS), the NEAR ecosystem’s thriving projects, and NEAR Foundation’s Web2.5 strategy. You’ll get the latest on NEAR Horizon Accelerator, NDC, NEAR’s Web2 → Web3 partnerships, and more.
NEAR Foundation Treasury Update
At the end of Q1 2023, NEAR Foundation’s treasury totalled $1.1b, including $365m fiat reserves and 316m NEAR ($630m at a closing price of $1.99).
The NEAR Foundation has continued to adopt a highly responsible approach to treasury management in order to minimize the risk of loss in a turbulent market. Exposure to non-NEAR assets therefore has been limited, with fiat reserves held in AAA-rated Swiss bank accounts.
Q1 has been a turbulent quarter for the US banking sector. However, the NEAR Foundation treasury’s proactive risk management policies — including limited exposure to Silicon Valley Bank (under FDIC insurance levels) and no exposure to Credit Suisse — have prevented any loss of funds. NEAR Foundation’s risk management strategy helps ensure that the NEAR Foundation maintains sufficient resources and runway even if the market downturn lasts for multiple years.
As a result, the NEAR Foundation is in an extremely strong position to continue to support the ongoing growth and development of the NEAR protocol and ecosystem .
A recap of NEAR’s go-forward strategy
Despite well-known issues with Web2 platforms and legacy institutions, and the significant progress made in the blockchain industry, Web3 has yet to fully deliver on its promise to open the web. The Web3 of today is held back by inaccessible user experiences, siloed apps that are difficult to discover and explore, few real-world use cases, and technology tribalism. While there is a lot of hype in Web3, there just isn’t enough value for users.
This is why the NEAR Foundation is focusing on making the most of NEAR protocol’s fundamentals and convictions. The NEAR protocol has the best tech in Web3, world-class talent, and an ample runway. The NEAR protocol also has the ability to achieve mainstream adoption through a focus on users, rather than cultish maximalism or hype, and the understanding that converting strong Web2 projects to Web3 will get the NEAR ecosystem there.
With NEAR’s recent launch of the Blockchain Operating System, this next phase of adoption is already underway. The BOS makes it easier than ever for Web2 apps and communities to take advantage of Web3’s opportunities while giving developers and end users a richer, more sustainable experience.
In 2023, NEAR Foundation is focused on two different approaches to bringing more users to the NEAR protocol and the BOS. It begins with the NEAR Foundation’s top-down approach to partnerships, led by a world-class business development team. By working with major applications and brands with substantial, established communities, the NEAR Foundation is partnering on real use cases that drive engagement on the NEAR protocol, like ticketing and earning. High-traction focus verticals for these partnerships include sports, entertainment, and loyalty. Major partnerships in recent months include Grupo Nutresa, Google Cloud, and Sweat Economy.
Q1 has also seen NEAR Foundation’s bottom-up, grassroots approach. This is designed to empower the NEAR ecosystem to invest in its own expansion through grants, primarily through 3 major community DAOs: Developer DAO, Marketing DAO, and Creatives DAO (visit the DAO websites to get involved). These grassroots DAOs will be supported by the NDC, which has launched several working groups in Q1. This quarter has also seen the launch of NEAR Horizon, an early-stage accelerator that will provide support across education, tech, hiring, legal, UX, and GTM guidance, to promising projects and founders on NEAR.
With the launch of the NDC, the DAOs, and the accelerator, NEAR Foundation will focus less on the allocation of capital directly to projects. Instead, the NEAR Foundation will support the community in making these decisions and further decentralizing key elements of the ecosystem. Also, Proximity supports projects building DeFi applications on the NEAR protocol through grants, advisory services, and developer support.
Q1 Ecosystem OKR performance
Throughout Q1, NEAR Foundation experienced several areas of growth toward our OKRs. While the NEAR Foundation met many of its goals, there is always work to be done.
There is a lot of green. However, as an ecosystem we missed our North Star. NEAR Foundation’s goal was 2M MAAs but we came in short, just under 1M. There are a couple of key reasons for this, as well as a path forward to improve performance next quarter.
SWEAT (which still represents the majority of MAA) is revisiting their MAA ramp up. Current expectations are that MAA growth will occur mostly in the second half of the year, with the US app launching in September.
NEAR Foundation’s BD team has been closing great deals (23 in Q1 alone) — most announcements haven’t been made (6 only) and most launches will be towards the end of the year.
NEAR Foundation has built a new model to better forecast and set MAA expectations. With this new model, the NEAR Foundation is expecting just over 1.5M MAAs in Q2 of this year with a path to 10M by the end of 2023.
Outside of MAAs, the NEAR ecosystem had a successful quarter with several areas of strength.
Crystalized strategy around the BOS with new branding + alpha.nearpages.wpengine.com launched in Denver (6K+ accounts).
Growth of Twitter followers far outpacing others in Web3 (175K per month vs. flat growth from others).
NDC Trust launched and grassroots DAOs starting to become fully independent and operational.
NEAR Horizon went from ideation to MVP with pre-cohort launch and partners signed up for full launch.
Despite macro conditions, the NEAR Foundation continues to manage its treasury effectively and NEAR ecosystem–based projects continue to raise external capital (Open Forest Protocol, Few and Far, Calimero). The Backer / VC Network data infrastructure was also revamped.
Lots of exciting BD deals closed, setting the stage for a strong end of year when they go live.
The Data / Analytics team was formed to operationalize KPIs and better track and understand what’s going on in the ecosystem.
Q1 saw a consistent increase in total new accounts with 1.5m new accounts, as well as a consistent increase in total new contracts, seeing 3,800 new contracts on the NEAR protocol. Q1 also saw 25m transactions on the NEAR protocol.
NEAR Foundation is currently working on a suite of real-time dashboards so the ecosystem can have visibility into the progress against our OKRs. You can find this at NEARAtlas.com.
OKR1: NEAR is the BOS
At ETHDenver, it was announced that the NEAR protocol announced that it is becoming the Blockchain Operating System — a common layer for discovering and creating Open Web experiences, across all blockchains. As part of that announcement, NEAR protocol launched Alpha.nearpages.wpengine.com, a composable frontend for Web3 allowing end users to easily and frictionlessly discover all of Web3’s possibilities in one seamless experience. It also enables developers to create and code interfaces in a single environment with the ability to fork a host of components to build apps faster, and more efficiently than ever before.
The BOS announcement generated a lot of excitement, inspiring Pantera Capital’s Franklin Bi to tweet, “Decentralized frontends are the future.”
Quoting Illia’s announcement tweet, Redpoint’s Managing Director Jason Warner said: “Something I actually think is interesting is what Illia and crew are doing with NEAR and what they are calling the open web. It’s an experiment worth running for sure starting with Near.Social.”
“We need innovation at every level of the stack, not just the core protocol and smart contract layers,” tweeted Ali Yahya, General Partner at a16z crypto. “NEAR is leading the way.”
Since launching alpha.nearpages.wpengine.com, there has been strong usage and curiosity from the NEAR ecosystem community, with 6,000 accounts created and over 2,500 individual components published. The Pagoda team has been working closely with the active community of builders to help enhance the BOS experience.
Illia Polosukhin, CEO of Pagoda and co-founder of the NEAR protocol, also hosted a technical workshop where he zoomed in on each layer of the BOS stack and showed some examples of features, components to build from, and how gateways can become super apps by integrating with the BOS.
The next big update on the Blockchain Operating System will be at Consensus. You can find out more about NEAR’s presence at Consensus here.
OKR2: NEAR is a thriving decentralized Ecosystem
One of the NEAR Foundation’s core mandates is to support the continued decentralization of the NEAR ecosystem, and great progress has been made on this front since the previous transparency report.
A roundup of the ongoing decentralization efforts across the NEAR ecosystem follows.
NEAR Digital Collective (NDC)
The NDC initiative was announced towards the end of last year, and has grown to become a grassroots movement with hundreds of participants, including users, projects, and other stakeholders. The NDC is focused on self-governance, aiming to empower the ecosystem to collectively make decisions in a robust and decentralized way on everything from funding to elected representatives and more.
There are now several working groups that have been launched as part of the NDC’s work, covering various ecosystem needs including governance (Governance WG), marketing (Distribution Network WG), project incubation (Startup DAO), and legal work (Legal WG).
To learn more about the NDC, please see here.
NEAR Community Treasury Launch
One of the NDC’s biggest achievements is the recent launch of the NEAR Community Treasury. Championed by the NDC’s Governance Working Group with support from the NEAR Foundation and other stakeholders, the NEAR Community Treasury leverages an innovative legal framework to provide the ecosystem with a robust, sustainable, and decentralized treasury.
At the outset, the NEAR Community Treasury will hold 5,662,061 NEAR, which was donated to the NEAR Digital Collective by the NEAR ecosystem community (along with a nominal amount of USDT that was donated by the NEAR Foundation as part of the administrative setup process).
The NEAR Community Treasury wallet is viewable here.
Grassroots DAO funding activity
The three core grassroots DAOs — Developer DAO, Marketing DAO, and Creatives DAO — have been making great strides recently in updating their internal governance and processes to ensure they are as transparent, sustainable, and effective as possible.
NEAR Foundation has been supporting each of the grassroots DAOs through that update process. Both the Developer DAO and Marketing DAO have already begun allocating funding again, and the Creatives DAO intends to follow suit shortly.
The grassroots DAOs remain the key source of funding for anyone looking to build in the NEAR ecosystem.
NEAR Horizon (Accelerator)
The mission of NEAR Horizon is to attract the highest quality founders to build on NEAR protocol and support them in taking off. To that end, NEAR Horizon’s strategy consists of three components.
Product
The NEAR Horizon team is building a dApp on NEAR’s Blockchain Operating System that is a double-sided marketplace, which allows founders to find people and organizations who can help them. The team launched an MVP of the product for beta testers in early March 2023.
Partnerships
The team is launching a series of RFPs (the first RFP was released in Feb 2023) to create partnerships with people and organizations who are well positioned to help Founders. In early Q2, the NEAR Horizon team will be releasing additional open calls for:
Engineering support resources
Talent / recruitment platforms and services
Legal platforms and services
Back office accounting platforms and services
Marketing services
Product management services
Content & Tooling
The NEAR Horizon team will provide asynchronous content and access to tooling within the dApp. Think go-to-market examples, legal how-to guides and tools like back office accounting software specifically made for Web3 businesses.
OKR3: Web2 → Web3
Starting in Q2 last year, the Business Development team’s plan was to revamp and hire a full BD team, restructure past historic deals, solve for key infrastructure gaps, and bring the highest quality builders to the NEAR ecosystem. The team is now fully hired, ramped up, has met most key infrastructure gaps, and is in process of renegotiating past deals. Q1 marked the first full quarter that BD has focused on bringing builders to the NEAR ecosystem.
The goal of BD is to help enterprises and startups realize that the NEAR protocol should be the default chain of choice to start building any blockchain application. Fundamentally, BD is attempting to kickstart a flywheel effect to drive network effects to attract builders to the NEAR protocol in order to make it that default choice.
The flywheel starts with enterprises, marquee use cases, or household brands building on NEAR that provide brand awareness and legitimacy. This in turn attracts startups to NEAR. Collectively, these support real world use cases and increase adoption to attract more users to the chain, which in turn draw more enterprises and startups to build on NEAR.
For core use cases, BD is focused on a few key categories, including gaming, loyalty and rewards, and emerging verticals such as sustainability and decentralized science. In Q1 we focused on improving the number of partnership opportunities we were seeing, and our pipeline has increased dramatically. We found high quality sources of leads to be from backer referrals and agencies / dev shops so have strengthened those ties. BD has also seen a rise in projects looking for more support and a number of builders came over from other chains to make NEAR as their primary, or sole, chain (e.g. Passion, Dropt, Solaire). Geographically, the team now has expanded its focus to India and Korea, and expects to drive meaningful opportunities from entrepreneurs in those countries.
SWEAT continues to be a category leader in the move-to-earn space becoming one of the most popular Web3 apps in the world. SWEAT is being consistently used by a million monthly active users engaging voluntarily with NEAR protocol and using SWEAT tokens for staking or transactions. NEAR Foundation’s BD team will continue working with the talented SWEAT team on launching new features such as Learn & Earn, token swaps, and games that will create deeper bonds between the NEAR blockchain and SWEAT users.
For NEAR Foundation’s Q1 goals, the BD team set out to close three Tier 1 partnerships and seven Tier 2 partnerships for a total of 10 lighthouse partnerships — a goal which the NEAR Foundation surpassed. Although several of those deals are yet to be announced, NEAR Foundation is excited to highlight and welcome the following partners to the NEAR ecosystem:
Dropt — By using Dropt, teams and enterprises can now easily and seamlessly introduce blockchain-powered loyalty and engagement mechanics into their customer journey. These Web3 features will help increase engagement, retention, and lifetime value without customers ever even knowing they are interacting with the blockchain.
BORA (Kakao games) — An affiliate of Kakao Games and its parent company BORANETWORK, BORA is focused on game development and blockchain-based gaming ecosystems. NEAR and BORA will support each other in spreading local brand awareness, invest in research and collaboration on cross-chain, host events, and generate Web3 opportunities in Korea.
WEMADE – As one of the largest publicly-listed gaming companies in South Korea and a leading game developer in South Korea for over 20 years, WEMADE will be vital in NEAR’s push toward mainstream adoption of Web3. NEAR and WEMADE will support the development of blockchain apps in Korea as well as other markets.
Crystals of Naramunz – Featured in a premium spot under Sweden Showcases side by side with traditional games at one of the biggest gaming events in the country. Their alpha waitlist surpassed 10,000 signups.
SLiC Images – In February, NBA All-Star Baron Davis announced SLiC Images, a photo and video rights management platform. Built on NEAR, it has received a grant worth $250K funded by Mintbase Grants Program.
SeatlabNFT – Recently named as finalists in the Mobile and Emerging Technologies category for StartUp of the Year.
Hydra Ventures – A first in the Web3 space, Hydra Ventures is designed to help other investment DAOs get off the ground. This partnership will open the door to the eventual launch of the first investment DAO in the Near ecosystem, with the goal of helping to provide critical funding to purpose-driven, socially impactful web3 startups.
NEAR Foundation is also excited to partner with Flow Carbon (tokenized carbon credits market), Starchain Gazer (play and own gaming), Vizta Digital (fashion metaverse), and Popp (customer engagement for SMBs) to continue expanding the NEAR ecosystem. The NEAR Foundation’s BD team remains committed to bringing the best Web2 and Web3 builders to NEAR, and look forward to sharing next quarter’s list of partnerships.
Building stronger connections with the NEAR ecosystem
As part of NEAR Foundation’s ongoing commitment to transparency and building stronger connections with the NEAR ecosystem, a number of new initiatives are in progress.
First, the NEAR Foundation is restarting NEAR Town Halls. Similar to their previous incarnation, the Town Halls will be open to the entire NEAR ecosystem. Hosted by Marcus Ribeiro, a member of NEAR Foundation’s Community Team, they will be held bi-weekly — giving everyone a chance to get a firsthand look at the latest updates and exciting developments in the NEAR ecosystem. You can watch our March Town Hall here.
Earlier this year, NEAR Foundation kickstarted the Ecosystem Roundtable. Meeting weekly, the Ecosystem Influencer Roundtable is designed to enhance communication and increase accountability between major ecosystem projects, Pagoda, and NEAR Foundation. The roundtable’s regular meetings help with aligning on updates, sharing insights from the ecosystem, and discussing high-level ecosystem goals. These meetings, however, are not for decision-making purposes.
Most recently, the Ecosystem Influencer Roundtable met at an offsite at ETHDenver. Over time, the goal is for the Ecosystem Influencer Roundtable to become more autonomous, and for the participants to work independently to collaborate, set goals and initiatives for the NEAR ecosystem, and develop their own governance structure. You can read more about the roundtable here.
The Community Team also put out a NEAR Foundation Community Survey. The goal of this survey was to measure the ecosystem sentiment around NEAR Foundation and gather feedback on where to focus and improve efforts.The common areas for improvement that were identified were around funding, improving communications and transparency, and improving the support and engagement with the NEAR ecosystem.
Lastly, NEAR Foundation has been working on an overhaul of NEAR’s Twitter Spaces/AMAs, which showcase and highlight projects building on the NEAR ecosystem. The NEAR Foundation’s Community Team is finalizing a structured process for projects to leverage NEAR Foundation’s platforms to conduct Twitter Spaces/AMAs with the NEAR Foundation team. The team encourages feedback by following up to the Spaces/AMAs with a feedback form, which is reviewed to ensure community voices are heard and the valuable feedback is put into action. NEAR Foundation has run a few of these in a test flight to refine the project, and the new process should be live by May 2023. Stay tuned on NEAR Twitter, Telegram, and Discord accounts for an announcement on this new process.
NEAR in the press
Q1 saw a number of top news stories from the NEAR Foundation and NEAR protocol’s thriving ecosystem. The NEAR ecosystem was covered in over 400 articles across the globe in Q1, including over 15 tier 1 stories in outlets including CoinDesk, Forbes and Bloomberg, and 34 tier 2 stories in outlets including Block and Cointelegraph.
Headlines included the announcement of the Blockchain Operating System at ETHDenver, as well as coverage from many of our partnership announcements, ecosystem hubs, and progress from many of NEAR protocol’s ecosystem projects. These include Kakao Games, SlickImages (led by ex-NBA all-star Baron Davis), Recur, LedgerLive, Calimero, Few&Far and the NDC, amongst others (more details on these below).
To find out more about NEAR Foundation’s and the NEAR ecosystem’s press coverage you can check out the monthly roundups below:
NEAR Foundation PR Roundup for January
NEAR Foundation PR Roundup for February
NEAR Foundation PR Roundup for March
Ecosystem Highlights
Completed Raises
Q1 2023 saw several projects complete a fundraising round.
Open Forest Protocol raised $4.1 million
Calimero raised $8.5 million
Few and Far raised $10.5 million
Orderly Network publicly announced raising fresh funding at a flat token valuation of $200 million!
Ecosystem News & Community
The NDC GWG announced the NEAR Community Treasury is now live. 5.7 million NEAR is now available for decentralized funding of grassroots initiatives through the NDC. This is a major milestone in the efforts in decentralization of the NEAR ecosystem.
DevDAO, the organization behind NEAR Developer Governance, made significant strides in fostering open discussions and development via the Community and Work Groups. They established a framework and platform for decentralized funding for developer opportunities, and distributed funding to several projects. At its core, DevDAO is an embodiment of the future of decentralization of the NEAR developer ecosystem. The roadmap includes a range of initiatives such as hackathons, virtual and in-person events, documentation, and dev support programs. If you’d like to learn how to get involved, check out this post outlining the various contribution pathways.
The NEAR Wiki Landing page has been overhauled to provide a better user experience and a more refined journey for the end user to find what they’re looking for.
NEAR DemoDay kicked off this quarter on the 15th and 16th of March. DemoDay is a full spectrum ecosystem showcase, aiming to run once a quarter, which brings projects, leaders and VCs/Funds together to showcase new projects as well as discussions of hot topics in the space and exciting developments on NEAR. It was an impactful event, garnering significant interest, including from CoinTelegraph. DemoDay saw 64 projects registered, 22 projects presented live on DemoDay, with ten ecosystem VIP judges, including Marieke Flament and Alex Shevchenko and folks from Huobi Incubator and Pantera Capital. The recap content can be found on PitchTalk.com.
The NEAR Foundation Community Team kicked off a weekly NF Ecosystem Amplification Twitter Spaces/AMAs series to highlight the multitude of projects building in the NEAR ecosystem. ~30 projects expressed their interest in participating.
NEAR protocol is being included in CoinGecko’s Candy Rewards Learn and Earn Program. It is set to officially kick off in early April.
The Governance Forum has gone from 8,888 members at the start of Q1 to 9,329 (~5% growth in the quarter). Weekly pageviews on the forum have gone up from 82,269 (December average) to 124,445 (~51% increase). However, the number of posts are down by 15% from the previous quarter.
NEAR Social (BOS) has gone from 483 MAA at the start of Q1 to 4141 MAA as of today. (~857% growth in the quarter, ~319% growth since NEAR Day @ETH Denver)
DeFi
NEAR protocol saw a peak of $88m TVL in Q1 2023. Ref.Finance led the way for TVL on NEAR protocol, followed by MetaPool. There was, however, a 34% drop in TVL at the beginning of April as a result of the bankruptcy of Alameda, following on from the effects of FTX.
Ref.Finance launched an Orderbook built on top of Orderly. The orderbook provides a transparent, efficient, and decentralized mechanism for matching buy and sell orders on the platform, allowing users to experience a Central Limit Order Book (CLOB)-like user interface.
Spin launched Strategies, aka DeFi Option Vaults, on NEAR protocol. DeFi Options Vaults (DOVs) are instruments that simplify option investment strategies for users. The DOV automatically deploys staked assets into specific options strategies — a process entirely run by smart contracts.
Gaming
Duel Network, an innovative play-to-earn gaming project on BSC, launched their token on NEAR. By embracing NEAR’s technology and growing ecosystem, Duel Network is positioned to attract and engage users from BSC. This strategic move not only amplifies the Dual Network’s reach, but also strengthens the collaboration between NEAR protocol and other leading chains.
NFTs
EveryoneEatsEntertainment recently launched Music Feast, a decentralized label and NFT marketplace, on NEAR protocol. With Music Feast the team is aiming to bridge the gap between the traditional music industry and Web3 by utilizing high caliber talent, and simplifying the purchase process for the end user by masking the current complexities. For example, there is fiat on-ramping with auto generated non-custodial wallets. The platform launched with a NEARWEEK AMA, along with their pioneer artists AshleeBANKZ and world-renowned hip-hop icon DJWhooKid.
They are currently working with 8 artists, and others are on the way.
Artists will release 6 NFTs per collection on a tiered system with each providing additional perks and benefits.
The main artist drop right now is Whoo Kid, featuring Ashlee Bankz. Between Whoo Kid and ClassiQ there are an estimated 1.3 million reachable fans.
Salmon Wallet is building an all-in-one, open-source wallet with an integrated bridge, NFT marketplace, and other features. According to the project, the Source of Water NFTs work as an exclusive membership program — holding a Source of Water NFT grants a wallet perpetual free commissions on any swap/bridge/on-off-ramp.
YouMinter launched on mainnet. YouMinter is an NFT Social platform where users can create, communicate, and build a community within a sleek UI, with effortless onboarding and usage.
Infra & Devs
A 2022 Near Foundation grant recipient completed and launched their Rust Smart Contract Security Course. And the best part? It’s completely free on YouTube.
Welldone Studio / Welldone Wallet dropped a NEAR plugin for Remix IDE. WELLDONE Studio demoed their new plugin on April 4th, which enables developers to create and deploy smart contracts on NEAR with Remix Project, the most popular IDE on Ethereum.
Coinpanda announced its API integration with the NEAR protocol. Coinpanda is an easy-to-use crypto tax platform that supports DeFi, NFTs, and 800+ integrations.
At ETHDenver, Calimero announced the launch of private sharding on NEAR. Now anyone with minimum experience and proficiency in blockchain technology can launch their own private shard in a matter of minutes and be sure about the performance and security that is managed by the platform itself. This is facilitated by Calimero Console, a user-friendly interface that makes deploying, monitoring, and maintaining private shards a streamlined and user-friendly process.
Keypom is a tool built and recently launched on NEAR that allows anyone to create highly customizable onboarding experiences for both new and existing users. They launched a companion no-code app as well as an SDK and docs at ETHDenver. Keypom will be at Consensus, where they’ll show off trial accounts — a way to instantly sign in and start using an app with the click of a link.
NEAR Foundation, in partnership with Developer Governance, Proximity Labs and Aurora Labs, sponsored over $36,000 worth of bounties at ETHDenver, and there were a number of great submissions. There will be many more hackathons coming up this year, so be on the lookout for announcements so you don’t miss out.
Aurora released Aurora Cloud, a turnkey blockchain solution for businesses transitioning to Web3.
A Look Ahead
to Q2, the NEAR Foundation is continuing its strategic focus on similar OKRs to Q1, including more work on the Blockchain Operating System, the continuing efforts toward a thriving decentralized ecosystem, and our Web2.5 strategy.
This NEAR Foundation Transparency Report (the “Report“) is provided for informational purposes only. The information contained herein is provided on an “as is” basis, and the NEAR Foundation makes no representations or warranties, express or implied, regarding the accuracy, completeness, or reliability of the information contained in this Report.
The NEAR Foundation, its affiliates, directors, employees, and agents, shall not be held liable for any errors, omissions, or inaccuracies in the information provided herein. NEAR Foundation reserves the right to update, modify, or amend any information contained in this Report without prior notice. This Report is not intended to provide financial, investment, legal, tax, or any other professional advice. Readers should consult with their own professional advisors before making any decisions based on the information contained in this Report. |
---
id: what-is
title: What are Web3 Apps?
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
Web3 Applications - also known as decentralized apps (dApps) - leverage [smart contracts](../2.smart-contracts/what-is.md) and blockchain data to offer **transparency**, **security** and **giving back control** to users over their assets and data.
![img](/docs/assets/welcome-pages/examples.png)
NEAR simplifies building Web3 apps for the general public, making it easy to **interact** with different blockchains, while helping to **onboard users** that are not familiarized with crypto.
---
### Why Integrating NEAR to your App?
Any application can benefit from integrating NEAR, including games, financial services, social platforms, and more.
- **Easy Onboarding**: Users can create accounts using familiar methods such as email login. Furthermore, applications can cover all transactional costs for their users, so they never have to worry about handling crypto.
- **Ownership**: Users have true ownership of digital assets within their accounts. Fungible Tokens can be used as reward systems, Non-Fungible Tokens can denote holdings, and wallets can represent digital identities.
- **Fast, Cheap and Scalable**: Near’s efficient consensus mechanism and fee model make transactions cost effective for both users and developers.
- **Security & Transparency**: All transactions and data on the blockchain is transparent and auditable, thus ensuring trust in the application’s behavior.
|
---
id: cookbook
title: Common Use Cases
sidebar_label: Cookbook
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
The repository contains [many recipes](https://github.com/near/near-api-js/blob/master/packages/cookbook) that you can readily use to solve common case scenarios.
| Name | Description |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ----------------------------------------------------------------------------------------------------------- |
| **ACCOUNTS** | |
| [Create Account](https://github.com/near/near-api-js/blob/master/packages/cookbook/accounts/create-testnet-account.js) | Create [NEAR accounts](/concepts/protocol/account-model) without using NEAR Wallet. |
| [Access Key Rotation](https://github.com/near/near-api-js/tree/master/packages/cookbook/accounts/access-keys) | Create and delete [access keys](/concepts/protocol/access-keys) for added security. |
| **TRANSACTIONS** | |
| [Get Transaction Status](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/get-tx-status.js) | Gets transaction status using a tx hash and associated account/contract ID. |
| [Recent Transaction Details](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/get-tx-detail.js) | Get recent transaction details without using an [indexing](/concepts/advanced/near-indexer-framework) service. |
| [Batch Transactions](https://github.com/near/near-api-js/blob/master/packages/cookbook/transactions/batch-transactions.js) | Sign and send multiple [transactions](/concepts/protocol/transactions). |
| **UTILS** | |
| [Deploy Contract](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/deploy-contract.js) | Deploys a smart contract using a pre-compiled WASM file. |
| [Calculate Gas](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/calculate-gas.js) | Calculate [gas burnt](/concepts/protocol/gas) from any contract call. |
| [Read State w/o Account](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/get-state.js) | Read state of a contract without instantiating an account. |
| [Wrap](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/wrap-near.js) & [Unwrap](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/unwrap-near.js) NEAR | Wrap and unwrap NEAR using the `wrap.near` smart contract. |
| [Verify Signature](https://github.com/near/near-api-js/blob/master/packages/cookbook/utils/verify-signature.js) | Verify a key pair signature. |
|
NEAR and WEMADE Team Up to Accelerate Mainstream Web3 Adoption
NEAR FOUNDATION
March 23, 2023
The Near Foundation is excited to announce that it’s partnering with WEMADE, one of the largest publicly-listed gaming companies in South Korea. A leading game developer in South Korea for over 20 years, WEMADE will be vital in Near’s push toward mainstream adoption of Web3.
Near and WEMADE will support the development of blockchain apps in Korea as well as other markets. Near and WEMADE will also jointly work on mutual brand awareness, and collaborate on a number of Web3 community events and business opportunities.
“WEMADE and Near share a similar vision of enabling and accelerating the mainstream adoption of blockchain to create a future of nearly limitless potential use cases and benefits for all of us across many different areas of our daily lives,” said Shane Kim, CEO, WEMIX and Vice President, WEMADE.
“In order to achieve that vision, we must make it easier, faster, and more cost-effective for developers to onboard off-chain apps, organizations, and startups, and are confident that Near is ideally positioned to do so.”
Onboarding end users and developers into Web3
The partnership will do much to encourage developers, including game designers, to build on the Near. Beyond co-hosting community events like offline hackathons and boot camps, Near and WEMADE will work together on mutual brand awareness, invest in research and collaboration on cross-chain initiatives, and be on the lookout for potential Web3 business opportunities and founders.
A renowned leader in game development, WEMADE is at the forefront of a generational shift as the gaming industry pivots to blockchain technology. Its WEMIX subsidiary is building an experience-based, platform-driven, and service-oriented mega-ecosystem — one that will give users everywhere access to a wide array of easy-to-use Web3 apps and experiences.
“We’re thrilled to be partnering with WEMADE as part of our shared vision towards a decentralized future for the gaming industry,” said Commenting on the partnership, Marieke Flament, CEO of the Near Foundation. “By joining forces, we are confident in our ability to accelerate the development of cutting-edge solutions that meet the growing needs of gamers and developers in the Web3 space.”
The Near-WEMADE partnership marks the second major Web3 gaming partnership from the Near Korea Hub. The first, a partnership with BORA — the Web3 GameFi platform of Kakao Games — will also be vital in accelerating the mainstream adoption of Web3.
|
---
sidebar_position: 3
---
# Private Methods
## When using callbacks
Usually, when a contract has to have a callback for a remote cross-contract call, this callback method should only be called by the contract itself. It's to avoid someone else calling it and messing the state. Pretty common pattern is to have an assertion that validates that the direct caller (predecessor account ID) matches to the contract's account (current account ID). Macro `#[private]` simplifies it, by making it a single line macro instead and improves readability.
Use this annotation within the [`near_bindgen` macro](../contract-structure/near-bindgen.md) as follows:
```rust
#[private]
pub fn my_method(&mut self) {
…
}
```
Which is equivalent to:
```rust
pub fn my_method(&mut self ) {
if near_sdk::env::current_account_id() != near_sdk::env::predecessor_account_id() {
near_sdk::env::panic_str("Method method is private");
}
...
}
```
Now with this annotation, only the account of the contract itself can call this method, either directly or through a promise.
## Writing internal methods
Not all functions need to be exposed publicly. It may be beneficial to write private methods for helper or utility functions, for instance. There are three approaches to write internal methods:
1. Using `fn` instead of `pub fn`
```rust
fn helper_method(a: u8, b: u8) {
…
}
```
2. Using `pub(crate) fn`. This may be helpful when an internal method is in a different module.
```rust
// Function that can be called in another Rust file
pub(crate) fn get_first_name(account: Account) {
…
}
```
More information from the [official Rust docs](https://doc.rust-lang.org/reference/visibility-and-privacy.html) regarding public/private methods.
3. Separate `impl` block
Another way of not exporting methods is by having a separate `impl Contract` section, that is not marked with `#[near_bindgen]`.
```rust
#[near_bindgen]
impl Contract {
pub fn increment(&mut self) {
self.internal_increment();
}
}
impl Contract {
/// This methods is still not exported.
pub fn internal_increment(&mut self) {
self.counter += 1;
}
}
```
|
Dragonfly Capital Joins NEAR Validator Advisory Board
COMMUNITY
January 18, 2021
For anyone following the validator set over the weekend, you may have noticed that a new validator called “dragonfly.poolv1.near” quickly climbed into the top three position in the active set. This is linked to Dragonfly Capital, whose managing director Haseeb Qureshi will join the NEAR Validator Advisory Board (NVAB) this week.
Dragonfly Capital is a global investment firm which focuses on blockchain and has an active presence across both the US and Asian markets. They are known for their research and highly technical team.
Dragonfly will play a key role in the governance and evolution of NEAR through its next phase of adoption as part of the NEAR Validator Advisory Board, which is a select group of professional validators and infrastructure providers who participate in the technical governance of NEAR. Because NEAR is a fully decentralized and community-controlled protocol, the validators help make decisions on the evolution of the technology and network. Starting with the MainNet launch in October 2020, NVAB members work with the engineering teams on testing, feedback, requests for new features, and market research.
The NVAB is also working closely with NEAR to develop the Smart Contract-based delegation for the staking of NEAR tokens, a unique innovation among Proof-of-Stake blockchain protocols. Delegation via smart contracts—rather than at the protocol level, as most PoS blockchains do—will offer more flexibility for the validators, allowing them either to produce their own validation contract or to configure staking rewards that optimize for particular positions, like the size of delegation or a certain lockup timeline. This enables a dynamic marketplace between validators and stakers while also securing the protocol.
Haseeb shared a post about why he and his team are excited about NEAR and joining the NVAB. As a horizontally-scalable, sharded PoS blockchain, NEAR will offer solutions to many of the pain points facing other protocols today, such as network congestion, limited transaction throughput, prohibitively high gas costs, and barriers to mainstream usability.
NEAR is a layer-one protocol designed to interoperate with Ethereum and which addresses some of the current challenges posed by the overwhelming volume of DeFi activity. NEAR can securely absorb and extend the development activity of a layer-one like Ethereum much like other layer-two solutions do, but with all the security and governance guarantees of an advanced layer-one protocol.
NEAR’s emphasis on usability means that developers don’t need to learn a new programming language to be able to build on the network. The combination of accessible, native WASM-based runtime alongside EVM compatibility on the horizon, as well as a fully decentralized, trustless cross-chain asset bridge called the Rainbow Bridge, means that building on NEAR is accessible to any developer, whether porting apps from Ethereum, or builders just getting started on blockchain programming. (Not to mention other usability-enhancing features such as human-readable addresses and contract-level developer rewards.)
The success of any smart contract platform depends not just on the quality of the tech, but also the community. We’re very excited to welcome Dragonfly Capital to the NVAB and the wider NEAR community as we forge the path to true mainstream crypto adoption. Don’t forget to check out their research post for more details on why Dragonfly is excited about NEAR’s future.
|
---
id: what-is
title: What are Primitives?
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
Primitives are fundamental building blocks that can be combined to create a fully functional application. Blockchain primitives include [Fungible Tokens (FT)](#fungible-tokens-ft), [Non Fungible Tokens (NFT)](#non-fungible-tokens-nft), [Decentralized Autonomous organizations (DAO)](#decentralized-autonomous-organizations-dao), [Link Drops](#linkdrops) and more.
![img](/docs/assets/welcome-pages/primitives-landing.png)
---
#### Fungible Tokens (FT)
[Fungible tokens](./ft.md) represent an **asset** on a blockchain that is **interchangeable**. Besides the native NEAR token, users can issue their own fungible tokens or use those that are already present in the ecosystem.
:::tip
Fungible Tokens are ideal to create **reward systems**, **fair tickets** and any other type of **token**.
:::
<hr class="subsection" />
#### Non Fungible Tokens (NFT)
In contrast with fungible tokens, each [non-fungible token (NFT)](./nft.md) is **unitary** and therefore **unique**. Users can create their own non-fungible token, transfer to other users, or exchange them in marketplaces.
:::tip
NFTs are ideal to represent **ownership of assets** such as **collectibles**, **event tickets** and other unique assets.
:::
<hr class="subsection" />
#### Decentralized Autonomous organizations (DAO)
[Decentralized Autonomous Organizations (DAOs)](./dao.md) are **self-organized groups** that form around common purposes. Membership, decision making, and funding are **coordinated** by **publicly voting** on proposals through a smart contract.
:::tip
DAOs are ideal to create **decentralized governance**, **funding**, and **decision-making** tools.
:::
<hr class="subsection" />
### LinkDrops
[LinkDrops](./linkdrop.md) are an easy way to **distribute digital assets** (NFTs, FTs) via links. You simply **provide a link** for users and they can **claim** your drop.
:::tip
LinkDrops are ideal to do **drops**, and **onboard new users** into Web3 apps.
::: |
---
id: frontrunning
title: Front Running
---
In the NEAR network, validators have access to the transaction pool, and can therefore see them before they execute. This enables validators to analyze transactions for a potential profit and frontrun them with a transaction of their own.
For example, imagine that you make a game where users are paid for solving puzzles. If not handled carefully, a validator could swap a transaction with the valid answer for one of its own and claim the prize. You can read more about this in [this blog post](https://www.paradigm.xyz/2020/08/ethereum-is-a-dark-forest).
|
---
id: basics
title: "Basic Instructions"
---
# Basic instructions
To compile release version of the smart contract you can run:
```bash
cargo build --target wasm32-unknown-unknown --release
```
:::info
The above `build` command is setting a `target` flag to create a WebAssembly `.wasm` file.
:::
Notice that your project directory now has a few additional items:
```bash
.
├── Cargo.lock ⟵ created during build to lock dependencies
├── Cargo.toml
├── src
│ └── lib.rs
└── target ⟵ created during build, holds the compiled wasm
```
# Build and Flags
We recommend you to optimize your build artifact with the use of the next flags in your Cargo.toml file. If you are performing a multi-contract build, you should include these settings in the Cargo.toml that is at the root of your project.
```bash
[profile.release]
codegen-units = 1
# Tell `rustc` to optimize for small code size.
opt-level = "z"
lto = true
debug = false
panic = "abort"
# Opt into extra safety checks on arithmetic operations https://stackoverflow.com/a/64136471/249801
overflow-checks = true
```
The above command is essentially setting special flags and optimizing the resulting `.wasm` file. At the end of the day, this allows you to customize the `cargo build --release` command.
# Custom Flags
If you wish to add custom flags to your build, you can perform this by adding build flags to your `ProjectFolder/.cargo/config.toml` as illustrated in this example.
```toml
[target.wasm32-unknown-unknown]
rustflags = ["-C", "link-arg=-s"]
```
A full set of build options can be accessed at https://doc.rust-lang.org/cargo/reference/config.html.
You can find an example [here](https://github.com/near/near-sdk-rs/blob/05e4539a8f3db86dd43b768ee9660dd4c8e7ea5c/examples/fungible-token/.cargo/config.toml).
|
---
sidebar_position: 2
sidebar_label: "Set up Rust and a contract skeleton"
title: "Set up Rust, get a NEAR testnet account, NEAR CLI, and get a basic smart contract skeleton ready"
---
import {Github} from "@site/src/components/codetabs"
# Getting started
In this tutorial we'll get a testnet account, use NEAR CLI to add a key to our computer's file system, and set up the basic skeleton of a Rust smart contract.
## Getting a testnet account
Visit [NEAR Wallet for testnet](https://testnet.mynearwallet.com/) and register for a free account. For the purposes of this tutorial, you may skip the option to add two-factor authentication if you wish.
:::note What just happened?
When you created your NEAR testnet account, a private key was created and placed into your browser's local storage. You may inspect this using developer tools and see it.
:::
## Creating a new key on your computer
We'll want to use a command-line interface (CLI) tool to deploy a contract, but at the moment the private key only exists in the browser. Next we'll _add a new key_ to the testnet account and have this stored locally on our computer as a JSON file. (Yes, you can have multiple keys on your NEAR account, which is quite powerful!)
Let's install NEAR CLI. (Please ensure you [have NodeJS](https://nodejs.org/) > 12.)
npm install -g near-cli
You may now run:
near
to see various commands, which are covered [in detail here](https://docs.near.org/tools/near-cli).
We'll start by "logging in" with this command:
near login
This will bring you to NEAR Wallet again where you can confirm the creation of a **full-access** key. We'll get to full-access and function-call access keys later, just know that for powerful actions like "deploy" we'll need a full-access key. Follow the instructions from the login command to create a key on your hard drive. This will be located in your operating system's home directory in a folder called `.near-credentials`.
:::note How was a key added?
When you typed `near login`, NEAR CLI generated a key pair: a private and public key. It kept the private key tucked away in a JSON file and sent the public key as a URL parameter to NEAR Wallet. The URL is long and contains other info instructing NEAR Wallet to "add a full access key" to the account. Our browser's local storage had a key (created when the account was made) that is able to do several things, including adding another key. It took the public key from the URL parameter, used it as an argument, and voilà: the testnet account has an additional key!
:::
You can see the keys associated with your account by running the following command, replacing `friend.testnet` with your account name:
near keys friend.testnet
## Setting up Rust
You may have found the [online Rust Book](https://doc.rust-lang.org/stable/book), which is a great resource for getting started with Rust. However, there are key items that are different when it comes to blockchain development. Namely, that smart contracts are [technically libraries and not binaries](https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#crate), but for now just know that we won't be using some commands commonly found in the Rust Book.
:::caution We won't be using
cargo run
during smart contract development.
:::
Instead, we'll be iterating on our smart contract by building it and running tests.
### Install Rust using `rustup`
Please see the directions from the [Rustup site](https://rustup.rs/#). For OS X or Unix, you may use:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
(Taken from the [Rust installation guide](https://www.rust-lang.org/tools/install))
### Add Wasm toolchain
Smart contracts compile to WebAssembly (Wasm) so we'll add the toolchain for Rust.
rustup target add wasm32-unknown-unknown
(More info on [targets and this toolchain here](https://doc.rust-lang.org/edition-guide/rust-2018/platform-and-target-support/webassembly-support.html).)
## Start writing Rust!
There's a basic repository that's helpful to clone or download [located here](https://github.com/near/boilerplate-template-rs).
The first thing we'll do is modify the manifest file at `Cargo.toml`:
```diff
[package]
- name = "rust-template"
+ name = "my-crossword"
version = "0.1.0"
- authors = ["Near Inc <hello@near.org>"]
+ authors = ["NEAR Friend <friend@example.com>"]
edition = "2018"
```
By changing the `name` here, we'll be changing the compiled Wasm file's name after running the build script. (`build.sh` for OS X and Linux, `build.bat` for Windows.) After running the build script, we can expect to find our compiled Wasm smart contract in `res/my_crossword.wasm`.
Now let's look at our main file, in `src/lib.rs`:
<Github language="rust" start="8" end="44" url="https://github.com/near/boilerplate-template-rs/blob/f1edeead98a9ec12c3f6db311f62025305f57874/contract/src/lib.rs" />
As you can see, this is a stub that's ready to be filled in. Let's pause and point out a few items:
- Note the [**near_bindgen** macro](/sdk/rust/contract-structure/near-bindgen) is above the struct and the impl
- Here the main struct is called `Contract`, while in other examples it might be `Counter` or something else. This is purely stylistic, but you may learn more from the link in the previous bullet.
- You may notice the word "Borsh" and wonder what that means. This is a binary serializer. Eventually, we'll want to save data as ones and zeroes to validators' hard drives, and do it efficiently. We use Borsh for this, as is explained [on this website](https://borsh.io).
Next, let's modify this contract little by little…
|
NEAR Digital Collective Legal Framework
COMMUNITY
March 21, 2023
To help accelerate real-world value creation in the NEAR ecosystem, the NEAR community has launched the NEAR Community Purpose Trust (for ease referred to in the remainder of this post as the ‘NEAR Community Treasury’). The NEAR Community Treasury is intended to serve as a decentralised treasury for the NEAR ecosystem that will allocate funds to support various grassroots initiatives.
The launch of the NEAR Community Treasury has been championed by the Governance Working Group (‘GWG’), a group focussing on ecosystem governance initiatives as part of the NEAR Digital Collective (‘NDC’). The NDC is an ambitious grassroots initiative that brings together users, projects, stakeholders and partners of the NEAR ecosystem to promote self-governance, aiming to empower the ecosystem to collectively make decisions on everything from funding to elected representatives and more. It is a significant step towards an even further decentralised network.
The NEAR Community Treasury leverages an innovative legal framework that builds on work that has already been done utilising Guernsey Special Purpose Trust frameworks elsewhere in the industry. The NEAR community hopes that this framework should help to bring much-needed clarity to participants in decentralised autonomous organisations (‘DAOs’). Below for discussion purposes only is a high-level summary of some of the key features of the NEAR Community Treasury framework.
What is the NEAR Community Treasury and how is it structured?
A trust is a mechanism for holding assets so that the legal title to those assets is separated from the beneficial interest in those assets. One or more trustees are appointed as the ‘legal’ owners of the assets in question, and those trustees are bound by various duties and obligations to hold those assets either:
for the benefit of one or more beneficiaries; or in certain cases,
to further one or more specified purposes (with a trust of this nature typically referred to as a ‘Purpose Trust‘).
The NEAR Community Treasury is a type of Purpose Trust, specifically a Guernsey Non-Charitable Purpose Trust (a ‘GNCPT’). A GNCPT is brought into existence when assets are transferred to one or more trustees (the ‘Trustees‘), and those trustees enter into a written settlement of trust (the ‘Trust Instrument’) with another party termed an enforcer (the ‘Enforcer‘) which determines how the assets subject to the trust will be administered.
The Trust Instrument sets out the duties and obligations of the Trustees and Enforcer, and also the various purposes that the NEAR Community Treasury was created to support. The NEAR Community Treasury is governed by Guernsey law at its inception (although this can be changed by the Trustees with NEAR community consent). The Trust Instrument has been drafted to deliberately minimise the trust that the NEAR community needs to place in the Trustees, the Enforcer and any centralised administrator. The NEAR Foundation has no control over the NEAR Community Treasury, nor any ownership right or interest in respect of any assets held in the NEAR Community Treasury.
The Trustees are required to administer the NEAR Community Treasury in accordance with the terms of the Trust Instrument and are also subject to various fiduciary duties which require them to, for example, always act honestly and in good faith and exercise their powers in furtherance of the purposes of the NEAR Community Treasury. The Trustees are also subject to a duty of care which requires them to employ the care, skill and diligence of a prudent person of business when administering the trust assets. Both the Trustees and Enforcer are also required to comply with all applicable laws and regulations in connection with their roles.
The Enforcer has a fiduciary duty to enforce the NEAR Community Treasury in relation to its non-charitable purposes and has a proactive oversight function, monitoring the Trustees and their administration of the NEAR Community Treasury to ensure they are complying with their duties and obligations. The Enforcer has the power to request information and documentation from the Trustees; and also has the power to remove one or more Trustees in certain circumstances (more on this below).
The Trustees can use the assets in the NEAR Community Treasury for any transaction or arrangement that furthers one or more purposes of the NEAR Community Treasury, provided the transaction and/or arrangement has been approved by the NEAR community.
At this stage, the NEAR community has not yet launched any on-chain voting mechanism (although there are various potential implementations in development). The Trust Instrument therefore also provides the Trustees with a limited power – subject to various constraints – to use assets in the NEAR Community Treasury for any transaction or arrangement that furthers one or more purposes of the NEAR Community Treasury without requiring approval of the NEAR community (the ‘Limited Trustee Power‘). Once an on-chain voting mechanism is launched by the NEAR community, this Limited Trustee Power will fall away permanently.
The Trust Instrument was reviewed by a set of skilled external and community legal counsel in Switzerland, the US and Guernsey. A group of lawyers from the NEAR community also reviewed the Trust Instrument, alongside various members of the GWG. The Trustees are required to make a copy of the Trust Instrument available to the NEAR community, and a copy of the signed Trust Instrument will be stored on IPFS (and this post will be updated with the IPFS link once it is confirmed by the Enforcer).
The NEAR Foundation does have any control over, or ownership of, the NEAR Community Treasury
What are the purposes of the NEAR Community Treasury?
The purposes of the NEAR Community Treasury are set out in Schedule 3 of the Trust Instrument, and consist of two types of purpose:
(i) Core Purposes: to support and promote the operation and/or development of the NEAR Blockchain and/or associated ecosystem. These Core Purposes cannot be changed by anyone, although new Core Purposes can be added by the Trustees with NEAR community consent.
(ii) Subsidiary Purposes: there are various Subsidiary Purposes including to stake the majority of the Trust Fund that is NEAR denominated, and to consider and if thought fit approve funding proposals from the NEAR community. Subsidiary Purposes can be added or removed by the Trustees with NEAR Community consent.
Any assets held in the NEAR Community Treasury must therefore be used by the Trustees to support one or more of these Core and/or Subsidiary Purposes.
Who are the Trustees and Enforcer of the NEAR Community Treasury?
The initial Trustees are the following individuals from the NEAR ecosystem:
Alina Tustanovska
Carolin Geier
Rahmat Albariqi (Riqi)
Rune Bentien
Antonio Morales Cordoba
The initial Enforcer is Francesco Paolo Piatti, who is an experienced lawyer in the Web3 space. The initial Trustees and Enforcer were selected by the GWG, a grassroots community group that has been working on various ecosystem governance initiatives. The process the GWG used to select the initial Trustees and Enforcer is set out in detail here.
How do the Trustees and Enforcer operate?
There must always be a minimum of 3 Trustees (although there is no upper limit specified in the Trust Instrument). Trustees can be appointed and/or removed by the Enforcer at the direction of the NEAR community. The Enforcer also has the power to remove any Trustee where that Trustee has committed a breach of a purpose or a breach of fiduciary duty. Conversely, the Enforcer can be removed by the Trustees at the direction of the NEAR community.
Each Trustee has one vote on any proposal. Trustees are required to disclose any direct or indirect conflict of interest in respect of any proposal, and by default cannot participate in any vote where they are conflicted. The Trust Instrument prohibits the same person occupying the role of a Trustee and Enforcer simultaneously.
The Trustees and Enforcer are entitled to be paid a reasonable remuneration for performing their respective roles (and the NEAR community has control in respect of this remuneration on the basis that, to the extent any remuneration is put in place that the NEAR community disagrees with, the NEAR community can remove the Trustees and/or Enforcer).
What assets are held by the NEAR Community Treasury?
At the outset, the NEAR Community Treasury will hold 5,662,061 NEAR that was donated to the NEAR Digital Collective initiative by the NEAR community (along with a nominal amount of USDT that was donated by the NEAR Foundation, consistent with its legal purpose, as part of the administrative set-up process). The NEAR Community Treasury wallet can be viewed here.
The Trustees will administer this initial trust property as a proof of concept, enabling the NEAR community to establish how to best utilise this GNCPT framework and demonstrate that the NEAR Community Treasury framework can be used effectively. Moving forward, the NEAR Foundation (as well as other NEAR ecosystem participants) can make further contributions of assets into the NEAR Community Treasury based on the needs of the ecosystem.
How will the NEAR Community Treasury operate in practice?
The Trustees provided NEAR addresses, as well as Twitter and Telegram handles (but not physical addresses), in the Trust Instrument. They are able to make decisions as they would normally in the absence of the trust (e.g. via real-time written communications like Telegram or Signal) without having to adopt any additional formalities or bureaucratic processes.
The Trustees control the NEAR Community Treasury multi-sig wallet and can execute transactions that support one or more of the NEAR Community Treasury’s purposes from this wallet, with a majority of Trustees required to approve/sign any transaction. Any such transaction or arrangement must support one or more of the NEAR Community Treasury’s purposes and would require NEAR community consent; however as discussed above until the NEAR community implements some form of on-chain voting mechanism, the Trustees have the Limited Trustee Power to allocate funds from the NEAR Community Treasury without requiring the consent of the NEAR community. Any such allocations would still need to support or further one or more of the Core and/or Subsidiary Purposes.
Based on the GWG’s proposed framework, the NEAR community’s intention during this initial period is for the NEAR Community Treasury to receive funding proposals just from the 3 ecosystem grassroots DAOs – being the Developer DAO, Marketing DAO and Creatives DAO. The NEAR Community Treasury’s scope will likely be widened moving forwards as determined by the Trustees and the NEAR community, potentially becoming the primary treasury/capital allocation node in the ecosystem.
Based on input from the GWG, the Trust Instrument envisages that the NEAR community will develop an on-chain voting mechanism that leverages proof of personhood technology (i.e. technology that can verify there is an identifiable, unique individual controlling a NEAR account).
Once the NEAR community launches this on-chain voting mechanism, the Limited Trustee Power will fall away permanently. The NEAR community will then be able to put forward and approve funding proposals, and also direct the Trustees to take various actions including:
fulfill grant requests;
add Core Purposes and add/remove Subsidiary Purposes;
appoint/remove Trustee(s) and/or Enforcer; and
change the NEAR Community Treasury’s governing law.
What are the benefits of the NEAR Community Treasury structure?
Participant Liability
One of the most significant legal issues currently facing DAOs and other decentralised initiatives is participant (or token-holder) liability. Recent legal developments (for example in connection with the CFTC’s enforcement action against Ooki DAO) have only heightened the uncertainty and risks in this context, particularly with respect to DAOs being classified as ‘general partnerships’ or ‘unincorporated associations’ and creating potential joint and several liability exposure for participants. This means participants potentially being held individually liable on an unlimited basis for their own actions, and/or the actions of the entire DAO/initiative, and/or the actions of certain participants.
It is the hope of the NEAR community that the NEAR Community Treasury may help to mitigate these potential participant liability issues:
The Trustees undertake (in their capacity as Trustees) certain activities and actions (e.g. holding treasury, making grants) that might otherwise expose ecosystem participants to potential liability. Other ecosystem participants do not undertake these activities and instead exercise oversight over the Trustees and Enforcer.
When the Trustees (a) act (as they are required to do) in accordance with the provisions of the Trust Instrument and their fiduciary and statutory duties as trustees; and (b) also make it clear to any third parties that they are acting in their capacities as trustees of the Community Treasury, then the liability of each Trustee should be limited to the value of the assets held in the NEAR Community Treasury.
In addition:
The Trustees are indemnified under the Trust Instrument, meaning that they will be compensated for any liability/losses suffered by them in carrying out their duties as Trustees from the assets held in the NEAR Community Treasury.
The Trust Instrument also makes it clear that the Trustees will not be liable for any losses arising to or suffered by the assets in the NEAR Community Treasury (save for any losses arising in respect of a Trustee’s breach of trusts arising from their own fraud, wilful misconduct or gross negligence).
Off-chain activities
Without a formal legal structure, if a DAO/decentralised initiative wishes to participate in an off-chain transaction or arrangement then typically individual participants would be required to enter into the relevant transaction/arrangement in their individual capacity (and/or some other affiliated legal person); exposing them to potential liability. While the NEAR Community Treasury is a ‘legal arrangement’ and so not itself a ‘legal person’ (i.e. it does not have a separate legal personality from the Trustees, unlike for example a limited liability company), the Trustees are able to interact with the off-chain world – in their capacity as trustees – in a similar way as other entities (for example, opening a bank account).
Tax
Certain activities undertaken by DAOs, particularly holding a DAO treasury, can create complex tax consequences for participants (especially in the absence of any clear guidance). One critical risk is the possibility of tax liability arising in connection with DAO activities being attributed to (and so payable by) individual participants.
The NEAR Community hopes that the NEAR Community Treasury may mitigate that risk for participants by ensuring the relevant activities are being undertaken by the Trustees (in their capacity as Trustees). In addition, as the NEAR Community Treasury does not have any Guernsey resident beneficiaries or Guernsey-source income, it should not be liable to tax in Guernsey nor be required to make any on-going tax or reporting filings.
Efficient and trustless
Unlike many other alternative DAO legal ‘wrapper’ or ‘proxy’ structures, the NEAR Community Treasury does not rely on a centralised administrative body to be brought into existence or maintain its legal standing – the execution of the Trust Instrument by the relevant parties is all that is required. As mentioned above, there are also minimal operational formalities, meaning the Trustees can make decisions as they would normally (i.e. as if the trust wasn’t there).
Under Guernsey law, there is also significant flexibility regarding who can serve as a Trustee or Enforcer, including no requirement for a locally-registered professional trustee/trust company to serve as a trustee. To the extent any disputes were to arise in connection with the NEAR Community Treasury, these would be heard and ultimately determined by the courts in Guernsey.
What happens if the NEAR Community Treasury is terminated?
The NEAR Community Treasury is irrevocable and can continue to exist for as long as there are Core and/or Subsidiary Purposes to support. The NEAR community could however direct the Trustees to transfer all of the NEAR Community Treasury assets to another trust (provided such a transfer supported one or more Core and/or Subsidiary Purposes).
The Trust Instrument also contains various contingencies in the event all of the NEAR Community Treasury’s Core and/or Subsidiary Purposes cease to exist and/or one or more Trustees undertake a transaction or arrangement that is in breach of one or more Core and/or Subsidiary purposes. In such circumstances, the Enforcer (acting reasonably and in good faith) has the power to direct the Trustees to transfer the NEAR Community Treasury assets to a new trust or otherwise deploy them for the benefit of the NEAR community.
Some closing thoughts
The NEAR community hopes that the NEAR Community Treasury framework will enable the NEAR community to benefit from a decentralised treasury in a risk mitigated manner. For more information about Guernsey Non-Charitable Purpose Trust frameworks, a template Guernsey Special Purpose Trust Instrument will shortly be hosted on the NEAR Foundation GitHub (and this post will be updated to include the relevant link, once available).
Disclaimer: Nothing in this article/post should be construed as legal, tax or investment advice. This post might not reflect all current updates to applicable laws, regulations or guidance. Any templates or documentation referenced in this post are made available on a non-reliance basis and the authors do not assume any responsibility for their contents or any consequences of their use. The authors disclaim any obligation to update this post, and also reserve the right to make any changes to this post without notice. The subject matter of this post deals with an emerging and uncertain area of the law and there are no guarantees (and none are given, of whatsoever nature, by the authors or otherwise) that the NEAR Community Treasury framework will effectively mitigate any of the risks identified above. In all cases persons should conduct their own investigation and analysis of the information in this post. Please consult with a reputable lawyer in your jurisdiction for any questions or concerns and before making use of any templates or documentation referenced in this post. Neither this post nor the NEAR Community Treasury constitutes, or is indented to constitute, the offer or sale of any security or token. |
```rust
// Account ID that represents a token in near-sdk v3
// Need to keep it around for backward compatibility
pub type OldAccountId = String;
// How the voting policy votes get weighted.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub enum WeightKind {
// Using token amounts and total delegated at the moment.
TokenWeight,
// Weight of the group role. Roles that don't have scoped group are not supported.
RoleWeight,
}
// Direct weight or ratio to total weight, used for the voting policy
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde")]
#[serde(untagged)]
pub enum WeightOrRatio {
Weight(U128),
Ratio(u64, u64),
}
// Defines configuration of the vote
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde")]
pub struct VotePolicy {
// Kind of weight to use for votes.
pub weight_kind: WeightKind,
// Minimum number required for vote to finalize.
// If weight kind is TokenWeight - this is minimum number of tokens required.
// This allows to avoid situation where the number of staked tokens from total supply is too small.
// If RoleWeight - this is minimum number of votes.
// This allows to avoid situation where the role is got too small but policy kept at 1/2, for example.
pub quorum: U128,
// How many votes to pass this vote.
pub threshold: WeightOrRatio,
}
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde")]
pub enum RoleKind {
// Matches everyone, who is not matched by other roles.
Everyone,
// Member greater or equal than given balance. Can use `1` as non-zero balance.
Member(U128),
// Set of accounts.
Group(HashSet<AccountId>),
}
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde")]
pub struct RolePermission {
// Name of the role to display to the user.
pub name: String,
// Kind of the role: defines which users this permissions apply.
pub kind: RoleKind,
// Set of actions on which proposals that this role is allowed to execute.
// <proposal_kind>:<action>
pub permissions: HashSet<String>,
// For each proposal kind, defines voting policy.
pub vote_policy: HashMap<String, VotePolicy>,
}
// Defines voting / decision making policy of this DAO
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde")]
pub struct Policy {
// List of roles and permissions for them in the current policy.
pub roles: Vec<RolePermission>,
// Default vote policy. Used when given proposal kind doesn't have special policy.
pub default_vote_policy: VotePolicy,
// Proposal bond.
pub proposal_bond: U128,
// Expiration period for proposals.
pub proposal_period: U64,
// Bond for claiming a bounty.
pub bounty_bond: U128,
// Period in which giving up on bounty is not punished.
pub bounty_forgiveness_period: U64,
}
// Versioned policy
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug, PartialEq))]
#[serde(crate = "near_sdk::serde", untagged)]
pub enum VersionedPolicy {
// Default policy with given accounts as council.
Default(Vec<AccountId>),
Current(Policy),
}
// Function call arguments
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct ActionCall {
method_name: String,
args: Base64VecU8,
deposit: U128,
gas: U64,
}
// Bounty information.
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct Bounty {
/// Description of the bounty.
pub description: String,
/// Token the bounty will be paid out.
/// Can be "" for $NEAR or a valid account id.
pub token: OldAccountId,
/// Amount to be paid out.
pub amount: U128,
/// How many times this bounty can be done.
pub times: u32,
/// Max deadline from claim that can be spend on this bounty.
pub max_deadline: U64,
}
// Info about factory that deployed this contract and if auto-update is allowed
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct FactoryInfo {
pub factory_id: AccountId,
pub auto_update: bool,
}
// Function call arguments
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub struct PolicyParameters {
pub proposal_bond: Option<U128>,
pub proposal_period: Option<U64>,
pub bounty_bond: Option<U128>,
pub bounty_forgiveness_period: Option<U64>,
}
// Votes recorded in the proposal
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, Debug)]
#[serde(crate = "near_sdk::serde")]
pub enum Vote {
Approve = 0x0,
Reject = 0x1,
Remove = 0x2,
}
// Configuration of the DAO
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, Debug)]
#[serde(crate = "near_sdk::serde")]
pub struct Config {
// Name of the DAO.
pub name: String,
// Purpose of this DAO.
pub purpose: String,
// Generic metadata. Can be used by specific UI to store additional data.
// This is not used by anything in the contract.
pub metadata: Base64VecU8,
}
// Kinds of proposals, doing different action
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
#[cfg_attr(not(target_arch = "wasm32"), derive(Clone, Debug))]
#[serde(crate = "near_sdk::serde")]
pub enum ProposalKind {
// Change the DAO config.
ChangeConfig { config: Config },
// Change the full policy.
ChangePolicy { policy: VersionedPolicy },
// Add member to given role in the policy. This is short cut to updating the whole policy.
AddMemberToRole { member_id: AccountId, role: String },
// Remove member to given role in the policy. This is short cut to updating the whole policy.
RemoveMemberFromRole { member_id: AccountId, role: String },
// Calls `receiver_id` with list of method names in a single promise.
// Allows this contract to execute any arbitrary set of actions in other contracts.
FunctionCall {
receiver_id: AccountId,
actions: Vec<ActionCall>,
},
// Upgrade this contract with given hash from blob store.
UpgradeSelf { hash: Base58CryptoHash },
// Upgrade another contract, by calling method with the code from given hash from blob store.
UpgradeRemote {
receiver_id: AccountId,
method_name: String,
hash: Base58CryptoHash,
},
// Transfers given amount of `token_id` from this DAO to `receiver_id`.
// If `msg` is not None, calls `ft_transfer_call` with given `msg`. Fails if this base token.
// For `ft_transfer` and `ft_transfer_call` `memo` is the `description` of the proposal.
Transfer {
// Can be "" for $NEAR or a valid account id.
token_id: OldAccountId,
receiver_id: AccountId,
amount: U128,
msg: Option<String>,
},
// Sets staking contract. Can only be proposed if staking contract is not set yet.
SetStakingContract { staking_id: AccountId },
// Add new bounty.
AddBounty { bounty: Bounty },
// Indicates that given bounty is done by given user.
BountyDone {
bounty_id: u64,
receiver_id: AccountId,
},
// Just a signaling vote, with no execution.
Vote,
// Change information about factory and auto update.
FactoryInfoUpdate { factory_info: FactoryInfo },
// Add new role to the policy. If the role already exists, update it. This is short cut to updating the whole policy.
ChangePolicyAddOrUpdateRole { role: RolePermission },
// Remove role from the policy. This is short cut to updating the whole policy.
ChangePolicyRemoveRole { role: String },
// Update the default vote policy from the policy. This is short cut to updating the whole policy.
ChangePolicyUpdateDefaultVotePolicy { vote_policy: VotePolicy },
// Update the parameters from the policy. This is short cut to updating the whole policy.
ChangePolicyUpdateParameters { parameters: PolicyParameters },
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct ProposalInput {
/// Description of this proposal.
pub description: String,
/// Kind of proposal with relevant information.
pub kind: ProposalKind,
}
// Validator interface, for cross-contract calls
#[ext_contract(ext_dao_contract)]
trait ExternalDaoContract {
fn add_proposal(&mut self, proposal: ProposalInput) -> Promise;
}
// Implement the contract structure
#[near_bindgen]
impl Contract {
#[payable]
pub fn create_proposal(&mut self, proposal: ProposalInput) -> Promise {
let promise = ext_dao_contract::ext(self.dao_contract.clone())
.with_attached_deposit(env::attached_deposit())
.with_static_gas(Gas(5*TGAS))
.add_proposal(proposal);
return promise.then( // Create a promise to callback query_greeting_callback
Self::ext(env::current_account_id())
.with_static_gas(Gas(50*TGAS))
.external_proposal_callback()
)
}
#[private] // Public - but only callable by env::current_account_id()
pub fn external_proposal_callback(&self, #[callback_result] call_result: Result<u64, PromiseError>) -> Option<u64> {
if call_result.is_err() {
log!("There was an error contacting external contract");
return None;
}
// Return the proposal id
let id = call_result.unwrap();
return Some(id);
}
}
``` |
# Injected Wallets
## Summary
Standard interface for injected wallets.
## Motivation
dApps are finding it increasingly difficult to support the ever expanding choice of wallets due to their wildly different implementations. While projects such as [Wallet Selector](https://github.com/near/wallet-selector) attempt to mask this problem, it's clear the ecosystem requires a standard that will not only benefit dApps but make it easier for established wallets to support NEAR.
## Rationale and alternatives
At its most basic, a wallet contains key pairs required to sign messages. This standard aims to define an API (based on our learning from [Wallet Selector](https://github.com/near/wallet-selector)) that achieves this requirement through a number of methods exposed on the `window` object.
The introduction of this standard makes it possible for `near-api-js` to become wallet-agnostic and eventually move away from the high amount of coupling with NEAR Wallet. It simplifies projects such as [Wallet Selector](https://github.com/near/wallet-selector) that must implement various abstractions to normalise the different APIs before it can display a modal for selecting a wallet.
This standard takes a different approach to a wallet API than other blockchains such as [Ethereum's JSON-RPC Methods](https://docs.metamask.io/guide/rpc-api.html#ethereum-json-rpc-methods). Mainly, it rejects the `request` abstraction that feels unnecessary and only adds to the complexity both in terms of implementation and types. Instead, it exposes various methods directly on the top-level object that also improves discoverability.
There have been many iterations of this standard to help inform what we consider the "best" approach right now for NEAR. Below is a summary of the key design choices:
### Single account vs. multiple account
Almost every wallet implementation in NEAR used a single account model until we began integrating with [WalletConnect](https://walletconnect.com/). In WalletConnect, sessions can contain any number of accounts that can be modified by the dApp or wallet. The decision to use a multiple account model was influenced by the following reasons:
- It future-proofs the API even if wallets (such as MetaMask) only support a single "active" account.
- Other blockchains such as [Ethereum](https://docs.metamask.io/guide/rpc-api.html#eth-requestaccounts) implement this model.
- Access to multiple accounts allow dApps more freedom to improve UX as users can seamlessly switch between accounts.
- Aligns with WalletConnect via the [Bridge Wallet Standard](./BridgeWallets.md).
### Storage of key pairs for FunctionCall access keys in dApp context vs. wallet context
- NEAR's unique concept of `FunctionCall` access keys allow for the concept of 'signing in' to a dApp using your wallet. 'Signing In' to a dApp is accomplished by adding `FunctionCall` type access key that the dApp owns to the account that the user is logging in as.
- Once a user has 'signed in' to a dApp, the dApp can then use the keypair that it owns to execute transactions without having to prompt the user to route and approve those transactions through their wallet.
- `FunctionCall` access keys have a limited quota that can only be used to pay for gas fees (typically 0.25 NEAR) and can further be restricted to only be allowed to call _specific methods_ on one **specific** smart contract.
- This allows for an ideal user experience for dApps that require small gas-only transactions regularly while in use. Those transactions can be done without interrupting the user experience by requiring them to be approved through their wallet. A great example of this is evident in gaming use-cases -- take a gaming dApp where some interactions the user makes must write to the blockchain as they do common actions in the game world. Without the 'sign in' concept that provides the dApp with its own limited usage key, the user might be constantly interrupted by needing to approve transactions on their wallet as they perform common actions. If a player has their account secured with a ledger, the gameplay experience would be constantly interrupted by prompts to approve transactions on their ledger device! With the 'sign in' concept, the user will only intermittently need to approve transactions to re-sign-in, when the quota that they approved for gas usage during their last login has been used up.
- Generally, it is recommended to only keep `FullAccess` keys in wallet scope and hidden from the dApp consumer. `FunctionCall` type keys should be generated and owned by the dApp, and requested to be added using the `signIn` method. They should **not** be 'hidden' inside the wallet in the way that `FullAccess` type keys are.
## Specification
Injected wallets are typically browser extensions that implement the `Wallet` API (see below). References to the currently available wallets are tracked on the `window` object. To avoid namespace collisions and easily detect when they're available, wallets must mount under their own key of the object `window.near` (e.g. `window.near.sender`).
**NOTE: Do not replace the entire `window.near` object with your wallet implementation, or add any objects as properties of the `window.near` object that do not conform to the Injected Wallet Standard**
At the core of a wallet are [`signTransaction`](#signtransaction) and [`signTransactions`](#signtransactions). These methods, when given a [`TransactionOptions`](#wallet-api) instance, will prompt the user to sign with a key pair previously imported (with the assumption it has [`FullAccess`](https://nomicon.io/DataStructures/AccessKey) permission).
In most cases, a dApp will need a reference to an account and associated public key to construct a [`Transaction`](https://nomicon.io/RuntimeSpec/Transactions). The [`connect`](#connect) method helps solve this issue by prompting the user to select one or more accounts they would like to make visible to the dApp. When at least one account is visible, the wallet considers the dApp [`connected`](#connected) and they can access a list of [`accounts`](#accounts) containing an `accountId` and `publicKey`.
For dApps that often sign gas-only transactions, [`FunctionCall`](https://nomicon.io/DataStructures/AccessKey#accesskeypermissionfunctioncall) access keys can be added/deleted for one or more accounts using the [`signIn`](#signin) and [`signOut`](#signout) methods. While this functionality could be achieved with [`signTransactions`](#signtransactions), it suggests a direct intention that a user wishes to sign in/out of a dApp's smart contract.
### Wallet API
Below is the entire API for injected wallets. It makes use of `near-api-js` to enable interoperability with dApps that will already use it for constructing transactions and communicating with RPC endpoints.
```ts
import { transactions, utils } from "near-api-js";
interface Account {
accountId: string;
publicKey: utils.PublicKey;
}
interface Network {
networkId: string;
nodeUrl: string;
}
interface SignInParams {
permission: transactions.FunctionCallPermission;
account: Account;
}
interface SignInMultiParams {
permissions: Array<transactions.FunctionCallPermission>;
account: Account;
}
interface SignOutParams {
accounts: Array<Account>;
}
interface TransactionOptions {
receiverId: string;
actions: Array<transactions.Action>;
signerId?: string;
}
interface SignTransactionParams {
transaction: TransactionOptions;
}
interface SignTransactionsParams {
transactions: Array<TransactionOptions>;
}
interface Events {
accountsChanged: { accounts: Array<Account> };
}
interface ConnectParams {
networkId: string;
}
type Unsubscribe = () => void;
interface Wallet {
id: string;
connected: boolean;
network: Network;
accounts: Array<Account>;
supportsNetwork(networkId: string): Promise<boolean>;
connect(params: ConnectParams): Promise<Array<Account>>;
signIn(params: SignInParams): Promise<void>;
signInMulti(params: SignInMultiParams): Promise<void>;
signOut(params: SignOutParams): Promise<void>;
signTransaction(
params: SignTransactionParams
): Promise<transactions.SignedTransaction>;
signTransactions(
params: SignTransactionsParams
): Promise<Array<transactions.SignedTransaction>>;
disconnect(): Promise<void>;
on<EventName extends keyof Events>(
event: EventName,
callback: (params: Events[EventName]) => void
): Unsubscribe;
off<EventName extends keyof Events>(
event: EventName,
callback?: () => void
): void;
}
```
#### Properties
##### `id`
Retrieve the wallet's unique identifier.
```ts
const { id } = window.near.wallet;
console.log(id); // "wallet"
```
##### `connected`
Determine whether we're already connected to the wallet and have visibility of at least one account.
```ts
const { connected } = window.near.wallet;
console.log(connected); // true
```
##### `network`
Retrieve the currently selected network.
```ts
const { network } = window.near.wallet;
console.log(network); // { networkId: "testnet", nodeUrl: "https://rpc.testnet.near.org" }
```
##### `accounts`
Retrieve all accounts visible to the dApp.
```ts
const { accounts } = window.near.wallet;
console.log(accounts); // [{ accountId: "test.testnet", publicKey: PublicKey }]
```
#### Methods
##### `connect`
Request visibility for one or more accounts from the wallet. This should explicitly prompt the user to select from their list of imported accounts. dApps can use the `accounts` property once connected to retrieve the list of visible accounts.
> Note: Calling this method when already connected will allow users to modify their selection, triggering the 'accountsChanged' event.
```ts
const accounts = await window.near.wallet.connect();
```
##### `signTransaction`
Sign a transaction. This request should require explicit approval from the user.
```ts
import { transactions, providers, utils } from "near-api-js";
// Retrieve accounts (assuming already connected) and current network.
const { network, accounts } = window.near.wallet;
// Setup RPC to retrieve transaction-related prerequisites.
const provider = new providers.JsonRpcProvider({ url: network.nodeUrl });
const signedTx = await window.near.wallet.signTransaction({
transaction: {
signerId: accounts[0].accountId,
receiverId: "guest-book.testnet",
actions: [
transactions.functionCall(
"addMessage",
{ text: "Hello World!" },
utils.format.parseNearAmount("0.00000000003"),
utils.format.parseNearAmount("0.01")
),
],
},
});
// Send the transaction to the blockchain.
await provider.sendTransaction(signedTx);
```
##### `signTransactions`
Sign a list of transactions. This request should require explicit approval from the user.
```ts
import { transactions, providers, utils } from "near-api-js";
// Retrieve accounts (assuming already connected) and current network.
const { network, accounts } = window.near.wallet;
// Setup RPC to retrieve transaction-related prerequisites.
const provider = new providers.JsonRpcProvider({ url: network.nodeUrl });
const signedTxs = await window.near.wallet.signTransactions({
transactions: [
{
signerId: accounts[0].accountId,
receiverId: "guest-book.testnet",
actions: [
transactions.functionCall(
"addMessage",
{ text: "Hello World! (1/2)" },
utils.format.parseNearAmount("0.00000000003"),
utils.format.parseNearAmount("0.01")
),
],
},
{
signerId: accounts[0].accountId,
receiverId: "guest-book.testnet",
actions: [
transactions.functionCall(
"addMessage",
{ text: "Hello World! (2/2)" },
utils.format.parseNearAmount("0.00000000003"),
utils.format.parseNearAmount("0.01")
),
],
},
],
});
for (let i = 0; i < signedTxs.length; i += 1) {
const signedTx = signedTxs[i];
// Send the transaction to the blockchain.
await provider.sendTransaction(signedTx);
}
```
##### `disconnect`
Remove visibility of all accounts from the wallet.
```ts
await window.near.wallet.disconnect();
```
##### `signIn`
Add one `FunctionCall` access key for one or more accounts. This request should require explicit approval from the user.
```ts
import { utils } from "near-api-js";
// Retrieve the list of accounts we have visibility of.
const { accounts } = window.near.wallet;
// Request FunctionCall access to the 'guest-book.testnet' smart contract for each account.
await window.near.wallet.signIn({
permission: {
receiverId: "guest-book.testnet",
methodNames: [],
},
account: {
accountId: accounts[0].accountId,
publicKey: utils.KeyPair.fromRandom("ed25519").getPublicKey(),
},
});
```
##### `signInMulti`
Add multiple `FunctionCall` access keys for one or more accounts. This request should require explicit approval from the user.
```ts
import { utils } from "near-api-js";
// Retrieve the list of accounts we have visibility of.
const { accounts } = window.near.wallet;
// Request FunctionCall access to the 'guest-book.testnet' and 'guest-book2.testnet' smart contract for each account.
await window.near.wallet.signInMulti({
permissions: [
{
receiverId: "guest-book.testnet",
methodNames: [],
},
{
receiverId: "guest-book2.testnet",
methodNames: [],
},
],
account: {
accountId: accounts[0].accountId,
publicKey: utils.KeyPair.fromRandom("ed25519").getPublicKey(),
},
});
```
##### Benefits
This NEP will optimize UX for multi contract DApps and avoid multiple redirects. These are more and more common in the ecosystem and this NEP will benefit the UX for those DApps.
##### Concerns
- The currently available keystores will have to catch up in order to support multiple keys per account
- We should add the new method to the Wallet interface for clarity in the NEP doc
##### `signOut`
Delete `FunctionCall` access key(s) for one or more accounts. This request should require explicit approval from the user.
```ts
import { utils, keyStores } from "near-api-js";
// Setup keystore to retrieve locally stored FunctionCall access keys.
const keystore = new keyStores.BrowserLocalStorageKeyStore();
// Retrieve accounts (assuming already connected) and current network.
const { network, accounts } = window.near.wallet;
// Remove FunctionCall access (previously granted via signIn) for each account.
await window.near.wallet.signOut({
accounts: await Promise.all(
accounts.map(async ({ accountId }) => {
const keyPair = await keystore.getKey(network.networkId, accountId);
return {
accountId,
publicKey: keyPair.getPublicKey(),
};
})
),
});
```
#### Events
##### `accountsChanged`
Triggered whenever accounts are updated (e.g. calling `connect` or `disconnect`).
```ts
window.near.wallet.on("accountsChanged", ({ accounts }) => {
console.log("Accounts Changed", accounts);
});
```
|
---
id: quick-reference
title: Using JavaScript API to interact with NEAR
sidebar_label: Using JavaScript API
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
## Quick Reference
- [Installation](#install)
- [Interacting with the Wallet](naj-wallet.md)
- [Accounts](naj-account.md)
- [Contracts](naj-contract.md)
- [Utilities](naj-utils.md)
## What is `near-api-js`
`near-api-js` is a complete library to interact with the NEAR blockchain. You can use it in the browser, or in Node.js runtime.
You'll typically first create a connection to NEAR with [`connect`](#connect) using a [`KeyStore`](#key-store).
With the connection object you now can:
- Interact with the [Wallet](naj-wallet.md) in a browser.
- Instantiate an [Account](naj-account.md) object to:
- Send tokens
- Deploy contracts
- Inspect, create or delete accounts
- Manage keys for accounts.
- Instantiate a [Contract](naj-contract.md) object to call smart contract methods.
The library also contains some [utility functions](naj-utils.md).
:::tip
To quickly get started with integrating NEAR in a web browser, read our [Web Frontend integration](/build/web3-apps/integrate-contracts) article.
:::
:::info
Note the difference between `near-api-js` and `near-sdk-js`:
The JavaScript _SDK_ is a library for developing smart contracts. It contains classes and functions you use to write your smart contract code.
The JavaScript _API_ is a complete library for all possible commands to interact with NEAR. It’s a wrapper for the RPC endpoints, a library to interact with NEAR Wallet in the browser, and a tool for keys management.
:::
---
## Install {#install}
Include `near-api-js` as a dependency in your package.
```bash
npm i --save near-api-js
```
## Import {#import}
You can use the API library in the browser, or in Node.js runtime. Some features are available only in one of the environments.
For example, the `WalletConnection` is only for the browser, and there are different `KeyStore` providers for each environment.
<Tabs>
<TabItem value="Browser" label="Browser" default>
```js
import * as nearAPI from "near-api-js";
```
</TabItem>
<TabItem value="Node" label="Node">
```js
const nearAPI = require("near-api-js");
```
</TabItem>
</Tabs>
## Key Store {#key-store}
If you sign transactions, you need to create a _Key Store_. In the browser, the LocalStorage KeyStore will be used once you ask your user to Sign In with the Wallet.
<Tabs>
<TabItem value="browser" label="Using Browser" default>
```js
// creates keyStore using private key in local storage
const { keyStores } = nearAPI;
const myKeyStore = new keyStores.BrowserLocalStorageKeyStore();
```
[<span className="typedoc-icon typedoc-icon-class"></span> Class `BrowserLocalStorageKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores_browser.browser_local_storage_key_store.BrowserLocalStorageKeyStore.html)
</TabItem>
<TabItem value="dir" label="Using Credentials Directory">
```js
// creates a keyStore that searches for keys in .near-credentials
// requires credentials stored locally by using a NEAR-CLI command: `near login`
// https://docs.near.org/tools/cli#near-login
const { keyStores } = nearAPI;
const homedir = require("os").homedir();
const CREDENTIALS_DIR = ".near-credentials";
const credentialsPath = require("path").join(homedir, CREDENTIALS_DIR);
const myKeyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);
```
[<span className="typedoc-icon typedoc-icon-class"></span> Class `UnencryptedFileSystemKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores_node.unencrypted_file_system_keystore.UnencryptedFileSystemKeyStore.html)
</TabItem>
<TabItem value="file" label="Using a File">
```js
// creates keyStore from a provided file
// you will need to pass the location of the .json key pair
const { KeyPair, keyStores } = require("near-api-js");
const fs = require("fs");
const homedir = require("os").homedir();
const ACCOUNT_ID = "near-example.testnet"; // NEAR account tied to the keyPair
const NETWORK_ID = "testnet";
// path to your custom keyPair location (ex. function access key for example account)
const KEY_PATH = "/.near-credentials/near-example-testnet/get_token_price.json";
const credentials = JSON.parse(fs.readFileSync(homedir + KEY_PATH));
const myKeyStore = new keyStores.InMemoryKeyStore();
myKeyStore.setKey(
NETWORK_ID,
ACCOUNT_ID,
KeyPair.fromString(credentials.private_key)
);
```
[<span className="typedoc-icon typedoc-icon-class"></span> Class `InMemoryKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores.in_memory_key_store.InMemoryKeyStore.html)
[<span className="typedoc-icon typedoc-icon-class"></span> Class `KeyPair`](https://near.github.io/near-api-js/classes/_near_js_crypto.key_pair.KeyPair.html)
</TabItem>
<TabItem value="key" label="Using a private key string">
```js
// creates keyStore from a private key string
// you can define your key here or use an environment variable
const { keyStores, KeyPair } = nearAPI;
const myKeyStore = new keyStores.InMemoryKeyStore();
const PRIVATE_KEY =
"by8kdJoJHu7uUkKfoaLd2J2Dp1q1TigeWMG123pHdu9UREqPcshCM223kWadm";
// creates a public / private key pair using the provided private key
const keyPair = KeyPair.fromString(PRIVATE_KEY);
// adds the keyPair you created to keyStore
await myKeyStore.setKey("testnet", "example-account.testnet", keyPair);
```
[<span className="typedoc-icon typedoc-icon-class"></span> Class `InMemoryKeyStore`](https://near.github.io/near-api-js/classes/_near_js_keystores.in_memory_key_store.InMemoryKeyStore.html)
[<span className="typedoc-icon typedoc-icon-class"></span> Class `KeyPair`](https://near.github.io/near-api-js/classes/_near_js_crypto.key_pair.KeyPair.html)
</TabItem>
</Tabs>
## Connecting to NEAR {#connect}
The object returned from `connect` is your entry-point for all commands in the API.
To sign a transaction you'll need a [`KeyStore`](#key-store) to create a connection.
<Tabs>
<TabItem value="testnet" label="TestNet" default>
```js
const { connect } = nearAPI;
const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore, // first create a key store
nodeUrl: "https://rpc.testnet.near.org",
walletUrl: "https://testnet.mynearwallet.com/",
helperUrl: "https://helper.testnet.near.org",
explorerUrl: "https://testnet.nearblocks.io",
};
const nearConnection = await connect(connectionConfig);
```
</TabItem>
<TabItem value="mainnet" label="MainNet">
```js
const { connect } = nearAPI;
const connectionConfig = {
networkId: "mainnet",
keyStore: myKeyStore, // first create a key store
nodeUrl: "https://rpc.mainnet.near.org",
walletUrl: "https://wallet.mainnet.near.org",
helperUrl: "https://helper.mainnet.near.org",
explorerUrl: "https://nearblocks.io",
};
const nearConnection = await connect(connectionConfig);
```
</TabItem>
<TabItem value="localnet" label="LocalNet">
```js
const { connect } = nearAPI;
const connectionConfig = {
networkId: "local",
nodeUrl: "http://localhost:3030",
walletUrl: "http://localhost:4000/wallet",
};
const nearConnection = await connect(connectionConfig);
```
</TabItem>
</Tabs>
[<span className="typedoc-icon typedoc-icon-module"></span> Module `connect`](https://near.github.io/near-api-js/modules/near_api_js.connect.html)
|
---
description: Astro DAO Factory aka Astro DAO of DAOs
title: Astro DAO
---
# ✨ Astro DAO
### **Astro (SputnikDAO V2)**
[**Astro**](https://astrodao.com) builds on the foundations of SputnikDAO V1 and widely expands the functionality of DAOs built atop it.
Features shipped with Astro include:
* Flexible, role-based voting policies
* Stable coin payouts
* This reduces the uncertainty imposed by crypto volatility between proposal requests and payouts
* Polling system for governance
* Electing representatives
* Cross-DAO accountability 
* DAOs can serve as members of other DAOs
* DAOs can own each other's social tokens for shared investment in collaboration.
Astro truly is the next evolution of SputnikDAO and comes with a host of new features, more flexibility, and a friendly UI. 
With Astro, DAOs will be able to retain more autonomy and, importantly, cast the net further in regards to governance through increased flexibility and the introduction of governance tokens. 
Despite the revamped user experience and broadened feature set, the goal of Astro remains the same; to empower communities within the NEAR ecosystem.
With Astro you can discover existing DAOs, [launch your own DAO](./how-to-launch-a-dao.md), and participate in [DAO governance](./dao-governance.md).
All you need is a NEAR account to start using Astro.
|
---
id: environment
title: Environment
#sidebar_label: 🏞️ Environment
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
Every method execution has an environment associated with information such as:
1. Who called the method
2. How much money is attached to the call
3. How many computational resources are available
4. The current timestamp
5. Helper functions for Public Key derivation, for example
---
## Environment Variables
<Tabs className="language-tabs" groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
| Variable Name | SDK Variable | Description |
| ---------------------- | ----------------------------- | ------------------------------------------------------------------------------------ |
| Predecessor | `near.predecessorAccountId()` | Account ID that called this method |
| Current Account | `near.currentAccountId()` | Account ID of this smart contract |
| Signer | `near.signerAccountId()` | Account ID that signed the transaction leading to this execution |
| Attached Deposit | `near.attachedDeposit()` | Amount in NEAR attached to the call by the predecessor |
| Account Balance | `near.accountBalance()` | Balance of this smart contract (including Attached Deposit) |
| Prepaid Gas | `near.prepaidGas()` | Amount of gas available for execution |
| Timestamp | `near.blockTimestamp()` | Current timestamp (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC) |
| Current Epoch | `near.epochHeight()` | Current epoch in the blockchain |
| Block Index | `near.blockIndex()` | Current block index (a.k.a. block height) |
| Storage Used | `near.storageUsage()` | Current storage used by this smart contract |
| Used Gas | `near.usedGas()` | Amount of gas used for execution |
| Signer Public Key | `near.signerAccountPk()` | Sender Public Key |
| Account Locked Balance | `near.accountLockedBalance()` | Balance of this smart contract that is locked |
</TabItem>
<TabItem value="rust" label="🦀 Rust">
| Variable Name | SDK Variable | Description |
|------------------------|---------------------------------|--------------------------------------------------------------------------------------|
| Predecessor | `env::predecessor_account_id()` | Account ID that called this method |
| Current Account | `env::current_account_id()` | Account ID of this smart contract |
| Signer | `env::signer_account_id()` | Account ID that signed the transaction leading to this execution |
| Attached Deposit | `env::attached_deposit()` | Amount in NEAR attached to the call by the predecessor |
| Account Balance | `env::account_balance()` | Balance of this smart contract (including Attached Deposit) |
| Prepaid Gas | `env::prepaid_gas()` | Amount of gas available for execution |
| Timestamp | `env::block_timestamp()` | Current timestamp (number of non-leap-nanoseconds since January 1, 1970 0:00:00 UTC) |
| Current Epoch | `env::epoch_height()` | Current epoch in the blockchain |
| Block Index | `env::block_index()` | Current block index (a.k.a. block height) |
| Storage Used | `env::storage_usage()` | Current storage used by this smart contract in bytes |
| Storage Byte Cost | `env::storage_byte_cost()` | Current storage cost per byte in yoctoNEAR |
| Used Gas | `env::used_gas()` | Amount of gas used for execution |
| Signer Public Key | `env::signer_account_pk()` | Sender Public Key |
| Account Locked Balance | `env::account_locked_balance()` | Balance of this smart contract that is locked |
</TabItem>
</Tabs>
---
## Who is Calling? Who am I?
The environment gives you access to 3 important users: the `current_account`, the `predecessor`, and the `signer`.
### Current Account
The `current_account` contains the address in which your contract is deployed. This is very useful to implement ownership, e.g. making a public method only callable by the contract itself.
### Predecessor and Signer
The `predecessor` is the account that called the method in the contract. Meanwhile, the `signer` is the account that _signed_ the initial transaction.
During a simple transaction (no [cross-contract calls](../anatomy/crosscontract.md)) the `predecessor` is the same as the `signer`. For example, if **alice.near** calls **contract.near**, from the contract's perspective, **alice.near** is both the `signer` and the `predecessor`. However, if **contract.near** creates a [cross-contract call](../anatomy/crosscontract.md), then the `predecessor` changes down the line. In the example below, when **pool.near** executes, it would see **contract.near** as the `predecessor` and **alice.near** as the `signer`.
![img](https://miro.medium.com/max/1400/1*LquSNOoRyXpITQF9ugsDpQ.png)
*You can access information about the users interacting with your smart contract*
:::tip
In most scenarios you will **only need to know the predecessor**. However, there are situations in which the signer is very useful. For example, when adding [NFTs](../../5.primitives/nft.md) into [this marketplace](https://github.com/near-examples/nft-tutorial/blob/7fb267b83899d1f65f1bceb71804430fab62c7a7/market-contract/src/nft_callbacks.rs#L42), the contract checks that the `signer`, i.e. the person who generated the transaction chain, is the NFT owner.
:::
---
## Balances and Attached NEAR
The environment gives you access to 3 token-related parameters, all expressed in yoctoNEAR (1 Ⓝ = 10<sup>24</sup>yⓃ):
### Attached Deposit
`attached_deposit` represents the amount of yoctoNEAR the predecessor attached to the call.
This amount is **already deposited** in your contract's account, and is **automatically returned** to the `predecessor` if your **method panics**.
:::warning
If you make a [cross-contract call](../anatomy/crosscontract.md) and it panics, the funds are sent back to **your contract**. See how to handle this situation in the [callback section](../anatomy/crosscontract.md#failed-execution)
:::
### Account Balance
`account_balance` represents the balance of your contract (`current_account`).
It includes the `attached_deposit`, since it was deposited when the method execution started.
If the contract has any locked $NEAR, it will appear in `account_locked_balance`.
---
### Storage Used
`storage_used` represents the amount of [storage](../anatomy/storage.md) that is currently being used by your contract.
:::tip
If you want to know how much storage a structure uses, print the storage before and after storing it.
:::
---
## Telling the Time
The environment exposes three different ways to tell the pass of time, each representing a different dimension of the underlying blockchain.
### Timestamp
The `timestamp` attribute represents the approximated **UNIX timestamp** at which this call was executed. It quantifies time passing in a human way, enabling to check if a specific date has passed or not.
### Current Epoch
The NEAR blockchain groups blocks in [Epochs](../../../1.concepts/basics/epoch.md). The `current_epoch` attribute measures how many epochs have passed so far. It is very useful to coordinate with other contracts that measure time in epochs, such as the [validators](../../../1.concepts/basics/validators.md).
### Block Index
The `block_index` represents the index of the block in which this transaction will be added to the blockchain.
---
## Gas
Your contract has a **limited number of computational resources** to use on each call. Such resources are measured in [Gas](/concepts/protocol/gas).
Gas can be thought of as wall time, where 1 PetaGas (1_000 TGas) is ~1 second of compute time.
Each code instruction costs a certain amount of Gas, and if you run out of it, the execution halts with the error message `Exceeded the prepaid gas`.
The environment gives you access to two gas-related arguments: `prepaid_gas` and `used_gas`.
### Prepaid Gas
`prepaid_gas` represents the amount of Gas the `predecessor` attached to this call. It cannot exceed the limit 300TGas (300 * 10<sup>12</sup> Gas).
### Used Gas
`used_gas` contains the amount of Gas that has been used so far. It is useful to estimate the Gas cost of running a method.
:::warning
During [cross-contract calls](./crosscontract.md) always make sure the callback has enough Gas to fully execute.
:::
:::tip
If you already [estimated the Gas](../../../1.concepts/protocol/gas.md#estimating-costs-for-a-call) a method needs, you can ensure it never runs out of Gas by using `assert`
<Tabs className="language-tabs" groupId="code-tabs">
<TabItem value="rust" label="🦀 Rust">
```rust
const REQUIRED_GAS: Gas = Gas(20_000_000_000_000); // 20 TGas
assert!(env::prepaid_gas() >= REQUIRED_GAS, "Please attach at least 20 TGas");
```
</TabItem>
</Tabs>
:::
---
## Environment Functions
<Tabs className="language-tabs" groupId="code-tabs">
<TabItem value="js" label="🌐 JavaScript">
| Function Name | SDK method | Description |
|-----------------------|--------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| SHA 256 | `near.sha256(value)` | Hashes a sequence of bytes using sha256. |
| Keccak 256 | `near.keccak256(value)` | Hashes a sequence of bytes using keccak256. |
| Keccak 512 | `near.keccak512(value)` | Hashes a sequence of bytes using keccak512. |
| RIPEMD 160 | `near.ripemd160(value)` | Hashes the bytes using the RIPEMD-160 hash function. |
| EC Recover | `near.ecrecover(hash, sig, v, malleabilityFlag)` | Recovers an ECDSA signer address from a 32-byte message `hash` and a corresponding `signature` along with `v` recovery byte. Takes in an additional flag to check for malleability of the signature which is generally only ideal for transactions. Returns 64 bytes representing the public key if the recovery was successful. |
| Log String | `near.log(msg)` | Logs the string message. This message is stored on chain. |
| Validator Stake | `near.validatorStake(accountId)` | For a given account return its current stake. If the account is not a validator, returns 0. |
| Validator Total Stake | `near.validatorTotalStake()` | Returns the total stake of validators in the current epoch. |
</TabItem>
<TabItem value="rust" label="🦀 Rust">
| Function Name | SDK method | Description |
|-----------------------|---------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| SHA 256 | `env::sha256(value)` | Hashes a sequence of bytes using sha256. |
| Keccak 256 | `env::keccak256(value)` | Hashes a sequence of bytes using keccak256. |
| Keccak 512 | `env::keccak512(value)` | Hashes a sequence of bytes using keccak512. |
| SHA 256 (Array) | `env::sha256_array(value)` | Hashes the bytes using the SHA-256 hash function. This returns a 32 byte hash. |
| Keccak 256 (Array) | `env::keccak256_array(value)` | Hashes the bytes using the Keccak-256 hash function. This returns a 32 byte hash. |
| Keccak 512 (Array) | `env::keccak512_array(value)` | Hashes the bytes using the Keccak-512 hash function. This returns a 64 byte hash. |
| RIPEMD 160 (Array) | `env::ripemd160_array(value)` | Hashes the bytes using the RIPEMD-160 hash function. This returns a 20 byte hash. |
| EC Recover | `env::ecrecover(hash, signature, v, malleability_flag)` | Recovers an ECDSA signer address from a 32-byte message `hash` and a corresponding `signature` along with `v` recovery byte. Takes in an additional flag to check for malleability of the signature which is generally only ideal for transactions. Returns 64 bytes representing the public key if the recovery was successful. |
| Panic String | `env::panic_str(message)` | Terminates the execution of the program with the UTF-8 encoded message. |
| Log String | `env::log_str(message)` | Logs the string message. This message is stored on chain. |
| Validator Stake | `env::validator_stake(account_id)` | For a given account return its current stake. If the account is not a validator, returns 0. |
| Validator Total Stake | `env::validator_total_stake()` | Returns the total stake of validators in the current epoch. |
</TabItem>
</Tabs>
:::info
In the JS SDK, `throw new Error("message")` mimics the behavior of Rust's `env::panic_str("message")`.
:::
---
|
Orange DAO Selects NEAR Foundation as Web3 Startup Partner
COMMUNITY
March 31, 2022
NEAR Foundation is excited to announce that Orange DAO, a crypto collective created by Y Combinator alumni for backing Web3 startups, has selected NEAR as its preferred layer 1 blockchain.
In turn, NEAR Foundation will invest $15 million into Orange DAO to help support the founders who are building Web3 companies on the NEAR blockchain.
“We are thrilled to have been selected by some of the brightest minds in the world as the preferred layer1 chain on which Orange DAO members will want to build,” said Marieke Flament, CEO of the NEAR Foundation. “We know that community-driven innovation benefits everyone, and this partnership is simply another example of our mission in practice.”
Bringing startup accelerator expertise to NEAR
Although Y Combinator is not formally involved in the project, Orange DAO is currently made up entirely of YC alumni, including NEAR co-founder Alexander Skidanov. After starting with just a few dozen YC alums, Orange DAO has expanded in recent months to include over a thousand YC founders.
One of the world’s leading startup accelerators, YC has been integral in developing some of the fastest-growing and most valuable tech brands. Based in Mountain View, California, YC has backed over 3,300 companies for a combined valuation of $600B, including Airbnb, Stripe, Dropbox, Coinbase, Opensea, Twitch, and Reddit.
YC alums created Orange DAO as a venture structure to both identify and support young crypto startups currently building the future of the Web3 ecosystem.
Orange DAO is not the first foray into Web3 by YC founders. Back in 2017, hundreds of alumni created the Pioneer Fund, a more traditional venture vehicle, to back Web3 projects. By contrast, Orange DAO operates as a decentralized autonomous organization, using blockchain tech to help multiple users make collective decisions.
Why Orange DAO chose NEAR
Unlike other blockchain networks, NEAR offers Web3 software developers an extremely fast, secure, and low-cost protocol—by way of its unique Nightshade sharding approach—for building decentralized applications (dapps). NEAR’s protocol technology, as well as its bridges to other blockchains, and developer ecosystem proved highly attractive to Orange DAO’s founders.
The Orange DAO team will leverage NEAR’s strengths to back past, present, and aspiring Y Combinator founders. The DAO will do this by helping founders apply and get accepted into YC; providing pre- and post-YC funding; as well as mentoring founders and helping where possible with recruitment and customer acquisition.
NEAR Foundation’s funding will vest over four years, and the Foundation will also provide time and resources to support YC founders. |
NEAR in Hong Kong: Create Without Limits
COMMUNITY
March 29, 2023
NEAR is making a debut in Hong Kong as a Platinum Sponsor for the Hong Kong Web3 Festival, which will be held at the Hong Kong Convention and Exhibition Centre on April 12-15, 2023. This four-day event, hosted on five center stages across an area of about 9,000㎡, will see over 10,000 attendees, 300 distinguished industry speakers, about 100 Web3 projects, community partners and media partners around the world congregate to network, share, and learn through high-level content and panel discussions.
Web3 Festival will bring together the world’s brightest minds, top Web3 projects and leading venture capital firms presenting content-rich discussions and topics centered around Web3. Hong Kong regulatory representatives will also dive into and interpret the latest digital asset regulation policies. Top industry leaders such as CZ of Binance, Illia of NEAR Protocol, Juan of Filecoin, Dr. Xiao Feng of Wanxiang and Yat Siu of Animoca Brands are all expected to speak at the Festival.
Join us on April 14th 9:30am to 12:30pm (GMT+8) at NEAR in HK Meetup — a half-day mini summit with a full schedule of keynote speeches and panels to explore topics on NEAR as a BOS, Web3 social, NFTs, DeFi and more. The summit is hosted as one of the official side stages as part of the Web3 Festival at the Convention Centre. A number of remarkable NEAR speakers will join us in Hong Kong and share their insights around NEAR’s ecosystem development. While we are finalizing the details of the event, the list of guests below are expected to speak at the summit:
Illia Polosukhin – Co-Founder of NEAR Protocol and CEO of Pagoda
Robbie Lim – Head of BD, NEAR Foundation
Louis Liu – Founder & CEO, Octopus Network
Amos Zhang – Founder of MetaWeb Ventures and Early Contributor of NEAR Protocol
Bowen Shen – Co-Founder, Proximity Labs
Kenny Qi – Founder & CEO, Sender Wallet
Cox Zhang – Founder & CEO, Connect3
Ran Yi – Co-Founder of Orderly Network
Arjun Arora – COO, Orderly Network
Register for NEAR in HK Meetup
From April 12th – 15th, you can visit the NEAR booth during Hong Kong Web3 Festival and mingle with NEAR projects, community members, and other builders from the ecosystem.
To participate in the NEAR in HK Meetup, please register via Eventbrite and obtain a single day pass to the HK Web 3 Festival on April 14th (valued at $100 USD). The space is limited and open registration is available for the first 200 qualified registrants only. The remaining tickets will be distributed via various community giveaways and online events to our most loyal community members. |
---
sidebar_position: 3
title: "Payable Methods"
---
# Payable Methods
We can allow methods to accept a NEAR token transfer together with the function call. This is done so that contracts can define a fee in tokens that needs to be paid when they are used. By default the methods are not payable and they will throw an error if someone will attempt to attach tokens to them during the invocation. This is done for safety reasons, in case someone accidentally transfers tokens during the function call.
To declare a method as payable, use the `({ payableFunction: true })` decorator parameter within the [`NearBindgen` decorated contract class](../contract-structure/near-bindgen.md) as follows:
```js
@call({ payableFunction: true })
my_method({}) {
// ...
}
```
This will allow the `my_method` function to be called with NEAR Tokens attached to the call, transferring tokens to the contract.
Example:
```js
@NearBindgen({})
export class Contract {
@call({ payableFunction: true })
take_my_money({}) {
near.log("Thanks!");
}
@call({})
do_not_take_my_money({}) {
near.log("No thanks!");
}
}
```
is equivalent to:
```js
@NearBindgen({})
export class Contract {
@call({})
take_my_money({}) {
near.log("Thanks!");
}
@call({})
do_not_take_my_money({}) {
if (near.attachedDeposit() > BigInt(0)) {
throw new Error("Method do_not_take_my_money doesn't accept deposit");
}
near.log("No thanks!");
}
}
```
|
Near and RECUR to Make Building on Web3 Easy for Web2 Brands
NEAR FOUNDATION
February 23, 2023
Near Foundation is excited to announce a new integration with RECUR, a Web3 platform helping major enterprises launch innovative, digital collectible experiences. With RECUR Builder, an enterprise-grade SaaS, the company is making it easier than ever for projects of all sizes to seamlessly build, scale, and integrate Web3 experiences into their existing products, marketing stack, video games, and more.
By using RECUR Builder, Web2 brands and other projects can develop on-chain branded experiences that enable the purchase, collection, and resale of digital projects and collectibles, like NFTs and beyond. Beloved brands like Paramount, Hello Kitty, and Nickelodeon currently work with RECUR to create chain-agnostic, bespoke experiences that make NFTs accessible through user-friendly experiences.
Near’s partnership with RECUR is part of its Web2.5 strategy, functioning as a bridge between the Web2 and Web3 worlds. This new integration will enable Near users to purchase, trade, and engage with RECUR’s extensive roster of licensed intellectual property, along with participation in upcoming mints and the option of ecosystem partnerships and NEAR-native mints.
Building and scaling Web3 experiences
RECUR prides itself on helping businesses and creators to build, distribute, and manage Web3 experiences at scale with enterprise-level tools. With a polished and super user-friendly interface, first-time buyers can purchase NFTs from major global and upcoming brands alike. With a Near Wallet, users can buy NFTs using credit cards, Apple Pay, Google Pay, and crypto (BTC, ETH, USDC).
“We are delighted to partner with Near to bring more Web2 companies into the world of Web3, supporting enterprises and fans with future-proof solutions via the RECUR platform,” says Zach Bruch, CEO of Recur. “We have always been passionate about building the future of web3 for everyone, and building alongside partners like Near is a crucial part of that journey.”
Marieke Flament, CEO of Near Foundation, noted that this partnership with RECUR is part of a larger commitment to making Web3 more accessible for everyone.
“[We] are excited about partnering with RECUR to empower brands and fans as they invent and explore new digital experiences,” says Flament. “Finding ways to make Web3 more user-friendly is a key part of unlocking the magic of this new chapter, and we believe this partnership with RECUR helps us to do that for many around the globe.” |
NEAR Foundation PR Roundup for March
NEAR FOUNDATION
March 31, 2023
The NEAR ecosystem is ending March on several extremely high notes, from partnerships and community events to unfolding initiatives.
NEAR strengthened its India and Southeast Asia presence, widened its gaming footprint — and of course, introduced the Blockchain Operating System (BOS).
Here are all the key happenings from a massive March.
NEAR unveils itself as the Blockchain Operating System (BOS)
Coindesk broke the biggest news of March, announcing NEAR as the Blockchain Operating System (BOS) at ETHDenver. NEAR will now be the common layer for browsing and discovering open web experiences in an industry-first category. The BOS makes NEAR the entry point for both web2 and web3, enabling easy web3 access and navigation for users and devs.
The BOS adds composable frontends to NEAR’s tech stack, simplifying onboarding and enhancing development from a collection of over 1,800 components. In only a few lines of code, builders from any ecosystem can create custom components and benefit from quick onboarding to help construct their web3 applications.
“The iOS provides developers a place to show their app in front of billions of users, and it gives them all the services and the infrastructure underneath to build,” NEAR co-founder Illia Polosukhin told CoinTelegraph. “We’re trying to give the platform underneath and let developers build.”
An alpha version of the BOS is now available for both users and developers to test at alpha.nearpages.wpengine.com.
Near at ETHDenver Highlights: the BOS, NEAR Day, and more
Exciting times for NEAR at ETHDenver, with a capacity crowd and jam-packed NEAR booth as the ecosystem engaged with builders from around the world. NEAR’s presence included a range of, including OnMachina on Web3 storage, Keypom for Web3 onboarding, and the Sweat Economy. Not to mention the BOS being first introduced to the world by Illia.
Let’s also not forget the over 1,000 people in attendance for NEAR Day, a one-day mini-summit for all things NEAR. Other big highlights out of ETHDenver included premium NFT platform Few & Far raising $30 million, the very first session unveiling the BOS, and Flowcarbon’s new carbon-market ecosystem built on the NEAR blockchain.
Arpit Sharma joins as Managing Director for eastward expansion
March also saw the appointment of Arpit Sharma as the Managing Director for India, South East Asia, and the Middle East regions. His focus will be on expanding the NEAR ecosystem’s presence in those regions, bringing a wealth of experience and expertise from a wide array of industries, solutions, and use cases.
Sharma’s web3 experience extends from the metaverse and NFTs to supply chain tracking and stablecoins. He sees enormous potential in regions and countries like India and the Middle East, believing that Web3 can be used to connect, collaborate and change the world. Regional hubs in India, Vietnam, and Korea should see a huge boost with Sharma on board.
Korean web3 gaming in focus with BORA and WEMADE
Next, NEAR set its sights firmly on the Korean gaming sector as Yahoo! Finance reported a new partnership with BORA gaming, the first of two such agreements. A subsidiary of METABORA, the two will explore new frontiers of web3 adoption in Asia and beyond. Both entities are affiliated with Kakao Games and bring a wealth of IP and gaming expertise into NEAR’s orbit.
Together, NEAR and METABORA will work to identify global IP-based web3 joint ventures. This means leveraging BORA’s existing gaming catalog and future development capabilities to bring fun and interactive web3 games to the world. And per Business Insider, the NEAR Korean Hub should be an enormous beneficiary as the partnership progresses.
On top of that, MarketWatch reported the new relationship between NEAR and global web3 gaming company WEMADE, also based out of South Korea. The partnership will leverage WEMAKE’s over 20 years of experience in the gaming industry, as well as its WEMIX 3.0 mainnet for advanced blockchain services.
“We’re thrilled to be partnering with WEMADE as part of our shared vision towards a decentralized future for the gaming industry,” added Marike Flament, CEO of NEAR. “By joining forces, we are confident in our ability to accelerate the development of cutting-edge solutions that meet the growing needs of gamers and developers in the web3 space.”
Popp’s web3 customer engagement platform launches on NEAR
Finally, small-to-medium-sized business owners are about to get exciting new tools for customer engagement using web3 and NEAR. Popp, a web3 customer engagement solution-as-a-service, announced that it will launch its white-label service exclusively on NEAR.
Popp lets businesses set up micro-tasks called “Popps,” which reward users when completed. Actions like retweets and reviews are rewarded with Popp’s native token that can be redeemed for vouchers, discounts, experiences, and more.
March was certainly a whirlwind month for NEAR, with the BOS taking the ecosystem into the next era of web3 usability. And not to mention NEAR Day at ETHDenver being a rousing success. NEAR will continue to forge ahead at full steam in April, but if we missed anything that happened in March the community should hear about, don’t hesitate to let us know!
|
Announcing NEAR Protocol’s MainNet Genesis
COMMUNITY
May 4, 2020
Update 20200806: See the end of this post for an update on project status.
NEAR’s mission is to enable community-driven innovation to benefit people around the world. The NEAR platform is a key piece of fulfilling this because it provides decentralized storage and compute that is secure enough to manage high value assets like money or identity and performant enough to make them useful for everyday people, putting the power of the Open Web in their hands.
Today, we are thrilled to announce a major step towards the fulfillment of that mission: Genesis for the NEAR Protocol MainNet has occurred and the network has already produced a million blocks.
This release, called “MainNet: POA”, is the first major release on the path to NEAR being the first fully sharded, fully operational proof-of-stake blockchain platform to run an open MainNet. This release represents the beginning of a multi-phase rollout of the platform over the upcoming months, as detailed in The Road to MainNet and Beyond and described in brief below.
The significance of MainNet: POA is that developers can now create production end-user-facing applications atop the smart contract platform running on the NEAR Protocol blockchain and the state of these applications is guaranteed to persist going forward, which crucially differentiates it from a TestNet release.
Because this is the POA release, there are some limitations to the functionality of the applications and the tooling of the platform on MainNet so it is intended for early adopters and sophisticated developers. NEAR’s TestNet, which runs the same code as MainNet but without any restrictions, allows developers to freely build and test their applications until they are ready for final deployment.
The following sections will cover exactly what this release contains and how it fits into the larger timeline of upcoming releases. It will help anyone — whether a developer, validator or potential end-user — understand how their experience and functionality are impacted by each of the steps on the way to the final Open MainNet release.
Contents:
About NEAR
Phases for Launching NEAR
Getting Started
About NEAR
Technically speaking, NEAR is a decentralized application platform built on top of a public, sharded, proof-of-stake blockchain. More importantly, NEAR is the backbone that powers the final stage of blockchain’s evolution, called the “Open Web”. In brief, you can think of blockchain technology as spanning three generations:
Open Money: Bitcoin showed the power of creating a global currency that anyone could interface with but there were limited opportunities to use this because of constraints on the performance of the blockchain and the limited computing layer on top of it.
Open Finance: Ethereum showed the power of expanding the financial primitive of Open Money by building a computing platform which could spawn new tokens and enable applications to permissionlessly access them. Despite lacking the performance or usability for general consumer adoption, Ethereum still proved that significant innovation could be achieved by making it easy for developers to combine financial building blocks to create valuable new products.
Open Web: When any data can be shared and composed between applications just like the financial primitives of Open Finance, the set of possible new business models and applications expands exponentially. No blockchain yet has been able to meet the requirements for this, however, because it must be performant enough to meet enormous demand, low cost enough to justify itself and usable enough by developers and consumers to allow user experiences on par with today’s web.
NEAR was built specifically with this final stage in mind. It doesn’t just provide the performance and usability upgrades which are necessary to drive the global adoption of Open Finance, it also has the scalability and low cost necessary to drive the even larger vision of the Open Web.
No blockchain of similar scope or sophistication has yet been released into full production. With the launch of NEAR’s Genesis Block, which officially started the MainNet blockchain on April 22, 2020, the project took the first major step along its own journey to having a fully decentralized, community-governed MainNet.
The ensuing rollout process, which will take place over the next several months, involves three distinct phases, as described below.
Phases for Launching NEAR
Generally speaking, projects like NEAR must build 2 key elements:
Below the surface: The underlying technical (blockchain) layer which provides the bare metal networking, virtual machine and data storage
Above the surface: The tooling and functionality which allows developers to easily build user-friendly applications.
Many blockchain projects have optimized for shipping the technical layer first but that means developers can’t actually build useful applications until smart contracts are implemented.
The goal of NEAR’s approach is to reverse the order of these two things, so the chain’s application-facing functionality is almost entirely in place from day 1, allowing developers to build actual production-ready apps even while the underlying chain infrastructure is still being progressively decentralized.
See each of the sections below for a more detailed investigation of the phases and their implications for key stakeholders.
Phase 0 – MainNet: POA
This initial phase of MainNet, which began with the recently implemented genesis block, allows builders to create production applications with guaranteed state preservation but is subject to restrictions on transfers and caveats that early tooling will be in a raw form.
These are the implications of MainNet POA:
Validators: The chain will initially be run by 4 nodes and a permissioned set of validators will be added during the course of this release. Inflation (and corresponding block rewards) will be set to zero so there is no dilution of stakes.
Patches or Rollbacks: Any issues experienced by the network, whether due to bugs or security, will be patched or rolled back as necessary while preserving the appropriate state for applications.
Developers: Because token transfers during this phase are restricted but both new account creation and app deployment require tokens, developers will need to work with the NEAR team to set up their accounts and implement their deployments. This process is similar to getting an API key. Contract Rewards for developers are enabled, so they can already earn 30% of the gas fees that are paid for the use of their contracts once deployed.
End Users: End users will be able to use applications on the network (as long as they don’t involve transfers of NEAR tokens between accounts) because using gas is not restricted. If these apps require NEAR accounts, this will need to be accomplished with some workarounds that can be coordinated with the team.
TestNet: Unlike MainNet, during this phase TestNet is full-featured and unrestricted so developers can test the full functionality of their applications in preparation for release during this or the later phases of MainNet.
Transitioning to Phase 1: This phase is ended and the next phase begins when the initial validating set from the Foundation hands off validation responsibility to a new set of validators sourced from within the community.
Phase 1 – MainNet: Restricted
In the Restricted phase, most of the changes occur below the surface so there will be few noticeable changes to developers or end-users. App developers will still be able to build, test and deploy production-ready applications on MainNet, just like during the POA phase. Tooling will continuously improve and end-users can still pay for gas to use applications but transfers of NEAR tokens are still restricted.
These are the implications of Restricted MainNet:
Validators: Instead of a small set of controlled nodes (as in the POA phase), the chain will be run across a large set of whitelisted validating nodes but inflation (block rewards) will still be inactive. This is a chance for validators to test-drive their nodes and fine tune their delegation setups. Though transfers are restricted, developers and end users will be able to delegate their tokens to validators for participation in the staking process.
Patches or Rollbacks: Because the chain will be run across a large set of validators, any bug- or security-related rollbacks or major patches will need to be coordinated with this group. The chain is still expected to maintain full security and uptime.
Developers: As with the POA phase, because token transfers are restricted and new account creation and app deployment require tokens, developers will need to work with a NEAR team to set up new accounts and implement their deployments. This process is similar to getting an API key. Contract Rewards for developers are enabled, so they can earn 30% of the gas fees that are paid for the use of their contracts once deployed.
End-Users: As with the POA phase, end users will be able to use applications on the network (as long as they don’t involve transfers of NEAR tokens between accounts) because using gas is not restricted.
TestNet: As with the POA phase, testnets that run alongside this MainNet will provide full functionality for applications as well as advances in the underlying technology and tooling.
Transitioning to Phase 2: This phase is ended and the next phase begins when a sufficiently large set of token holders votes that the conditions for successful open MainNet are fully in place and the network is ready to become completely open and unrestricted. This is similar to the approach used by Cosmos.
Phase 2 – MainNet: Open (Community-Governed)
The final phase of MainNet puts everything in place. The network is fully decentralized because it is being run on a large validator set which can be permissionlessly joined by anyone with enough stake. Applications have no restrictions on their functionality and NEAR tokens are free to be transferred. Developers can permissionlessy create accounts and deploy applications.
These are the implications of this Community-Governed (Open) Mainnet:
Validators: Anyone with sufficient stake (or delegated stake) can participate in running the network. Lockups will begin unlocking as normal in this phase.
Patches or Rollbacks: As with any properly decentralized network, updates to the chain are entirely subject to the decentralized governance process and adoption by validating nodes. This means that any bug- or security-related rollbacks or patches will need to be handled entirely through governance and, as with any decentralized network, no single party can provide guarantees about the performance or operational characteristics of the network.
Developers: Developers will be able to permissionlessly create accounts and deploy full-functionality applications. These activities will require tokens, which can be permissionlessly acquired via any mechanism available “in the wild”. Contract Rewards for developers are enabled, so they can earn 30% of the gas fees that are paid for the use of their contracts once deployed.
End Users: End users will be able to permissionlessly create accounts and use any applications that exist on the network.
TestNet: As before, TestNet will be full-featured and full-functionality. For more information on specific sub-networks and the anticipated forward-looking release cycle, refer to the Road to MainNet and Beyond post.
Ongoing Evolution: As a permissionless, open source network, anyone can contribute to the codebase. Future improvements and growth will be ultimately determined by the emergent will of the community and its adoption among validators. Financial support for ongoing development will be provided by the network’s Foundation Reward.
Getting Started
Everyone who has worked on getting NEAR to this point is extremely excited to see the community get more involved in every aspect of the network’s development, operation, and ecosystem development.
During this initial phase of MainNet, here are several ways to get your hands dirty:
Developers: Because TestNet is full-featured, you can build your app as normal! Check out the docs quickstart for information about how to do this and ask questions in the chat. If you are ready to deploy to MainNet, register for the Developer Program.
Validators: Whether you expect to validate with your own stake or receive delegation, you can start test-driving your setup and sign up for staking programs to participate in any upcoming ones. Similarly, if you are interested in purchasing tokens, be sure to sign up for the token list to hear news of any opportunities to do so.
Interested Contributors: If you run your own community and we can help out or if you are interested in helping out directly, learn about our community programs or ask questions in the chat.
Startup Founders: NEAR is a supporter of the Open Web Collective, a protocol-agnostic community of startup founders who are focused on building on the decentralized web. They provide education, networking and support during this process. Learn more and join at https://openwebcollective.com.
Business Leaders: If you are curious about how to integrate with NEAR or whether it might be a good fit for your business needs, reach out to [email protected].
Update 20200806:
We are currently in Phase 0, where the NF is running the network’s nodes.Phase I involves a transition to a decentralized group of third party validators.
This occurs in several steps:
The validators (who have been participating in the incentivized TestNet for months now) are promoted to MainNet and given accounts there.
At the same time, tokens are distributed to the recipients who should receive them so they can delegate these tokens to the validators. This activity will take some time because there are many recipients
Once the network has been determined to be sufficiently stable (which could be a week, or it could be more), the NF will spin down its nodes and Phase I officially begins.
The first and second steps are expected to begin by the end of August (though it is an engineering timeline and thus subject to change).The third step will depend a lot on what we see there, plus it has some dependencies on the ecosystem of validators, custodian partners and their customers, so it’s not really appropriate to put a date on it.
The transition to phase II requires the validators to signal their choice that they are ready to remove transfer restrictions on the network. This is similar to what Cosmos did. The NEAR team can’t determine when exactly this will occur. It might occur almost immediately after Phase I officially begins or it may occur long after — it is entirely up to the validators (and the stake which delegates to them).
As a final note, which you can read in the blog post https://pages.near.org/blog/near-mainnet-genesis/, there is no network inflation before Phase II, so anyone who is not participating in delegation or staking prior to Phase II is not missing anything other than the opportunity to test-drive your delegation and vote to advance to phase II. |
```bash
near view v2.keypom.near get_drop_supply_for_owner '{"account_id": "bob.near"}'
``` |
```js
import { Wallet } from './near-wallet';
const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
const FT_CONTRACT_ADDRESS = "ft.primitives.near";
const wallet = new Wallet({ createAccessKeyFor: FT_CONTRACT_ADDRESS });
await wallet.callMethod({
method: "ft_transfer",
contractId: FT_CONTRACT_ADDRESS,
args: {
receiver_id: KEYPOM_CONTRACT_ADDRESS,
amount: "1"
},
deposit: "1",
gas: "100000000000000"
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs groupId="nft-contract-tabs" className="file-tabs">
<TabItem value="NFT Primitive" label="Reference" default>
```js
import { Wallet } from './near-wallet';
const CONTRACT_ADDRESS = "nft.primitives.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'nft_transfer',
args: {
token_id: "1",
receiver_id: "bob.near"
},
contractId: CONTRACT_ADDRESS,
deposit: 1
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
</TabItem>
<TabItem value="Paras" label="Paras">
```js
import { Wallet } from './near-wallet';
const CONTRACT_ADDRESS = "x.paras.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'nft_transfer',
args: {
token_id: "490641",
receiver_id: "bob.near"
},
contractId: CONTRACT_ADDRESS,
deposit: 1
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
</TabItem>
<TabItem value="Mintbase" label="Mintbase">
```js
import { Wallet } from './near-wallet';
const CONTRACT_ADDRESS = "thomasettorreiv.mintbase1.near";
const wallet = new Wallet({ createAccessKeyFor: CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'nft_transfer',
args: {
token_id: "490641",
receiver_id: "bob.near"
},
contractId: CONTRACT_ADDRESS,
deposit: 1
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
:::tip
Check how to also do this using [`Mintbase JS`](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/sdk/transfer)
:::
</TabItem>
</Tabs>
|
```bash
near call v2.keypom.near create_drop '{"public_keys": <PUBLIC_KEYS>, "deposit_per_use": "10000000000000000000000"}' --depositYocto 23000000000000000000000 --gas 100000000000000 --accountId bob.near
``` |
---
id: minter
title: NFT minter
---
# NFT Minter
[![Demo](https://img.shields.io/badge/Demo-Visit%20Demo-brightgreen)](https://minter.mintbase.xyz/)
[![Deploy](https://img.shields.io/badge/Deploy-on%20Vercel-blue)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FMintbase%2Ftemplates%2Fblob%2Fmain%2Fminter)
This is a Next.js 14 frontend minter example that includes a simple interface from which you can mint nfts easily
![img](https://i.imgur.com/QDJPsAA.png)
:::tip Mintbase Templates
This is part of the [Mintbase Templates](https://templates.mintbase.xyz/), a collection of templates that you can use to scaffold your own project
:::
---
## Project Walkthrough
This is a simple minter example built on top of **Next.js 14** using some of [@mintbase-js](https://github.com/Mintbase/mintbase-js) packages.
*NOTE: As a standard on Mintbase as we use the latest versions of Next.js we recommend using pnpm, but the package manager is up to your personal choice.*
if you dont have a store you can [deploy a new contract](https://www.mintbase.xyz/launchpad/contracts/0) on our launchpad
---
## Pre-Setup
If you would like the minter to use your own NFT contract you can easily deploy one through the mintbase market UI, additionally if you want to open up minting to be available for any person you will need to connect it to a proxy contract
### Deploying a Near Contract on Mintbase:
1. Login on Mintbase and access [Contracts Page](https://www.mintbase.xyz/launchpad/contracts/0)
2. Click on New Contract
3. Choose Store Name (this will be the contract address to add on your minsta instance, this need to be added on the `process.env.NEXT_PUBLIC_NFT_CONTRACT_ADDRESS` environment variable) and Store Symbol
4. Proceed to transaction.
5. Succeeded
6. Go to Contract Settings
<hr class="subsection" />
### Add Proxy Minter Contract
1. Under Contract Settings go to Minters
2. add `0.drop.proxy.mintbase.near` (this is the contract address that need to be added on `process.env.NEXT_PUBLIC_PROXY_MINTER_CONTRACT_ADDRESS`), and click Add Minters.
3. Proceed to transaction.
4. Succeeded
<hr class="subsection" />
### Step 1: Get the wallet connection
This method will get the wallet instance used to send the mint transaction. To learn more about this, you can check our guide at [Wallet Connection Guide](https://docs.mintbase.xyz/dev/getting-started/add-wallet-connection-to-your-react-app).
```typescript
const getWallet = async () => {
try {
return await selector.wallet();
} catch (error) {
console.error("Failed to retrieve the wallet:", error);
throw new Error("Failed to retrieve the wallet");
}
};
```
<hr class="subsection" />
### Step 2: Use the onSubmit method
Get all the form data and use the onSubmit method to handle the minting process
```typescript
const onSubmit = async (data: SubmitData) => {
const wallet = await getWallet();
const reference = await uploadReference({
title: typeof data?.title === "string" ? data.title : "",
media: data?.media as unknown as File,
});
const file = uploadFile(data?.media as unknown as File);
await handleMint(
reference.id,
file,
activeAccountId as string,
wallet,
reference.media_url as string,
data.title
);
};
```
<hr class="subsection" />
### Step 3: Upload the NFT reference
The nft reference represents the offchain data which permanently stored on IPFS on Arweave in this case you can use [@mintbase-js/data](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/data) to easily upload it to arweave.
In this not only are we uploading an offchain JSON object which contains the media as well as the title but also uploading a separate media file to be included onchain.
[Learn more about how references work here](https://docs.mintbase.xyz/dev/getting-started/anatomy-of-a-non-fungible-token)
```typescript
const reference = await uploadReference({
title: typeof data?.title === "string" ? data.title : "",
media: data?.media as unknown as File,
});
const file = uploadFile(data?.media as unknown as File);
```
<hr class="subsection" />
### Step 4: Handling the mint
Here we start by configuring the callback which is the link and params to where the user will be redirected after minting after signing the mint transaction on the wallet.
In this case a number of params are included to be able to show a better success page.
The argument for calling the contracts "mint" function is then built. This transaction will be sent to the proxy contract which then calls the nft contracts nft_batch_mint method
```typescript
async function handleMint(
reference: string,
media: Promise<ArweaveResponse>,
activeAccountId: string,
wallet: Wallet,
mediaUrl: string,
nftTitle: string
) {
const callbackArgs = {
contractAddress: MintbaseWalletSetup.contractAddress.toString(),
amount: 1,
ref: `${reference}`,
mediaUrl: mediaUrl,
title: nftTitle,
};
if (reference) {
await wallet.signAndSendTransaction({
signerId: activeAccountId,
receiverId: proxyAddress,
callbackUrl: cbUrl(reference, callbackArgs),
actions: [
{
type: "FunctionCall",
params: {
methodName: "mint",
args: {
metadata: JSON.stringify({
reference,
media: (await media).id,
}),
nft_contract_id: MintbaseWalletSetup.contractAddress,
},
gas: "200000000000000",
deposit: "10000000000000000000000",
},
},
],
});
}
}
return { form, onSubmit, preview, setPreview };
};
```
This sums up the blockchain portion of the code
<hr class="subsection" />
### Setup
In the `minter/src/config/setup.ts` file, we define several key configurations for interacting with the Mintbase platform. This setup is crucial for ensuring that our application communicates correctly with Mintbase smart contracts.
---
## ENV Variables
- `proxyAddress`: This is the address of the proxy contract on Mintbase. It is either taken from the environment variable `NEXT_PUBLIC_PROXY_CONTRACT_ADDRESS` or defaults to `"0.minsta.proxy.mintbase.testnet"` if the environment variable is not set.
- `contractAddress`: The address of the minting contract. Similar to `proxyAddress`, it is sourced from `NEXT_PUBLIC_MINT_CONTRACT_ADDRESS` or defaults to `"test122212.mintspace2.testnet"`.
- `network`: Indicates the blockchain network we are interacting with. It defaults to `"testnet"` if `NEXT_PUBLIC_NETWORK` is not specified in the environment.
- `callbackUrl`: A URL used for callbacks, constructed dynamically based on the `network` variable. If we are on the testnet, it uses the testnet URL; otherwise, it defaults to the mainnet URL.
To customize these configurations for different environments, you can set the following environment variables in your `.env` file:
`NOTE: the env variables need to have the NEXT_PUBLIC_ on the variable name due to be available for the browser to process`
- `NEXT_PUBLIC_PROXY_CONTRACT_ADDRESS`: Your proxy contract address on Mintbase.
- `NEXT_PUBLIC_MINT_CONTRACT_ADDRESS`: Your mint contract address on Mintbase.
- `NEXT_PUBLIC_NETWORK`: The network you want to interact with (`"testnet"` or `"mainnet"`).
after that you can run
```bash
pnpm install
pnpm dev
```
---
## Extending
This project is setup using Next.js + @mintbase/js
You can use this project as a reference to build your own, and use or remove any library you think it would suit your needs.
:::info Get in touch
You can get in touch with the mintbase team using the following channels:
- Support: [Join the Telegram](https://tg.me/mintdev)
- Twitter: [@mintbase](https://twitter.com/mintbase)
::: |
The continued evolution of the NEAR Foundation
NEAR FOUNDATION
September 21, 2023
The NEAR Foundation’s vision is one of an Open Web, where users have true ownership of their data and assets, and are empowered to participate in value creation, ownership and governance opportunities in permissionless systems. The ultimate goal is to enable billions of users to participate in an Open Web.
To help achieve this, the NEAR Foundation strategy has been two-fold – one of top-down to attract prominent Web2 organizations into Web3, the other of bottoms-up to empower the ecosystem through the fostering of grassroots community – all of this being powered by the Blockchain Operating System and NEAR Protocol. The primary goal has been to grow users (MAU) so that more people can experience what Web3 can bring to them. Great progress has been made, with over 2.6m Monthly Active Users on NEAR protocol driven by this strategy, with NEAR protocol now as one of the top 5 most active blockchains driven by innovative partnerships such as Cosmose AI.
Over recent months, there have been discussions between NEAR Foundation leadership and the NEAR Foundation Council (NFC) on the strategic direction of the Foundation and the best way the Foundation can continue in its evolution to support the NEAR ecosystem in achieving this broader vision.
As part of this, Marieke Flament has elected to move into a council-only position to support the continued evolution of the Foundation. Chris Donovan, General Counsel of the Foundation, will step up as CEO and will work closely with the NFC and the broader ecosystem on the Foundation’s evolution plans. Chris has been with the Foundation for over a year since joining from Outlier Ventures and brings a wealth of experience in web3. In addition to her role on the NFC, Marieke will also stay on as a strategic advisor to Chris until the end of the year. There are no changes to the current strategy of the Foundation.
In a statement, Mona El Isa, Chairperson of the NFC remarked: “Marieke has been pivotal in all the incredible progress the NEAR ecosystem has made over the last two years, bringing NEAR to be one of the most active ecosystems in web3 and progressing the journey of the ecosystem towards decentralization. Amidst many critical industry and world events, Marieke has set the NEAR Foundation and the NEAR ecosystem on a solid pathway. I am excited to welcome Chris into his new role – I could think of no one better placed to continue the Foundation’s mission and wish him all the success.” |
MetaBUIDL Launch Highlights
COMMUNITY
September 2, 2021
TL:DR
MetaBUIDL is a global hackathon hosted by NEAR with a $1M prize pool.
NEAR powers a world where people control their money, power, and governance.
MetaBUIDL ushers in an era of “zero finance” where distributed computing invisibly powers all of our activities.
Check out talks from NEAR co-founder Illia Polosukhin, Atelier Ventures founder Li Jin, Richard Muirhead,Managing partner of Fabric Ventures and more!
MetaBUIDL is here! NEAR’s $1,000,000 competition for hackers and community members designed to kickstart the next generation of projects that will power the decentralized economy.
Taking place over 17 days online and across nine hack nodes including San Francisco, New York, Bogota, Lisbon, Kano, Nigeria, Mukachevo and Kyiv in Ukraine and two locations in China, MetaBUIDL is a front seat to what happens next.
As part of our kick off we invited a host of speakers to explore everything from the passion economy, NFTs and the rise of the metaverse.
Illia Opens the Show with the Open Web
But before all that, NEAR co-founder Illia Polosukhin introduced us to the open web, a “world where people control their money, power and governance.”
Illia also explored how NEAR has been a part of that journey, and why, most importantly, blockchain is just one part of this future. In order for the open web to really succeed, there needs to be a focus on shared ownership, proper incentivisation, and a roadmap to a more inclusive web.
➡️ Watch his talk here
When the Ownership Economy and the Passion Economy Collide
Next up, Illia took a deep dive into the passion economy with Li Jin, the founder and general partner of Atelier Ventures.
The passion economy is a place in which “people are leveraging different platforms and tools in order to make a living from their non-commoditized passions and skills,” said Jin.
This comes in contrast to the gig economy, which was all about monetising pre-commoditised tasks and services. The gig economy was a step forward in online work in that it gave more autonomy and freedom to workers, but fell short of allowing people to be their own boss and decide what work they wanted to do.
The two discussed the tensions between the creators in the web2 world and the owners of those platforms, and how web3 services, when done right, could create a symbiotic relationship whereby the platform and creator work collaboratively: bringing incentives for the two groups together for mutual benefit.
➡️ Watch their talk here
VCs and What Comes Next in Crypto
Next up we invited Richard Muirhead, managing partner at Fabric Ventures to explore crypto through a VC lens, the trends that are emerging and where the industry might head next.
“There’s this new wave of software weaponized to deal with the concept of ownership. Assets have become accessible, divisible and ownable through software,” says Muirhead.
One particular area of interest Muirhead has been focusing on is the pay to earn platforms like Axie Infinity and Yield Good Games and what happens when NFTs, gaming and opportunities to own a slice of the metaverse are combined.
When looking to the future, Muirhead sees finance’s role in crypto fading into the background.
“We’re heading to a world of zero finance – where transactions become invisibly embedded in all of our activities online. If you have a passion for a particular piece of content on YouTube, or preserving a particular part of the environment, finance should be in service of all of those activities. It should be invisible under those activities and be in the service of them.”
Muirhead believes social tokens and social movements in the crypto space are rapidly becoming indistinguishable from financial opportunities and sees a lot more growth ahead.
➡️ Watch their talk here
NFTs and the Broader Digital Economy
Lastly, but certainly not leastly check out our talk between Maria Shen, Partner of Electric Capital and Brady Dale, a journalist for The Defiant.
In this talk, Shen explores the evolution of crypto from programmable money, to programmable assets to where we are today; the explosion of financial use cases across the crypto sphere, in particular the marriage of NFTs and DeFi.
“While NFTs and DeFi have become interlinked, there’s still something missing,” says Shen. “There’s no liquidity for NFTs.” The solution? Fractionalisation.
“Fractionalisation is probably the best solution we’ve seen so far that solves this solution. “Take something that’s non-fungible, make it fungible via ERC-20s, and then allow them to plug into the DeFi stack,” says Shen.
The two explored examples of projects looking to unlock the next wave of NFTs. You’re not going to want to miss some of the projects they talk about.
➡️ Watch their talk here
And if you’ve missed out on the chance to be part of the hackathon, it’s not too late!
Join MetaBUIDL
About NEAR
NEAR Protocol is a high-performance blockchain platform for developing Open Web applications. Easy to build on and easy to use, NEAR will bridge the users of today’s internet to the blockchain-based web of the future.
NEAR Protocol is built by a world-class team of engineers and entrepreneurs, including world champions of ACM-ICPC, Google Code Jam, and TopCoder Open. NEAR is backed by top VCs such as A16Z, Pantera Capital, Electric Capital, Dragonfly Capital, Coinbase Ventures, Blockchain.com, and Baidu Ventures. |
```js
const ammContract = "v2.ref-finance.near";
const result = Near.call(
ammContract,
"swap",
{
actions: [
{
pool_id: 79,
token_in: "token.v2.ref-finance.near",
token_out: "wrap.near",
amount_in: "100000000000000000",
min_amount_out: "1",
},
],
},
300000000000000,
1
);
```
<details>
<summary>Example response</summary>
```json
"5019606679394603179450"
```
</details> |
---
id: indexers
title: QueryAPI Indexing Example
sidebar_label: Getting Started
---
With QueryAPI you can quickly create your own indexer by:
* Writing your own custom indexer function;
* Specifying the schema for your own custom hosted database and write to it with your indexer function;
* Retrieving that data through a GraphQL API.
:::tip
You can watch a complete video walkthrough of Query API [following this link](https://www.youtube.com/watch?v=VwO6spk8D58).
:::
:::info
NEAR QueryAPI is currently under development. Users who want to test-drive this solution need to be added to the allowlist before creating or forking QueryAPI indexers.
You can request access through [this link](http://bit.ly/near-queryapi-beta).
:::
## How it Works
QueryAPI works by:
1. Writing the indexer name to the blockchain, registering its creation;
2. Creating the tables as specified in the schema to the GraphQL database, exposing a GraphQL endpoint to query the data;
3. Spinning up a cloud process that runs your indexer function, writing to the GraphQL database;
You can access the [NEAR QueryAPI by following this link](https://near.org/dataplatform.near/widget/QueryApi.App).
This should take you to a dashboard that looks like this:
![QueryAPI Dashboard](/docs/assets/QAPIScreen.png)
:::tip Video Walkthrough
**Tip:** Watch the [QueryAPI widget introduction](https://www.youtube.com/watch?v=VwO6spk8D58&t=109s).
:::
## Creating an Indexer
Clicking on "Create New Indexer" will redirect you in-browser to a Component code editor that looks like this:
![QueryAPI Indexer Dashboard](/docs/assets/QAPIScreen2.png)
This is the interface through which you can create a new Indexer. On here you can specify:
* the filtering, transforming logic in `indexingLogic.js`
* the database schema in `schema.sql`
* the GraphQL queries in `GraphiQL`
* the indexer name on Indexer Name
* from which block to start indexing
### Design Workflow
To design and create your indexer, you can follow this recommended workflow:
1. Using [nearblocks.io](https://nearblocks.io), find transactions to smart contracts that you want to index
2. Take the block `height` and put it into the [Debug Mode filter](../query-api/index-function.md#local-debug-mode), open your browser's _Developer Console_, and hit <kbd>Play</kbd>
4. Inspect the block and write JavaScript code using [NEAR Lake Primitives](../lake-framework/building-indexers/primitives.md) to extract data from a `block` object. (This JS code will be your [`IndexingLogic.js`](#indexinglogicjs))
> **Tip:** Use `context.log` for debugging to ensure you are getting the right results
4. Add more blocks for debugging, or start following the blockchain to see how new blocks are handled
5. Create tables that you need to store the data using Postgres [CREATE table syntax](https://www.postgresql.org/docs/current/sql-createtable.html). (This SQL code will be your [`schema.sql`](#schemasql))
:::tip Video Walkthrough
**Tip:** Watch the [introduction to indexing functions](https://www.youtube.com/watch?v=VwO6spk8D58&t=411s).
:::
### `IndexingLogic.js`
The indexer code editor is pre-populated with a template that looks like this:
```js
import { Block } from "@near-lake/primitives";
/**
* Note: We only support javascript at the moment. We will support Rust, Typescript in a further release.
*/
/**
* getBlock(block, context) applies your custom logic to a Block on Near and commits the data to a database.
*
* Learn more about indexers here: https://docs.near.org/concepts/advanced/indexers
*
* @param {block} Block - A Near Protocol Block
* @param {context} - A set of helper methods to retrieve and commit state
*/
async function getBlock(block: Block, context) {
// Add your code here
const h = block.header().height;
await context.set("height", h);
}
```
This editor with this code shows the `indexingLogic.js` file that is selected. This logic in particular will perform the filtering of blockchain transactions, transforming and saving the data you specify to a GraphQL database you define in `schema.sql`.
:::info Saving data
You will likely want to save the data you capture from your indexer to your defined tables in the GraphQL database. You can do this easily by using the [`context.db`](../query-api/context.md#db) object [`insert`](../query-api/context.md#insert) method. For example, if you have a table called `transactions` with columns `id`, `sender`, `receiver`, `amount`, `block_height`, you can insert a mutation query for one new element in the table like this:
```js
const tx = {
block_height: h,
sender: "senderId",
receiver: "receiverId",
amount: 100,
};
await context.db.Transactions.insert(tx);
```
:::
:::info Using GraphQL mutations
You can also insert elements using GraphQL mutation queries in your `indexingLogic.js` file:
```js
await context.graphql(`
mutation MyMutation($transaction: some_table_insert_input!) {
insert_<ACCOUNT_NAME>_near_transactions_one(
object: $transaction
) {
affected_rows
}
}
`);
```
Creating GraphQL queries within strings can be difficult, especially considering that the table names vary depending on your indexer name and account ID. An easier way to do this would be by visiting the GraphQL Playground site and creating the queries there.
> **Tip:** watch the video on how to [create queries in Playground](https://www.youtube.com/watch?v=VwO6spk8D58&t=1207s).
:::
### `schema.sql`
This tab in the editor will be pre-populated with a template that looks like this:
```sql
CREATE TABLE "indexer_storage" (
"function_name" TEXT NOT NULL,
"key_name" TEXT NOT NULL,
"value" TEXT NOT NULL,
PRIMARY KEY ("function_name", "key_name")
);
```
This is the database schema that will be used to store the data you specify in `indexingLogic.js`. You can add more tables and columns to this schema as you see fit. They will be created as soon as you create the indexer.
Creating this default table will allow you to use the [`context.set`](../query-api/context.md#set) helper method to write data. It takes two arguments: a key argument that accepts a string and a value argument, which will be written to the `key_name` and `value` columns.
:::caution Note on schema migration
You are able to update `indexingLogic.js` after you have registered/created your indexer, but you are only allowed to specify `schema.sql` once before you submit your indexer. If you want to update your schema, you will have to create a new indexer.
:::
### `GraphiQL`
The GraphiQL tab in the editor will allow you to view the returned data from your GraphQL endpoint. This is best verified after you have created the indexer.
:::tip Video Walkthrough
**Tip:** Watch how to [create mutations in GraphQL](https://www.youtube.com/watch?v=VwO6spk8D58&t=781s).
:::
### Publishing
Clicking the <kbd>Publish</kbd> button will open the following pop-up. From here, you can configure the Indexer name, start block, and contract filter.
![Publishing QueryAPI Indexer](/docs/assets/QAPIPublish.png)
#### Start Block Options
- `Start from latest block`: Start indexing from the tip of the network. The exact block height is not guaranteed. Useful for testing indexing for events happening in real-time.
- `Continue from last processed block`: Update the configuration of the Indexer, and resume indexing from the last processed block. The block at which the configuration is updated is not guaranteed. Useful for fixing bugs encountered on specific blocks, adding additional logs, etc.
- `Start from block height`: Start indexing from the height specified, i.e., when the contract was deployed, or when a specific event occurs.
:::info
`Continue from last processed block` is only available for existing indexers. Updating the contract filter is disabled for this option, as it will create a backlog of blocks for two different contracts.
:::
:::warning
`Start from latest block` and `Start from block height` supersede the existing process. All queued blocks at the time of update will be cleared.
:::
## Performing Queries on the Public GraphQL API
In this section, we will provide a brief overview of how to query from a component in NEAR.
It is helpful to create a helper method which will allow us to fetch from our GraphQL API. Let's call it`fetchGraphQL`. It takes three parameters:
1. `queriesDoc`: A string containing the queries you would like to execute.
2. `queryName`: The specific query you want to run.
3. `variables`: Any variables to pass in that your query supports, such as `offset` and `limit` for pagination.
```javascript
function fetchGraphQL(queriesDoc, queryName, variables) {
return asyncFetch(
QUERY_API_ENDPOINT,
{
method: "POST",
headers: { "x-hasura-role": `<your_account_name>_near` },
body: JSON.stringify({
queries: queriesDoc,
variables: variables,
operationName: queryName,
}),
}
);
}
```
To use the `fetchGraphQL` function, first define a string of queries, e.g `transactionQueriesDoc` containing your desired queries:
```javascript
const transactionQueriesDoc = `query TransactionsQuery {
root_near_transactions {
id
sender
receiver
amount
block_height
}
}
...
query AnotherQuery {
root_near_accounts {
id
}
}`;
```
Next, call the `fetchGraphQL` function with the appropriate parameters and process the results. In this example, we fetch transaction data and update the application state:
```javascript
fetchGraphQL(transactionQueriesDoc, "TransactionsQuery", {})
.then((result) => {
if (result.status === 200) {
let data = result.body.data;
if (data) {
const transactions = data.root_near_transactions;
// Perform any necessary operations on the fetched data
...
// Update state with the new transactions data
State.update({
transactions: transactions,
});
}
}
});
```
We have just shown how to fetch data from the indexers that we have created from within NEAR. To view a more complex example, see this widget which fetches posts with proper pagination: [Posts Widget powered By QueryAPI](https://near.org/dataplatform.near/widget/QueryApi.Examples.Feed.Posts).
:::tip Video Walkthrough
**Tip:** Watch an [end-to-end example](https://www.youtube.com/watch?v=VwO6spk8D58&t=943s).
:::
|
---
sidebar_position: 1
---
# near_bindgen
The `#[near_bindgen]` macro is used on a `struct` and the function implementations to generate the necessary code to be a valid NEAR contract and expose the intended functions to be able to be called externally.
For example, on a simple counter contract, the macro will be applied as such:
```rust
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::near_bindgen;
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, Default)]
pub struct Counter {
value: u64,
}
#[near_bindgen]
impl Counter {
pub fn increment(&mut self) {
self.value += 1;
}
pub fn get_count(&self) -> u64 {
self.value
}
}
```
In this example, the `Counter` struct represents the smart contract state and anything that implements `BorshSerialize` and `BorshDeserialize` can be included, even `collections`, which will be covered in the next section. Whenever a function is called, the state will be loaded and deserialized, so it's important to keep this amount of data loaded as minimal as possible.
`#[near_bindgen]` also annotates the `impl` for `Counter` and this will generate any necessary boilerplate to expose the functions. The core interactions that are important to keep in mind:
- Any `pub` functions will be callable externally from any account/contract.
- For more information, see [public methods](../contract-interface/public-methods.md)
- `self` can be used in multiple ways to control the [mutability of the contract](../contract-interface/contract-mutability.md):
- Functions that take `&self` or `self` will be read-only and do not write the updated state to storage
- Functions that take `&mut self` allow for mutating state, and state will always be written back at the end of the function call
- Exposed functions can omit reading and writing to state if `self` is not included in the function params
- This can be useful for some static functionality or returning data embedded in the contract code
- If the function has a return value, it will be serialized and attached as a result through `env::value_return`
<!-- TODO include link to near_bindgen docs, when they aren't empty -->
## Initialization Methods
By default, the `Default::default()` implementation of a contract will be used to initialize a contract. There can be a custom initialization function which takes parameters or performs custom logic with the following `#[init]` annotation:
```rust
#[near_bindgen]
impl Counter {
#[init]
pub fn new(value: u64) -> Self {
log!("Custom counter initialization!");
Self { value }
}
}
```
All contracts are expected to implement `Default`. If you would like to prohibit the default implementation from being used, the `PanicOnDefault` derive macro can be used:
```rust
#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct Counter {
// ...
}
```
## Payable Methods
Methods can be annotated with `#[payable]` to allow tokens to be transferred with the method invocation. For more information, see [payable methods](../contract-interface/payable-methods.md).
To declare a function as payable, use the `#[payable]` annotation as follows:
```rust
#[payable]
pub fn my_method(&mut self) {
...
}
```
## Private Methods
Some methods need to be exposed to allow the contract to call a method on itself through a promise, but want to disallow any other contract to call it. For this, use the `#[private]` annotation to panic when this method is called externally. See [private methods](../contract-interface/private-methods.md) for more information.
This annotation can be applied to any method through the following:
```rust
#[private]
pub fn my_method(&mut self) {
...
}
```
:::info Interaction with other macros
When `near_bindgen` is built for the wasm32 target, it generates the external NEAR contract bindings. To achieve this it is actually generating another function with the signature `pub extern "C" fn function_name()` that first deserializes the contract struct from NEAR storage and then calls the `contract.function_name(parameter1, parameter2, ...)`. If you have annotated your function with any attribute-like macros, these are then executed _twice_. Specifically if the attribute like macro makes any modification to the function signature, or inserts any code that depends on the contract struct (in the form of `&self`, `&mut self`, or `self`) this will fail in the second invocation, because the externally exposed function does not have any concept of this struct. It is possible to detect this by checking which build target you are building for and limit the execution of the macro to operate only on the first pass.
:::
|
NEAR Foundation Transparency Report
NEAR FOUNDATION
September 12, 2022
With this report, the NEAR Foundation would like to expand the consistent and frequent communication with the NEAR community, to contribute to the long-term health and viability of the ecosystem.
As a result, the Foundation is publishing its first transparency report and committing to quarterly reports moving forward.
The purpose of the Foundation, per its articles of incorporation is promoting and developing new technologies and applications, especially in the fields of open and decentralized software architectures, to enable innovation to benefit people around the world. A dominating but not exclusive focus is set on the promotion and development of the NEAR Protocol and related technologies as well as the promotion and support of applications using the NEAR Protocol.
To deliver on its purpose, the Foundation is organised around 3 core areas of focus awareness, support and governance.
Below the Foundation shares details of how it allocated funding in Q4 2021 and Q1 + Q2 of 2022. This will include the rationale for these decisions and insight into future plans.
In totality, the Foundation deployed $540M in fiat and tokens during these three quarters. The allocation of these funds has helped the ecosystem while it grew at an unprecedented rate.
The number of accounts on the NEAR Protocol has grown from 1.1 million at the beginning of 2022 to 15.6 million accounts at the end of Q2.
The number of weekly active developers deploying on mainnet has grown from 250 to 1,500 per week.
DAOs have surged from 50 to 700 and the number of projects deployed on NEAR has increased from 100 to 750.
The NEAR Foundation in Q4 2021
In Q4 of 2021, the NEAR Foundation announced the launch of an $800 million ecosystem fund. The fund was to be split into four broad groups:
$350M – Proximity DeFi Grants – to help projects in the space of financial innovation within the NEAR Ecosystem.
$250M – Foundation Grants – to support projects building on NEAR, through direct investment and grants.
$100M – Startup Funds – to decentralize capital deployment into dedicated investment funds within the ecosystem.
$100M – Regional Funds – to establish physical hubs in key regions around the world to provide a local presence.
The below goes into further detail about how much was allocated, how much was committed and what projects were included in the allocation.
Category Announcement Committed
Proximity DeFi Grants $350m $350m
Foundation Grants $250m $133m
Startup Funds $100m $18m
Regional Hubs $100m $33m
Total Ecosystem Fund $800m $534m
Charity & Education $6m
Total Capital Deployed $540m
*Grants awarded in NEAR valued at $3.33 on 30th June 2022
Proximity DeFi Grants
Allocation: $350 million
Committed: $350 million
Why DeFi?
DeFi is one of the cornerstones of a healthy blockchain ecosystem. The provision of financial products and services helps users learn the tools necessary to safely navigate a Web3 ecosystem, as well as drive innovation.
DeFi helps other projects grow by facilitating quick, safe, and easy ways to move and swap currencies in and out of projects as they see fit. While the Foundation cannot deploy DeFi primitives itself, it can help support the creation of funds that can. Proximity forms that function inside the NEAR ecosystem.
Proximity is a research and development firm supporting projects building decentralized finance (DeFi) applications on NEAR and Aurora through grants, advisory services, and developer support.
Proximity’s allocation decisions are independent of the Foundation.
Ecosystem Grants
Allocation: $250 million
Committed: $133 million
Foundation Grants cover a broad range of investments from grant allocation to direct investment and are primarily focused on the following verticals: Infrastructure & Integrations, Gaming & Entertainment, NFTs, and DAOs.
The Foundation has come up with specific strategies and has deployed capital within each vertical.
Infrastructure and Integrations – Infrastructure is a catch all term for key parts of the ecosystem that are needed to help unlock mass adoption. These include things like wallets, bridges, oracles, zk technologies, privacy tools, and improved tools for developers. Integrations with the NEAR network are crucial to bring more users into web3. The following partnerships have been instrumental in accelerating NEAR’s connection with the rest of web3.
Key projects:Aurora, Pagoda, Calimero, Switchboard, Octopus, Brave, Coinbase Earn, BitGo, USDT, Fireblocks, Token Terminal, Copper
Gaming / Entertainment – The web3 gaming space is still wide open. The first iteration of web3 games proved consumer demand. Now, there is room to iterate on long-term sustainable models, introduce permissionless composability, and create new forms of NFTs in addition to games that are primarily or even fully on-chain.
Key projects:Armored Kingdom, SWEAT, Endlesss, Niche, playEmber, eFuse
NFTs – NFTs on NEAR is a large and extremely important opportunity in which NEAR has a unique tech advantage as NEAR NFTs are applications that are programmable. NEAR has a chance to be the first mover in true, long-term, sustainable and unique NFT use cases.
Key projects:Few & Far, Mintbase, Paras, Seatlab, Stack Sports
DAOs – We believe NEAR has the strongest no-code, easy to use, DAO tech stack that is already helping to decentrally govern key ecosystems and hundreds of millions of dollars. We will facilitate DAO use cases in investing, gaming, NFTs, sustainability, and science.
Key projects:AstroDAO, OrangeDAO, SailGP, Flamingo DAO, Unchain Fund
Startup Funds
Allocation: $100 million
Committed: $18 million
The Foundation does not believe it should be the sole distributor of capital to developers and entrepreneurs. Decisions should not be made in a vacuum with just one centralized organization.
In order to further decentralize capital deployment, the Foundation has allocated grant funds to MetaWeb, MOVE Capital, Stealth Capital, Open Web Collective who are focused on funding projects of the NEAR Ecosystem, each with their own thesis.
The Foundation has committed $18 million thus far to these funds that have subsequently made 50+ allocations into NEAR ecosystem projects.
MetaWeb, another NEAR native investment fund, has raised $30m from Sequoia, in addition to NF. MetaWeb have made 33 investments to date, including Niche, Orderly, Above.Land, and Sender Wallet.
MOVE Capital is a NEAR native investment fund that has raised $13m from Accomplice and DCG, in addition to NF. MOVE has made 15 investments to date, including Tonic, Calimero, Few & Far, and Sweatcoin.
Stealth Capital is an investment fund for founders, and brings a wealth of experience supporting the development of projects on Solana and Polygon, as well as NEAR.
Open Web Collective is a blockchain accelerator and investor backing the builders of the multi-chain, decentralized web. Open Web Collective’s approach to supporting founders is hands-on, user-centric, and analytical.
In addition to these, additional funds will be announced in the coming months, focused on specific verticals such as Sustainability, Sports & Entertainment, and Web2 → Web3.
Collectively the NEAR Foundation believes these funds will help realize its vision of bringing a billion users to Web3 in a healthier, more decentralized way.
Regional Hubs
Allocation: $100 million
Committed: $33 million
To be global, we have to be local.
As part of NEAR’s ambition to reach a billion people, the Foundation believes we need hubs around the world to connect with people where they are – with local events, in local languages, to find the best people wherever they are and forging partnerships with local organizations.
The NEAR Foundation has outlined seven regional hubs as part of its roadmap. So far, three have launched:
Ukraine Hub (in exile in Lisbon)
Kenya Hub (Sankore)
Balkans Hub
In addition to these hubs, the Foundation will soon be announcing Vietnam and India hubs and will be launching additional hubs in South Korea and the US.
The Foundation has chosen these locations based on a variety of factors, including web3 adoption, # of developers, regulatory environments, and available capital.
Funding, Treasury & Decentralisation
In addition, the NEAR Foundation has received $560m from the following key backers: Tiger Capital, FTX, a16z, Circle, Dragon Fly, and many others.
The Foundation has been very conservative in how the funds have been managed. Exposure to non-NEAR assets has been limited, with over $0.5b of funds raised held in fiat in Swiss bank accounts. This strategy helps ensure that the Foundation maintains sufficient resources throughout the market downturn.
This approach has left the Foundation in an extremely strong position to continue to distribute funds to high quality projects for the foreseeable future.
The Foundation is on a continued decentralization journey, and as part of this mandate working on its promise to put tokens in the hands of the community.
The community has come together in response to Illia’s talk from ECC in Paris to implement an ecosystem-wide self-governance treasury called the NEAR Digital Collective (NDC).
The purpose of the NDC is to further decentralize NEAR’s ecosystem governance, distribute more of the Foundation’s token holdings to the community and move decision-making on-chain in order to make our community more resilient, transparent, and fair.
A Community Working Group is now forming to take the next steps to launch and implement the NDC framework. This process is led and shaped by the community. Building better, sustainable self-governance at a global level starts with the community.
Every voice matters and we believe the process now being launched can serve as a model approach across Web3 for the creation and implementation of truly decentralized, on-chain governance.
The Road Ahead
NEAR’s mission is to:
Remove every barrier for Web3 creators, by creating an ecosystem that is uniquely simple, safe, scalable and sustainable.
The NEAR Foundation is committed to this mission. We will continue to support the ecosystem, drive awareness to NEAR and web3, and continue to educate regulators around the world.
The Foundational will continue to invest and deploy capital in the key verticals mentioned above: infrastructure, integrations, gaming / entertainment, NFTs, and DAOs
In addition, the Foundation will continue to decentralize and deploy capital into additional ecosystem funds and regional hubs that are dedicated to the ongoing health of the NEAR ecosystem.
As part of this journey, we are also committing to releasing quarterly transparency reports moving forward to show the NEAR community where capital is deployed and why. This will also include performance of the largest investments, grants, funds, and hubs
For any questions or feedback, please reach out to [email protected].
All of these efforts are to allow you to create without limits.
We believe in a world where creativity is no longer held back by technology.
A world without limits.
Thank you! |
NEAR Transparency Report: the State of Staking
NEAR FOUNDATION
November 21, 2022
As part of the Foundation’s commitment to transparency, each week it will publish data to help the NEAR community understand the health of the ecosystem. This will be on top of the quarterly report, and the now monthly funding reports.
You can find the quarterly reports here.
You can find monthly reports on funding here.
This week, the Foundation is focusing on the state of staking in the NEAR ecosystem.
The state of staking, as of Friday 18th November 2022
At the time of writing, there is 469 million NEAR staked, which equates to approximately 42% of the total supply, or 56.5% of circulating supply.
The staking total is spread across 131 validators, which is up on last month’s total validator number of 126, a four percent increase in the decentralization of the network.
The seat price – the amount of NEAR required to be eligible for staking has fallen precipitously. From 100,000 NEAR in October to just 20,000 NEAR in November, this means securing the network has become more accessible than ever before. The Foundation expects the number of validators to grow significantly to approximately 300 by the end of this year, as NEAR Foundation starts to delegate to Stake Wars winning participants.
This will continue as the protocol deploys its roadmap. In 2023, for example, the number of validators will continue to climb to a maximum of 400. You can read more about the road map here.
Staking Distribution
Of the 131 validators, eight validators hold 33% of the total staked balance, representing 154 million $NEAR. A total of 15 validators, hold 50% of the total staked balance, and 116 validators hold the other 50% of the total NEAR available. A stake of 33% is the stake that can halt the network, according to Pikespeak.
Distribution Validators Staked
0-33% 8 154m
33%-50% 7 74m
51%-75% 21 124m
76%-100% 95 116m
131 469m
To improve decentralisation, the Foundation, along with the ecosystem is continuing to improve the breadth and depth of the validators, and actively encourages stakeholders to delegate to validators outside the top 15.
Why are validators important?
The NEAR network is decentralized, meaning that multiple people collaborate in order to keep it safe. We call such people validators.
In order to make sure that all the transactions in the network are valid, i.e. that nobody is trying to steal money, the validators follow a specific consensus mechanism.
Currently, there are a few well-known consensus mechanisms to keep a blockchain working correctly and resistant to attacks. NEAR Protocol uses a version of Proof-of-Stake, particularly Thresholded Proof of Stake.
In Proof-of-Stake, users show support to specific network validators by delegating NEAR tokens to them. This process is known as staking. The main idea is that, if a validator has a large amount of tokens delegated is because the community trusts them.
Validators have two main jobs. The first is to validate and execute transactions, aggregating them in the blocks that form the blockchain. Their second job is to oversee other validators, making sure no one produces an invalid block or creates an alternative chain (eg. with the goal of creating a double spend).
If a validator is caught misbehaving, then they get “slashed”, meaning that their stake (or part of it) is burned.
In the NEAR networks, an attempt to manipulate the chain would mean taking control over the majority of the validators at once, so that the malicious activity won’t be flagged. However, this would require putting a huge sum of capital at risk, since an unsuccessful attack would mean slashing your staked tokens.
Why is decentralization important?
Staking is not only about the rewards, it is the basis for security and stability of the NEAR Protocol. To avoid centralization, split your stake between smaller staking pools instead of putting everything in the largest one.
Community members like Zavodil Validator have created excellent alternatives to NEAR’s official explorer, embedding metadata from the active staking pools to help you choose which Validators to Stake with. Also, consider joining the #staking channel on https://near.chat and ask questions!
These reports will be published each week, and cover different aspects of the ecosystem. |
---
NEP: 1
Title: NEP Purpose and Guidelines
Authors: Bowen W. <bowen@near.org>, Austin Baggio <austin.baggio@near.org>, Ori A. <ori@near.org>, Vlad F. <frol@near.org>;
Status: Approved
DiscussionsTo: https://github.com/near/NEPs/pull/333
Type: Developer Tools
Version: 1.1.0
Created: 2022-03-03
Last Updated: 2023-03-05
---
## Summary
A NEAR Enhancement Proposal (NEP) is a design document that specifies reusable and interoperable components integrated across the NEAR ecosystem.
NEPs are the primary mechanism for evolving NEAR’s runtime, Smart Contract Standards, and Wallets ecosystem in a community-driven way. NEPs provide a concise technical specification and a rationale for the feature. The NEP author is responsible for building consensus within the community and documenting dissenting opinions. The typical primary audience for NEPs are the developers of the NEAR reference implementations and decentralized application developers.
NEPs are stored as text files in a versioned repository, allowing for easy historical tracking. A list of NEPs is available on [GitHub](https://github.com/near/NEPs).
## Motivation
The purpose of the NEP process is to ensure the seamless evolution of the NEAR platform and to empower the community to contribute to its development. Given the complexity and number of participants involved across the ecosystem, a well-defined process helps ensure transparency, security, and stability.
## NEP Types
There are four kinds of NEPs:
1. A **Protocol** NEP describes a new feature of the NEAR protocol.
2. A **Contract Standards** NEP specifies NEAR Smart Contract interfaces for a reusable concept in the NEAR ecosystem.
3. A **Wallet Standards** NEP specifies ecosystem-wide APIs for Wallet implementations.
4. A **Developer Tools** NEP defines norms and guidelines for developer tooling in the NEAR ecosystem.
Currently, all types of NEPs follow the same process, but for Protocol NEPs a draft implementation is required.
## Submit a NEP
### Start with ideation
Everyone in the community is welcome to propose, discuss, and review ideas to improve the NEAR protocol and standards. The NEP process begins with a [new idea](https://www.neardevgov.org/blog/how-to-ideate-in-the-near-developer-governance) for the NEAR ecosystem. A single NEP should contain a single key proposal or new idea.
Each NEP must have an author: Someone who writes the NEP using the style and format described below. The author, or another champion, shepherds the discussions in the appropriate forums and attempts to build community consensus around the idea to help it progress toward completion.
Before submitting a NEP, the author should first attempt to ascertain whether the idea is NEP-able. Vetting an idea publicly before writing a NEP saves the potential author time. Asking the NEAR community first if the idea is original helps prevent effort on something guaranteed to be rejected based on prior discussions. It also helps ensure the idea applies to the entire community. Just because an idea sounds good to the author does not mean it will work for most people in most use cases.
In general, the process for socializing an idea is:
- **Check prior proposals:** Many ideas for changing NEAR come up frequently. Please search the [Dev Gov Gigs Board](https://devgovgigs.near.social), the [NEAR Forums](https://gov.near.org), and NEPs in this repo before proposing something new.
- **Share the idea:** Submit your [idea](https://www.neardevgov.org/blog/how-to-ideate-in-the-near-developer-governance) on the [Dev Gov Gigs Board](https://devgovgigs.near.social).
- **Get feedback:** The [Dev Gov Gigs Board](https://devgovgigs.near.social) has comment threading which allows the community to ideate, ask questions, wrestle with approaches, etc. If more immediate responses are desired, consider bringing the conversation to the appropriate [Community Group](https://gov.near.org/c/dev/community-groups/103).
### Submit a NEP Draft
Following the above initial discussions, the author should submit a NEP draft into the GitHub NEP repository. The draft NEP must follow the [NEP-0000 template](https://github.com/near/NEPs/blob/master/nep-0000-template.md), or else it will fail the review immediately.
To submit a NEP draft as a pull request, the NEP author should:
1. Fork the [NEPs repository](https://github.com/near/NEPs).
2. Copy `nep-0000-template.md` to `neps/nep-0000-my-feature.md` (where “my-feature” is descriptive; don’t assign a NEP number yet).
3. Fill in the NEP following the NEP template guidelines. For the Header Preamble, make sure to set the status as “Draft.”
4. Push this to your GitHub fork and submit a pull request.
5. Now that your NEP has an open pull request, use the pull request number to update your `0000` prefix. For example, if the PR is 305, the NEP should be `neps/nep-0305-my-feature.md`.
6. Push this to your GitHub fork and submit a pull request. Mention the @near/nep-moderators in the comment and turn the PR into a "Ready for Review" state once you believe the NEP is ready for review.
## NEP Lifecycle
The NEP process begins when an author submits a [NEP draft](#submit-a-nep-draft). The NEP lifecycle consists of three stages: draft, review, and voting, with two possible outcomes: approval or rejection. Throughout the process, various roles play a critical part in moving the proposal forward. Most of the activity happens asynchronously on the NEP within GitHub, where all the roles can communicate and collaborate on revisions and improvements to the proposal.
![NEP Process](https://user-images.githubusercontent.com/110252255/201413632-f72743d6-593e-4747-9409-f56bc38de17b.png)
### NEP Stages
- **Draft:** The first formally tracked stage of a new NEP. This process begins once an author submits a draft proposal and the NEP moderator merges it into the NEP repo when properly formatted.
- **Review:** A NEP moderator marks a NEP as ready for Subject Matter Experts Review. If the NEP is not approved within two months, it is automatically rejected.
- **Voting:** This is the final voting period for a NEP. The working group will vote on whether to accept or reject the NEP. This period is limited to two weeks. If during this period necessary normative changes are required, the NEP will revert to Review.
Moderator, when moving a NEP to review stage, should update the Pull Request description to include the
review summary, example:
```markdown
---
## NEP Status _(Updated by NEP moderators)_
SME reviews:
- [ ] Role1: @github-handle
- [ ] Role2: @github-handle
Contract Standards WG voting indications (❔ | :+1: | :-1: ):
- ❔ @github-handle
- ❔ ...
<Other> voting indications:
- ❔
- ❔
```
### NEP Outcomes
- **Approved:** If the working group votes to approve, they will move the NEP to Approved. Once approved, Standards NEPs exist in a state of finality and should only be updated to correct errata and add non-normative clarifications.
- **Rejected:** If the working group votes to reject, they will move the NEP to Rejected.
### NEP Roles and Responsibilities
![author](https://user-images.githubusercontent.com/110252255/181816534-2f92b073-79e2-4e8d-b5b9-b10824958acd.png)
**Author**<br />
_Anyone can participate_
The NEP author (or champion) is responsible for creating a NEP draft that follows the guidelines. They drive the NEP forward by actively participating in discussions and incorporating feedback. During the voting stage, they may present the NEP to the working group and community, and provide a final implementation with thorough testing and documentation once approved.
![Moderator](https://user-images.githubusercontent.com/110252255/181816650-b1610c0e-6d32-4d2a-a34e-877c702139bd.png)
**Moderator**<br />
_Assigned by the working group_
The moderator is responsible for facilitating the process and validating that the NEP follows the guidelines. They do not assess the technical feasibility or write any part of the proposal. They provide comments if revisions are necessary and ensure that all roles are working together to progress the NEP forward. They also schedule and facilitate public voting calls.
![Reviewer](https://user-images.githubusercontent.com/110252255/181816664-a9485ea6-e774-4999-b11d-dc8be6b08f87.png)
**NEP Reviewer** (Subject Matter Experts)<br />
_Assigned by the working group_
The reviewer is responsible for reviewing the technical feasibility of a NEP and giving feedback to the author. While they do not have voting power, they play a critical role in providing their voting recommendations along with a summary of the benefits and concerns that were raised in the discussion. Their inputs help everyone involved make a transparent and informed decision.
![Approver](https://user-images.githubusercontent.com/110252255/181816752-521dd147-f56f-4c5c-84de-567b109f21d6.png)
**Approver** (Working Groups)<br />
_Selected by the Dev Gov DAO in the bootstrapping phase_
The working group is a selected committee of 3-7 recognized experts who are responsible for coordinating the public review and making decisions on a NEP in a fair and timely manner. There are multiple working groups, each one focusing on a specific ecosystem area, such as the Protocol or Wallet Standards. They assign reviewers to proposals, provide feedback to the author, and attend public calls to vote to approve or reject the NEP. Learn more about the various working groups at [neardevgov.org](http://neardevgov.org/).
### NEP Communication
NEP discussions should happen asynchronously within the NEP’s public thread. This allows for broad participation and ensures transparency.
However, if a discussion becomes circular and could benefit from a synchronous conversation, any participants on a given NEP can suggest that the moderator schedules an ad hoc meeting. For example, if a reviewer and author have multiple rounds of comments, they may request a call. The moderator can help coordinate the call and post the registration link on the NEP. The person who requested the call should designate a note-taker to post a summary on the NEP after the call.
When a NEP gets to the final voting stage, the moderator will schedule a public working group meeting to discuss the NEP with the author and formalize the decision. The moderator will first coordinate a time with the author and working group members, and then post the meeting time and registration link on the NEP at least one week in advance.
All participants in the NEP process should maintain a professional and respectful code of conduct in all interactions. This includes communicating clearly and promptly and refraining from disrespectful or offensive language.
### NEP Playbook
1. Once an author [submits a NEP draft](#submit-a-nep-draft), the NEP moderators will review their pull request (PR) for structure, formatting, and other errors. Approval criteria are:
- The content is complete and technically sound. The moderators do not consider whether the NEP is likely or not to get accepted.
- The title accurately reflects the content.
- The language, spelling, grammar, sentence structure, and code style are correct and conformant.
2. If the NEP is not ready for approval, the moderators will send it back to the author with specific instructions in the PR. The moderators must complete the review within one week.
3. Once the moderators agree that the PR is ready for review, they will ask the approvers (working group members) to nominate a team of at least two reviewers (subject matter experts) to review the NEP. At least one working group member must explicitly tag the reviewers and comment: `"As a working group member, I'd like to nominate @SME-username and @SME-username as the Subject Matter Experts to review this NEP."` If the assigned reviewers feel that they lack the relevant expertise to fully review the NEP, they can ask the working group to re-assign the reviewers for the NEP.
4. The reviewers must finish the technical review within one week. Technical Review Guidelines:
- First, review the technical details of the proposals and assess their merit. If you have feedback, explicitly tag the author and comment: `"As the assigned Reviewer, I request from @author-username to [ask clarifying questions, request changes, or provide suggestions that are actionable.]."` It may take a couple of iterations to resolve any open comments.
- Second, once the reviewer believes that the NEP is close to the voting stage, explicitly tag the @near/nep-moderators and comment with your technical summary. The Technical Summary must include:
- A recommendation for the working group: `"As the assigned reviewer, I do not have any feedback for the author. I recommend moving this NEP forward and for the working group to [accept or reject] it based on [provide reasoning, including a sense of importance or urgency of this NEP]."` Please note that this is the reviewer's personal recommendation.
- A summary of benefits that surfaced in previous discussions. This should include a concise list of all the benefits that others raised, not just the ones that the reviewer personally agrees with.
- A summary of concerns or blockers, along with their current status and resolution. Again, this should reflect the collective view of all commenters, not just the reviewer's perspective.
5. The NEP author can make revisions and request further reviews from the reviewers. However, if a proposal is in the review stage for more than two months, the moderator will automatically reject it. To reopen the proposal, the author must restart the NEP process again.
6. Once both reviewers complete their technical summary, the moderators will notify the approvers (working group members) that the NEP is in the final comment period. The approvers must fully review the NEP within one week. Approver guidelines:
- First, read the NEP thoroughly. If you have feedback, explicitly tag the author and comment: `"As a working group member, I request from @author-username to [ask clarifying questions, request changes, or provide actionable suggestions.]."`
- Second, once the approver believes the NEP is close to the voting stage, explicitly comment with your voting indication: `"As a working group member, I lean towards [approving OR rejecting] this NEP based on [provide reasoning]."`
7. Once all the approvers indicate their voting indication, the moderator will review the voting indication for a 2/3 majority:
- If the votes lean toward rejection: The moderator will summarize the feedback and close the NEP.
- If the votes lean toward approval: The moderator will schedule a public call (see [NEP Communication](#nep-communication)) for the author to present the NEP and for the working group members to formalize the voting decision. If the working group members agree that the NEP is overall beneficial for the NEAR ecosystem and vote to approve it, then the proposal is considered accepted. After the call, the moderator will summarize the decision on the NEP.
8. The NEP author or other assignees will complete action items from the call. For example, the author will finalize the "Changelog" section on the NEP, which summarizes the benefits and concerns for future reference.
### Transferring NEP Ownership
While a NEP is worked on, it occasionally becomes necessary to transfer ownership of NEPs to a new author. In general, it is preferable to retain the original author as a co-author of the transferred NEP, but that is up to the original author. A good reason to transfer ownership is that the original author no longer has the time or interest in updating it or following through with the NEP process. A bad reason to transfer ownership is that the author does not agree with the direction of the NEP. One aim of the NEP process is to try to build consensus around a NEP, but if that is not possible, an author can submit a competing NEP.
If you are interested in assuming ownership of a NEP, you can also do this via pull request. Fork the NEP repository, modify the owner, and submit a pull request. In the PR description, tag the original author and provide a summary of the work that was previously done. Also clearly state the intent of the fork and the relationship of the new PR to the old one. For example: "Forked to address the remaining review comments in NEP \# since the original author does not have time to address them.
## What does a successful NEP look like?
Each NEP should be written in markdown format and follow the [NEP-0000 template](https://github.com/near/NEPs/blob/master/nep-0000-template.md) and include all the appropriate sections, which will make it easier for the NEP reviewers and community members to understand and provide feedback. The most successful NEPs are those that go through collective iteration, with authors who actively seek feedback and support from the community. Ultimately, a successful NEP is one that addresses a specific problem or needs within the NEAR ecosystem, is well-researched, and has the support of the community and ecosystem experts.
### Auxiliary Files
Images, diagrams, and auxiliary files should be included in a subdirectory of the assets folder for that NEP as follows: assets/nep-N (where N is to be replaced with the NEP number). When linking to an image in the NEP, use relative links such as .../assets/nep-1/image.png
### Style Guide
#### NEP numbers
When referring to a NEP by number, it should be written in the hyphenated form NEP-X where X is the NEP's assigned number.
#### RFC 2119
NEPs are encouraged to follow [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) for terminology and to insert the following at the beginning of the Specification section:
The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt).
## NEP Maintenance
Generally, NEPs are not modifiable after reaching their final state. However, there are occasions when updating a NEP is necessary, such as when discovering a security vulnerability or identifying misalignment with a widely-used implementation. In such cases, an author may submit a NEP extension in a pull request with the proposed changes to an existing NEP document.
A NEP extension has a higher chance of approval if it introduces clear benefits to existing implementors and does not introduce breaking changes.
If an author believes that a new extension meets the criteria for its own separate NEP, it is better to submit a new NEP than to modify an existing one. Just make sure to specify any dependencies on certain NEPs.
## References
The content of this document was derived heavily from the PEP, BIP, Rust RFC, and EIP standards bootstrap documents:
- Klock, F et al. Rust: RFC-0002: RFC Process. https://github.com/rust-lang/rfcs/blob/master/text/0002-rfc-process.md
- Taaki, A. et al. Bitcoin Improvement Proposal: BIP:1, BIP Purpose and Guidelines. https://github.com/bitcoin/bips/blob/master/bip-0001.mediawiki
- Warsaw, B. et al. Python Enhancement Proposal: PEP Purpose and Guidelines. https://github.com/python/peps/blob/main/pep-0001.txt
- Becze, M. et al. Ethereum Improvement Proposal EIP1: EIP Purpose and Guidelines. https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1.md
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
|
Near Partners with BORA, Web3 GameFi Platform of Kakao Games
NEAR FOUNDATION
March 6, 2023
Near is excited to announce a new strategic partnership with BORA, a Web3 gaming subsidiary of METABORA. Near and BORA will support each other in spreading local brand awareness, invest in research and collaboration on cross-chain, host events, and generate Web3 opportunities in Korea.
An affiliate of Kakao Games and its parent company BORANETWORK, BORA is focused on game development and blockchain-based gaming ecosystems. Its mobile gaming titles include Friends Popcorn, Friends Town, and Friends Shot.
“We are thrilled to be working with Near and welcome their expertise, knowledge and network as we aim to transform the world of Web3 gaming,” said Vincent Lim, a CBO of BORA. “Together with Near we will not only explore cross-promotion opportunities, but also seek future collaborations on IP-based game development that will lead to mass adoption and give us the competitive edge we need to position ourselves as leading players in the web3 gaming space.”
Since the launch of Near’s Korean Hub in November of 2022, BORA has been steadily building up awareness throughout South Korea, while focusing on Web3 innovation, business development, education, and talent. The hub is led by entrepreneurs Scott Lee and Ben Kang — both influential figures within South Korea’s growing blockchain community.
“One of the big ambitions of the hub is to tap into the country’s active gaming community, and to bring amazing projects and creators to the Near ecosystem.” said Robbie Lim, GM, Partners & International at Near. “ The partnership with BORA is our first major win – and a big step forward for NEAR as it accelerates its ambition to become the go to layer 1 for the Web3 gaming community.” |
NEAR in April: Sweatcoin, Kenya Regional Hub, and More
COMMUNITY
April 28, 2022
Spring is in swing, and things haven’t slowed down a bit for the NEAR ecosystem and community. In April, NEAR cemented exciting new partnerships, expanded its global footprint, and introduced dramatic new platform enhancements.
NEAR Foundation’s partnership with Sweatcoin and the NEAR Regional Hub launch in Kenya are two such developments. April was also a month full of blockchain events, with NEAR appearing at Paris Blockchain Week Summit and DevConnect.
From meeting new friends to enabling tomorrow’s movement economy, here’s everything you need to know about NEAR in April.
Sweatcoin builds the Movement Economy on NEAR
During the Paris Blockchain Week Summit, NEAR announced a partnership with Sweatcoin, the London-based move-to-earn project for incentivizing healthier living. The Sweatcoin app’s native SWEAT token and infrastructure will be built atop NEAR’s rapid, secure, and infinitely scalable blockchain.
Sweatcoin signals a radical shift in the incentivization of health and fitness, rewarding users for moving with the SWEAT token. These tokens can then be redeemed, spent, or traded in a new Open Movement Economy enabled by the NEAR blockchain.
“The inherent issue with traditional cryptocurrency is that you have to use your own money,” says Oleg Fomenko, Co-founder of Sweatcoin. “While SWEAT will be available to purchase, the key difference is that for everyday users, you invest your steps, which we hope is going to encourage people around the world to want to be more active.
As the project matures and becomes more integrated with wearables, users will be able to earn SWEAT via a wider variety of activities like hiking, rowing, and cycling. Tokens can then be sold and traded like any other digital crypto asset or used to purchase goods and services on the Sweatcoin app marketplace from one of over 300 brand partners like Reebok and Sonos.
Helping onboard the world to Web3 is one of NEAR’s core mission objectives. Collaborating with Sweatcoin is a substantial step in that direction, making NEAR a key part of tomorrow’s move-to-earn economy.
NEAR at Paris Blockchain Week Summit
The Sweatcoin partnership announcement was just the tip of the iceberg for NEAR at the Paris Blockchain Week Summit. From April 12-14, the NEAR Foundation participated in a number of talks on blockchain innovation, dapp development, and DAO governance.
The NEAR-Atka Meetup kicked things off at the historical Palais Brongniart stock exchange building. Attendees mingled over food and champagne as NEAR figures took the stage.
NEAR Foundation CEO Marieke Flament started the keynotes with opening remarks and an introduction to the NEAR ecosystem. Illia Polosukhin, Co-founder of NEAR, then updated the audience on NEAR infrastructure and developments, including protocol security and enterprise solutions. Attendees also received a progress report from Anton Vaisburd, general manager of NEAR’s Ukraine Regional Hub. The day concluded with the 90-minute “Building on NEAR” panel, featuring tips and insights from developers of key ecosystem projects.
At the Discovery Stage on Day 2, Flament gave a keynote on the diversity of apps and economies set to emerge in the future. She pointed to YouMinter, SailGP, and Sweatcoin as examples of apps and partnerships that are helping to build the Open Web on NEAR.
PBWS wrapped up on April 14th with Flament leading the “Interactive Roundtable: Pioneering the Future of DAOs.” Panelists included NEAR Co-founder Polosukhin, SailGP’s Charlie Dewhurst, and Paraswap founder Mounir Benchelemb.
Polosukhin advocated for DAOs’ potential to help solve difficult challenges quickly in ways that traditional non-profits or corporations cannot. Dewhurst noted that DAOs like SailGP can bring competitors closer to fans and encourage collaborative team and sports brand building with audiences. Benchelemb added that while DAOs empower individuals regardless of background, simplified onboarding is critical for mass adoption in the future.
Click here for full highlights of NEAR @ PBWS 2022.
NEAR in the News
Recently, NEAR made news with Flament discussing the environmental impact of crypto and the protocol’s carbon neutrality in an article published on Verdict. She referenced Sweatcoin as a way that the NEAR Foundation is encouraging greener lifestyles across the planet. Flament said a key goalsof the partnership is to make physical activity part of the global GDP, leading to a more sustainable global economy.
NEAR also popped up in a BNN Bloomberg article about the state of Fintech post-Brexit. Flament noted that while Fintech has improved financial services in certain respects, it hasn’t been truly disruptive and the space has become crowded. Blockchain and the Open Web will be the catalyst for developers to inject adrenaline and meaningful disruption into fintech and payments, she said.
NEAR checked in ahead of April’s IFGS conference, with Flament speaking to Finextra about Web3’s transformative potential on financial services. While blockchain will decentralize finance and offer new modalities of transacting value, she said nurturing new talent will be a key challenge to overcome. It’s why NEAR recently partnered with OrangeDAO, a crypto group created by Y Combinator alums, which is backing Web startups and talent.
Next, Flament penned an op-ed for UK Tech titled “Web3 and the race for talent: why diversity is critical to success.” Her thoughts ranged from how diversity can be hard-coded into Web3 and how education to enhance blockchain’s inclusivity.
Flament also represented NEAR as a panelist for Financial Times’ FT Live online event on April 27th. The panel discussion went on a deep dive into the environmental, social, and governance (ESG) issues facing crypto. The conversation centered on whether more investor scrutiny is needed to make digital assets more sustainable. The panelists also talked about lowering the blockchain’s carbon footprint and preventing illicit activities like money laundering using cryptocurrencies.
Education and networking at DevConnect Amsterdam
NEAR @ DevConnect took place on April 21st at Boom Chicago in Amsterdam, with a full day of in-depth sessions. The event gave attendees an opportunity to connect with fellow developers, community members, and ecosystem partners.
DevConnect also provided developers space and resources for onboarding to NEAR and Aurora, as well as information on how projects and developers can potentially apply for and receive funding via the NEAR Foundation Grants program.
Core topics at DevConnect included NEAR’s vision and roadmap for 2022, and technical overviews of Aurora and NearPay, a new crypto debit card. Speakers included CEO Marieke Flament, NEAR co-founder Illia Polosukhin, and Flux CTO Jasper De Gooijer, and COO of NearPay Illin.
As always, anyone who couldn’t attend in person at Boom Chicago was able to stream DevConnect on NEARVERSE. DevConnect Amsterdam was a huge success and NEAR looks forward to subsequent events in 2022.
Sankore and NEAR launch the Kenya Regional Hub
April also saw the NEAR Foundation announce the launch of the Kenya Regional Hub. A partnership with Sankore, NEAR Guild based in Kenya, the hub will accelerate blockchain innovation, education, and talent development across Sub-Saharan Africa.
The hub will be led by Sankore founder Kevin Imani and his core team. They plan to organize events, launch an incubator, and incorporate NEAR into Sankore’s existing bounty system. Imani’s vision is to use blockchain to help solve some of Africa’s biggest challenges. He believes that partnering with NEAR for the Regional Hub will help nurture the talent to do just that.
“We are excited by the potential avenues throughout Africa for blockchain solutions,” says Marieke Flament, CEO of the NEAR Foundation. “This hub represents a unique opportunity to partner with local talent not only for the opportunities that we know exist today but also for the opportunities yet to be created in the future.”
Given Sankore’s success incubating blockchain projects, it won’t take long for NEAR’s Kenya Regional to gain traction. The NEAR Foundation is thrilled to offer the hub the resources to create a prosperous, open digital future.
ICYMI: The Merging of Music and the Blockchain
The NEAR Foundation also published 4-part series “Music in the Blockchain Era” in April. It explored the radical shift taking place in blockchain-enabled music, including new royalty models, DAO record labels, and more.
To facilitate a more free and fair Open Web, NEAR Foundation will support new pathways and technologies for musical creativity. The foundation will also help build stronger communities for fans and artists alike.
Want to learn more about how blockchain is changing the way we create, consume, and interact with music and musicians? Check out the “Music in the Blockchain Era” series below:
Introducing the Future of Sound
Building a Record Label on the Blockchain
The Rise of the New Musician
The Future of Decentralized Music
|
Customer acquisition platform helps crypto companies grow
COMMUNITY
April 17, 2020
Depending on who you ask, the drop-off rate of blockchain applications is somewhere between 95% and 97%. This means that no more than five users actually succeed with onboarding for every 100 that try. In addition, web2 users today barely see any value in blockchain applications, which they often describe as “toy applications.”
Currently, the market of blockchain applications is extremely tiny, with somewhere between 10,000 and 12,000 developers in the mix. As a result, there are only a couple hundred projects, very few of which have any traction.
Talented entrepreneurs and developers expect robust developer tooling, seamless onboarding for their users, and numerous opportunities to monetize their applications and businesses over time. Such an infrastructure is almost non-existent on a protocol-level today. As such, there is an opportunity for developers to build applications that solve these challenges.
What if you could encode digital assets into URLs and QR codes? Not only this, what if you could send this URL to your friend who doesn’t even have a digital wallet?
Introducing Linkdrop
Linkdrop helps crypto-native organizations (e.g., protocols, decentralized applications, and wallets) manage their marketing campaigns by providing tools that help them target their potential customers. URLs and QR codes allow them to create a seamless experience for end-users, including the first-time crypto users. With this approach, users don’t have to deal with complex wallet creation processes, and crypto-native organizations enjoy significantly improved conversion rates during the onboarding stage.
In addition, Linkdrop creates opportunities for companies to tap into their users’ networks by allowing them to invite their friends through referral links.
Not only can you address the crypto-acquiring process with Linkdrop, you can also enable wallet creation and sign in with Google via Linkdrop’s wallet widget.
With Linkdrop, companies can manage their link campaigns, distribute them, and run analytics in one place. This allows you to measure the impact of your Linkdrop campaigns and use meaningful user analytics to optimize your next one.
Why Blockchain:
Linkdrop started with the blockchain market as an entry point in other markets. From Linkdrop’s perspective, gaming and internet companies integrating blockchain-based marketing will be the first outside of crypto to adopt Linkdrop solutions. Once blockchain becomes the dominant technology for transferring value, traditional companies will start acquiring users with blockchain-based marketing campaigns.
Further Reading
Linkdrop’s blog
Relevant Industries
Wallets (e.g., Gnosis Safe, Coinbase Wallet, and Trust Wallet are customers), blockchain applications (e.g., Decentraland, Snark.art, and Pool Together), protocols (e.g., Binance, Flow, and NEAR). |
- Proposal Name: System methods in runtime API
- Start Date: 2019-09-03
- NEP PR: [nearprotocol/neps#0013](https://github.com/nearprotocol/neps/pull/0013)
# Summary
[summary]: #summary
Adds new ability for contracts to perform some system functions:
- create new accounts (with possible code deploy and initialization)
- deploy new code (or redeploying code for upgrades)
- batched function calls
- transfer money
- stake
- add key
- delete key
- delete account
# Motivation
[motivation]: #motivation
Contracts should have the ability to create new accounts, transfer money without calling code and
stake. It will enable full functionality of contract-based accounts.
# Reference
[reference]: #reference
We introduce additional promise APIs to support batched actions.
Firstly, we enable ability to create empty promises without any action. They act similarly to
traditional promises, but don't contain function call action.
Secondly, we add API to append individual actions to promises. For example we can create
a promise with a function_call first using `promise_create` and then attach a transfer action on top
of this promise. So the transfer will only deposit tokens if the function call succeeds. Another example
is how we create accounts now using batched actions. To create a new account, we create a transaction with
the following actions: `create_account`, `transfer`, `add_key`. It creates a new account, deposit some funds on it and the adds a new key.
For more examples see NEP#8: https://github.com/nearprotocol/NEPs/pull/8/files?short_path=15b6752#diff-15b6752ec7d78e7b85b8c7de4a19cbd4
**NOTE: The existing promise API is a special case of the batched promise API.**
- Calling `promise_batch_create` and then `promise_batch_action_function_call` will produce the same promise as calling `promise_create` directly.
- Calling `promise_batch_then` and then `promise_batch_action_function_call` will produce the same promise as calling `promise_then` directly.
## Promises API
[promises-api]: #promises-api
```rust
promise_batch_create(account_id_len: u64, account_id_ptr: u64) -> u64
```
Creates a new promise towards given `account_id` without any actions attached to it.
###### Panics
* If `account_id_len + account_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
###### Returns
* Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_batch_then(promise_idx: u64, account_id_len: u64, account_id_ptr: u64) -> u64
```
Attaches a new empty promise that is executed after promise pointed by `promise_idx` is complete.
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If `account_id_len + account_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
###### Returns
* Index of the new promise that uniquely identifies it within the current execution of the method.
---
```rust
promise_batch_action_create_account(promise_idx: u64)
```
Appends `CreateAccount` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R48
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
---
```rust
promise_batch_action_deploy_contract(promise_idx: u64, code_len: u64, code_ptr: u64)
```
Appends `DeployContract` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R49
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If `code_len + code_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_function_call(promise_idx: u64,
method_name_len: u64,
method_name_ptr: u64,
arguments_len: u64,
arguments_ptr: u64,
amount_ptr: u64,
gas: u64)
```
Appends `FunctionCall` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R50
*NOTE: Calling `promise_batch_create` and then `promise_batch_action_function_call` will produce the same promise as calling `promise_create` directly.*
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If `account_id_len + account_id_ptr` or `method_name_len + method_name_ptr` or `arguments_len + arguments_ptr`
or `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_transfer(promise_idx: u64, amount_ptr: u64)
```
Appends `Transfer` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R51
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If `amount_ptr + 16` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_stake(promise_idx: u64,
amount_ptr: u64,
public_key_len: u64,
public_key_ptr: u64)
```
Appends `Stake` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R52
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
* If `amount_ptr + 16` or `public_key_len + public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_add_key_with_full_access(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64)
```
Appends `AddKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R54
The access key will have `FullAccess` permission, details: [0005-access-keys.md#guide-level-explanation](click here)
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
* If `public_key_len + public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_add_key_with_function_call(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64,
nonce: u64,
allowance_ptr: u64,
receiver_id_len: u64,
receiver_id_ptr: u64,
method_names_len: u64,
method_names_ptr: u64)
```
Appends `AddKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-156752ec7d78e7b85b8c7de4a19cbd4R54
The access key will have `FunctionCall` permission, details: [0005-access-keys.md#guide-level-explanation](click here)
* If the `allowance` value (not the pointer) is `0`, the allowance is set to `None` (which means unlimited allowance). And positive value represents a `Some(...)` allowance.
* Given `method_names` is a `utf-8` string with `,` used as a separator. The vm will split the given string into a vector of strings.
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
* if `method_names` is not a valid `utf-8` string, fails with `BadUTF8`.
* If `public_key_len + public_key_ptr`, `allowance_ptr + 16`, `receiver_id_len + receiver_id_ptr` or
`method_names_len + method_names_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_delete_key(promise_idx: u64,
public_key_len: u64,
public_key_ptr: u64)
```
Appends `DeleteKey` action to the batch of actions for the given promise pointed by `promise_idx`.
Details for the action: https://github.com/nearprotocol/NEPs/pull/8/files#diff-15b6752ec7d78e7b85b8c7de4a19cbd4R55
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If the given public key is not a valid public key (e.g. wrong length) `InvalidPublicKey`.
* If `public_key_len + public_key_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
```rust
promise_batch_action_delete_account(promise_idx: u64,
beneficiary_id_len: u64,
beneficiary_id_ptr: u64)
```
Appends `DeleteAccount` action to the batch of actions for the given promise pointed by `promise_idx`.
Action is used to delete an account. It can be performed on a newly created account, on your own account or an account with
insufficient funds to pay rent. Takes `beneficiary_id` to indicate where to send the remaining funds.
###### Panics
* If `promise_idx` does not correspond to an existing promise panics with `InvalidPromiseIndex`.
* If the promise pointed by the `promise_idx` is an ephemeral promise created by `promise_and`.
* If `beneficiary_id_len + beneficiary_id_ptr` points outside the memory of the guest or host, with `MemoryAccessViolation`.
---
|
---
id: recompress-storage
title: Recompressing archival node storage
sidebar_label: Recompressing archival node storage
sidebar_position: 4
description: How to recompress archival node’s storage to reduce its size.
---
# Recompressing archival node storage
The nearcore 1.26.0 release introduces various improvements to node’s
storage layer. Among better performance, the changes result in
*significant* reduction of the storage on archival nodes: from 7.7 TB
to 3.8 TB on mainnet and from 3.6 TB to 1.7 TB on testnet.
However, to take full advantage of the savings, some manual steps need
to be taken. This document describes those steps. Note that if
you’re not running an archival node, you don’t need to do anything.
One of the improvements is changing of the compression algorithm used
by the databases. Because of that, the whole process is referred to
as ‘recompressing the storage’.
## Downloading recompressed snapshot
Rather than performing the recompression, an easier way of getting
benefits of the storage optimisation is to download a new [node data
snapshots](/intro/node-data-snapshots). This option is available for
mainnet and testnet chains alike.
If you’ve started a new archival node from a backup on 2022-06-10 or
later, your node is already running with recompressed storage and you
don’t need to take any further actions.
## Performing the operation
The recompression can be performed at any time. That is, it doesn’t
need to happen directly after the node upgrade. In fact, it might be
better to schedule it some number of days after binary upgrade. Such
delay gives time to make sure that the binary release works correctly
before introducing another change.
### Required free space
Recompressing storage works by creating *a new* database. As
a result, it requires noticeable amount of free disk space.
Specifically 4 TB for mainnet and 2 TB for testnet archival nodes.
If your host does not have enough free space you will need to resize
one of the existing partitions (if you are running in the cloud and
can resize disks freely) or temporarily attach a new disk.
At the end of the process it will be possible to delete the old
database freeing a lot of space. Note however that while increasing
disk size in the cloud is often a simple operation, shrinking it might
be more complicated. You need to plan accordingly based on your
node’s setup.
### Stopping the node
While the recompression takes place the database cannot be modified.
In other words, the node needs to be shut down. The operation takes
around twelve hours on mainnet and six hours on testnet. If you
require a continuous access to an archival node, you will need to set
up a redundant node if one is not already available.
Procedure for stopping a node depends on configuration of your system.
For example, if neard is run as a systemd service, the command to stop
it might look like:
```console
$ sudo systemctl stop neard.service
```
### Executing the recompression
The recompression is done by executing `recompress-storage` command of
`neard` binary. If the command is interrupted the whole operation
needs to be run from scratch. Because of that, it’s best to run it
inside of a screen or tmux session or through nohup utility. For
example:
```console
$ NEAR_HOME=$HOME/.near # change to point to near home directory
$ export NEAR_HOME
$ screen
$ # Inside of screen session:
$ neard recompress-storage --output-dir="${NEAR_HOME:?}/data.new"
```
Once recompression finishes successfully, the new database needs to be
put in place of the old one. This is simply done by renaming the
`data.new` directory:
```console
$ NEAR_HOME=$HOME/.near # change to point to near home directory
$ export NEAR_HOME
$ mv -- "${NEAR_HOME:?}/data" "${NEAR_HOME:?}/data.bak"
$ mv -- "${NEAR_HOME:?}/data.new" "${NEAR_HOME:?}/data"
```
The `data.bak` backup might be worth keeping at least until
verification described in the next section is completed. If the
verification fails, it will be easy to recover database prior to
recompression. Otherwise `data.bak` can be deleted.
#### Disk size considerations
As mentioned above, the operation requires up to 4 TB of free disk
space. The above commands assume that near home directory has it but
if it doesn’t you will have to write new database in a different
location adjusting `--output-dir` flag accordingly.
For example, if the archival node is running in cloud environment an
easy way could be to create a new disk and mount it under a new
location, e.g. `/mnt`. This could look something like:
```console
$ NEAR_HOME=$HOME/.near # change to point to near home directory
$ export NEAR_HOME
$ # After attaching new disk to the virtual machine; e.g. at /dev/sdx:
$ dev=/dev/sdx
$ sudo mkfs.ext4 "${dev:?}"
$ sudo mount "${dev:?}" /mnt
$ sudo chown -R $USER /mnt
$ neard recompress-storage --output-dir=/mnt/data
$ # ... recompress comences ...
$ rm -rf -- "${NEAR_HOME:?}/data"
$ cp -R -- /mnt/data "${NEAR_HOME:?}"
$ sudo umount /mnt
```
If you’re using a different configuration with a separate disk mounted
at `~/.near` directory, copying is not necessary and can be handled by
swapping the mount points. Note that in this instance the new disk
needs to be an SSD.
```console
$ cp ~/.near/*.json /mnt
$ sudo umount ~/.near
$ sudo umount /mnt
$ sudo mount "${dev:?}" ~/.near
```
The details will depend on the configuration of the system you’re
using.
### Verification
At this point it is possible to start the archival node again.
However, we recommend performing sanity checks on the new database
before doing that. This can be done with help of `view-state` command
as follows:
```console
$ NEAR_HOME=$HOME/.near # change to point to near home directory
$ export NEAR_HOME
$ head=$(neard view-state view-chain |
sed -ne 's/ *height: *\([0-9]*\),$/\1/p')
$ test -n "$head" || echo 'Unable to read chain head'
$ echo TIP: "$head"
TIP: 63870907
$ start=$((head - 1000))
$ neard view-state apply-range --start-index=$start --shard-id=0
$ neard view-state apply-range --start-index=$start --shard-id=1
$ neard view-state apply-range --start-index=$start --shard-id=2
$ neard view-state apply-range --start-index=$start --shard-id=3
```
If the commands report no errors or differences, it’s safe to start
the node again. This verification should take around 15 minutes.
## What has been changed
The 1.26.0 release introduced three main changes which reduced size of
the storage.
Firstly, we’ve incorporated Zstandard (zstd) compression algorithm
which by itself reduces size of the database by around a quarter.
However, normally existing data remains intact unless it’s changed or
compacted. Since RPC nodes rewrite most of the storage every five
epochs, their database will be recompressed after two and a half days.
On the other hand, archival nodes benefit from it being done manually
since otherwise the size reduction would take a long time to present
itself.
Secondly, we’ve started garbage collecting partial encoded chunks on
archival nodes. RPC nodes already garbage collected that data so this
change doesn’t affect them. The encoded chunks are needed when other
nodes sync their state but can be reconstructed from other objects in
the database. They constitute around a quarter of the database’s size
thus garbage collecting them results in a big reduction in storage
size at the cost of slight computation increase when node sends old
blocks to other archival nodes which attempt to sync their state.
Thirdly, we’ve stopped generating trie changes on archival nodes.
Those objects are needed on RPC nodes but can be omitted on archival
nodes. They accounted for around a quarter of the database’s size.
## Do I need to do anything?
You don’t need to do anything if you’re running an RPC node or if you
don’t care about storage cost. If you have SSD disk space laying
around you may continue running your node without performing the
recompression.
Note also that if you are operating an archival node but are worried
about scheduling (e.g. you’re busy dealing with other issues and thus
have no time to deal with neard database changes) you can postpone the
recompression.
|
---
sidebar_position: 2
sidebar_label: Block
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# `Block` Structure
## Definition
`Block` is the main entity in NEAR Protocol blockchain. `Blocks` are produced in NEAR Protocol every second.
It contains the info:
- about the `Block` producer (`AccountId` of the validator responsible for particular `Block` production)
- Block Header
- List of Chunk Headers
## Representation
### `Block`
<Tabs>
<TabItem value="rust" label="Rust" default>
```rust links=1
pub struct BlockView {
pub author: AccountId,
pub header: BlockHeaderView,
pub chunks: Vec<ChunkHeaderView>,
}
```
</TabItem>
<TabItem value="typescript" label="TypeScript">
```ts links=1
export interface Block {
author: string;
header: BlockHeader;
chunks: ChunkHeader[];
};
```
</TabItem>
</Tabs>
### `BlockHeaderView`
`BlockHeaderView` contains main info about the block.
<Tabs>
<TabItem value="rust" label="Rust">
```rust
pub struct BlockHeaderView {
pub height: BlockHeight,
pub prev_height: Option<BlockHeight>,
pub epoch_id: CryptoHash,
pub next_epoch_id: CryptoHash,
pub hash: CryptoHash,
pub prev_hash: CryptoHash,
pub prev_state_root: CryptoHash,
pub chunk_receipts_root: CryptoHash,
pub chunk_headers_root: CryptoHash,
pub chunk_tx_root: CryptoHash,
pub outcome_root: CryptoHash,
pub chunks_included: u64,
pub challenges_root: CryptoHash,
/// Legacy json number. Should not be used.
pub timestamp: u64,
pub timestamp_nanosec: u64,
pub random_value: CryptoHash,
pub validator_proposals: Vec<ValidatorStakeView>,
pub chunk_mask: Vec<bool>,
pub gas_price: Balance,
pub block_ordinal: Option<NumBlocks>,
/// TODO(2271): deprecated.
pub rent_paid: Balance,
/// TODO(2271): deprecated.
pub validator_reward: Balance,
pub total_supply: Balance,
pub challenges_result: ChallengesResult,
pub last_final_block: CryptoHash,
pub last_ds_final_block: CryptoHash,
pub next_bp_hash: CryptoHash,
pub block_merkle_root: CryptoHash,
pub epoch_sync_data_hash: Option<CryptoHash>,
pub approvals: Vec<Option<Signature>>,
pub signature: Signature,
pub latest_protocol_version: ProtocolVersion,
}
```
</TabItem>
<TabItem value="typescript" label="TypeScript">
```ts links=1
export interface BlockHeader {
approvals: (string | null)[];
blockMerkleRoot: string;
blockOrdinal: number;
challengesResult: ChallengeResult[];
challengesRoot: string;
chunkHeadersRoot: string;
chunkMask: boolean[];
chunkReceiptsRoot: string;
chunkTxRoot: string;
chunksIncluded: number;
epochId: string;
epochSyncDataHash: string | null;
gasPrice: string;
hash: string;
height: number;
lastDsFinalBlock: string;
lastFinalBlock: string;
latestProtocolVersion: number;
nextBpHash: string;
nextEpochId: string;
outcomeRoot: string;
prevHash: string;
prevHeight: number;
prevStateRoot: string;
randomValue: string;
rentPaid: string;
signature: string;
timestamp: number;
timestampNanosec: string;
totalSupply: string;
validatorProposals: [];
validatorReward: string;
};
```
</TabItem>
</Tabs>
|
NEAR Korea Hub: June 2023 Highlights
NEAR FOUNDATION
July 3, 2023
Since launching in November of 2022, NEAR Korea Hub has hit a number of major milestones in the Korean Web3 industry. The Hub has significantly contributed to the expansion of the Web3 ecosystem over the past 6 months by forming partnerships with leading domestic game companies, providing generous developer support, and forging long-term relationships with college blockchain clubs.
Let’s take a look at all of the exciting things that came out of the NEAR Korea Hub during NEAR co-founder Illia Polosukhin’s visit.
NEAR co-founder Illia Polosukhin talks Web3 and AI
A number of major Korean media outlets conducted interviews with Illia on NEAR Protocol’s Web3 and AI strategy. Illia pointed out that NEAR Protocol’s principle focus is on the Blockchain Operating System (BOS) and FastAuth, an important new product that provides a better-than-Web2 onboarding experience that can help foster the mass adoption of Web3.
Here is a list of Illia’s interviews (the coverage is in Korean):
Hankyung (Korea Economy) – “Blockchain and AI will Create the Best Synergy”
Kyunghyang – Blockchain AI Synergy will be Amazing
Kyunghyang Weekly – Is Fake News the Fault of Generative AI?
TechM – Korean Games Leading in Web3.0 Business Model… Synergy with AI and Blockchain
CoinDesk – Popularization of Web3 Starts from User-Centered Thinking
Illia’s talk at ETHSeoul & Buidl Asia — June 2nd – June 7th
Illia attended ETH Seoul and BUIDL Asia — both major Web3 events — as the first keynote speaker, where he gave a speech entitled “Web3’s Future, BOS.”
“One of the major problems with Web3 is the user inconvenience when making and using wallets,” Illia pointed out. “With BOS, which provides a Web2-like experience and ease for developers and users, NEAR Protocol wants to connect all blockchain and users to onboard 1 billion users to Web3”. He also added: “BOS acts as a gateway to combine all features such as DeFi and NFT which are scattered around the Web3 network”.
Illia further emphasized the importance of the Korean market and shared achievements of NEAR Korea Hub.
Illia’s Speech at the Gyeonggi Province ‘AI Expert Policy Roundtable’ — June 8th
Illia was invited to give his speech “The Intersection of AI and Web3” at the “AI Expert Policy Roundtable” hosted by Gyeonggi-do, the largest province in Korea. He also discussed potential partnership opportunities with the governor of Gyeonggi-do, who is also a presidential candidate.
In his speech, Illia noted: “AI should be open source instead of closed source. We need to find institutional measures to secure and manage high-quality data based on Web3 technology in the public domain. The combination of Web3 and AI has the potential to act as a pillar of the new policy for mass adoption. NEAR Protocol will be the strongest use case if allowed to become a bridge for onboarding users to Web3”.
Business Meetings and Major Partnerships
Meetings with global companies
NEAR Foundation and NEAR Korea Hub hosted meetings between Illia and the management of major global companies in Korea. There were constructive discussions with companies looking to expand into Web3, which have already shown significant results.
From having small discussions to signing MOUs with major companies including Netmarble and Mirae Asset, the Korea Hub laid the foundation for solid collaboration. This foundation will serve as an important first step in expanding the Web3 industry in Korea.
MARBLEX Partnership — June 5th
NEAR Foundation has joined forces with MARBLEX, a blockchain subsidiary of Netmarble, to Expand Korea’s Web3 Gaming Industry with Aurora. Netmarble is a global top 7 game publisher with 1M+ MAU in the last three games.
Through this strategic business agreement, NEAR Foundation and MARBLEX plan to achieve mutual growth by linking the NEAR blockchain and Aurora with WARP Bridge to enable interactive collaboration, promote global joint marketing events, and enhance brand awareness. Furthermore, competitive and casual gamers alike will now be able to enjoy a variety of games and exclusive content through NEAR’s Blockchain Operating System (BOS).
More information on the NEAR Blog and Twitter.
Mirae Asset Partnership – June 7th
In a pivotal partnership for the blockchain industry, NEAR Foundation is joining forces with Mirae Asset — a subsidiary of Asia’s largest financial group Mirae Asset Global — to help bridge the gap between traditional finance and Web3.
Through this strategic business agreement, NEAR Foundation and Mirae Asset aim to expand the Web3 business domain and lead the global financial paradigm by conducting joint research and collaboration on Real-World Assets Technology. Furthermore, both parties have agreed to organize global joint events to enhance brand awareness and establish a mutual support system to strengthen the Web2/Web3 business network.
More information on the NEAR Blog and Twitter.
Vortex Gaming Onboarding — June 22nd
NEAR Foundation is excited to announce a new partnership with Vortex Gaming, a Web3 subsidiary of the leading game industry INVEN. INVEN is the largest game media·community in Korea, with a monthly active user (MAU) count of 7.2 million.
With the guidance of the NEAR Korea Hub, NEAR Foundation and Vortex Gaming plan to achieve mutual growth by collaborating to support the growth of Vortex Gaming; strengthen the NEAR game ecosystem; conduct offline hackathons and events to foster developer talent; and enhance brand awareness and business networks.
Read the full announcement on the NEAR Foundation blog.
Major Events
Glitch Hackathon Winners Dinner – May 30th
During the Glitch Hackathon, which took place from May 19th to 21st, Illia and the NEAR Korea team organized a meetup event with the participants of the NEAR Track. Despite being a multi-chain hackathon with five mainnets participating, the NEAR Track had the highest number of participants, and PokaTika from the NEAR Track won the hackathon.
NEAR Korea Hub’s constant support throughout the hackathon helped achieve these remarkable results. NEAR Korea Hub provided comprehensive support and mentoring to the participating teams. Furthermore, the meetup event, which was hosted to continuously build the Korean Web3 ecosystem and establish strong relationships with new builders, saw participation from over 70 builders.
It provided builders with valuable opportunities to showcase their products. A considerable number of teams participating in the Glitch Hackathon also took part in the ETHSeoul Hackathon, which serves as evidence of the growth of the domestic builder ecosystem for NEAR Protocol.
ETHSeoul Hackathon — June 2nd – 4th
NEAR Protocol held “NEAR Track at ETHSeoul”, an event for the blockchain ecosystem and community. ETHSeoul served as a platform for discussions on Web3 mass adoption, with participation from 46 hackathon teams (including over 250 builders) and 800 Web3 users.
Among the 46 participating teams, 24 teams chose NEAR Protocol despite the event’s focus on Ethereum, indicating the strong interest and influence of NEAR in Korea.
At NEAR Track, after an intense competition among outstanding teams, the following teams emerged victorious:
1st. Pokatika, is a mobile application that enhances the post-event experience with unique NFT photo cards.
2nd. On Stage(What’s Next), turns artists’ characters and illustrations into NFTs, providing AI training data to NFT holders for integrating them into new AI images.
Co-3rd. AGLIPPA, combines blockchain and AI to democratize artistic creation, allowing anyone to transform personal experiences into everlasting NFT.
Co-3rd. 0xtail, matches football enthusiasts for a football game.
BUIDL Asia — June 6th – 7th
BUIDL Asia 2023 provided a platform for various projects and communities to come together, share insights, and discuss development trends. The event, organized by Erica Kang — a prominent figure representing Korean Web3 women — garnered significant media and corporate attention.
Illia and Alex Shevchenko, co-founder of Aurora, participated as speakers and shared insights on the NEAR ecosystem’s current trends and future prospects. Additionally, NEAR Korea Hub operated a booth at the event, allowing attendees to experience the Blockchain Operating System (BOS) first-hand.
NEAR x Hashed Night — June 8th
NEAR x Hashed Night was a highly successful event co-organized with Hashed, a distinguished venture capital firm representing the Web3 industry. The event witnessed the participation of 35 partner companies and an impressive attendance of 410 individuals. Illia led the event alongside key executives from the NEAR ecosystem who served as distinguished speakers. They provided insightful introductions to NEAR Protocol and its notable projects, facilitating valuable networking opportunities for all attendees.
Speakers like Alex Shevchenko, co-founder of Aurora, Bowen Shen, co-founder of Proximity Labs, and Ran Yi, co-founder of Orderly Network attended the event. Representatives from Mirae Asset and MARBLEX, who recently formed a strategic partnership with NEAR Foundation, were also present. It was amazing to see so many major Web2 and Web3 companies in one place, as it created a fantastic opportunity to explore new business prospects.
As one attendee noted: “The place was so crowded that it was running out of oxygen”. This achievement was made possible thanks to NEAR’s growing reputation in the Korean Web3 industry and the onboarding of numerous builders through Glitch and ETHSeoul Hackathon.
NEAR Korea is really excited about NEAR’s upcoming events, including Korea Blockchain Week(KBW), and they look forward to high expectations and participation!
Raising NEAR awareness in Korea
Overall, Illia’s time in Korea along with the hard work of NEAR Korea Hub has greatly enhanced the awareness and influence of NEAR Protocol within Korea. This was made possible through the active support of the NEAR Foundation and the strong collaboration with ecosystem partners. |
```js
import { Wallet } from './near-wallet';
const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near";
const FT_CONTRACT_ADDRESS = "ft.primitives.near";
const DROP_AMOUNT = "10000000000000000000000";
const wallet = new Wallet({ createAccessKeyFor: KEYPOM_CONTRACT_ADDRESS });
await wallet.callMethod({
method: "create_drop",
contractId: KEYPOM_CONTRACT_ADDRESS,
args: {
public_keys: state.publicKeys,
deposit_per_use: DROP_AMOUNT,
ftData: {
contractId: FT_CONTRACT_ADDRESS,
senderId: accountId, // TODO How to get account id
// This balance per use is balance of human readable FTs per use.
amount: "1"
// Alternatively, you could use absoluteAmount, which is dependant on the decimals value of the FT
// ex. if decimals of an ft = 8, then 1 FT token would be absoluteAmount = 100000000
},
},
deposit: "23000000000000000000000" // state.publicKeys.length * dropAmount + 3000000000000000000000,
gas: "100000000000000",
});
```
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |
---
title: 3.1 Understanding DeFi
description: Decentralized Finance and the Future of Finance
---
# 3.1 Understanding Decentralized Finance and the Future of Finance
The basis of Decentralized Finance is grounded in the notion of protocol shared liquidity or pooled value. If we think about this on a macro level, especially as compared with existing finance, we need to turn our current understanding up-side-down:
In the existing financial system, the bank as an entity holds your money for you and issues you credit. Value is locked behind the walls of the financial entity and primarily kept between multiple different financial institutions.
<> – <> – <>
When I would like to execute a trade, I am sending the bank's money, labeled as my money, to an intermediary, from which I then exchange that value for another type of value. And here is the interesting, part:
A third party, usually a market maker or a financial institution itself, helps ensure that the market I trade on is sufficiently liquid. Meaning there is enough underlying value in the market to allow for the quick and easy exchange of value between different parties.
Notice that in this system, the exchange of value is largely designed around the complimentary dynamics of different centralized entities:
* A suite of banking institutions or credit institutions.
* Market makers / liquidity providers.
* A centralized exchange or an intermediary, designed to specifically facilitate this process.
The key premise of decentralized finance, is that liquidity for markets can be pooled on-chain, in such a manner that the code handles the accrual of value from which a market or financial service can be created. The specific DeFi primitive is then built around the activity that the user can engage in, with this shared liquidity pool.
_“For the first time what we have is a potentially digitally native store of value where the bits in the computer are the money, which is very different from the existing financial system where you do have a ledger and the bank has an entry that says you have such and such money. But it is really just an IOU from the bank - if you go to the bank they will give you some cash. It’s not that the bits in the computer are the money. So if you take that one step further and say, if the bits in the computer are the money, why is that interesting? Well it is interesting because now what that means is that computers can own money. Computers and machines and software can take custody of money. And so for the first time, a human can pay a machine without another human in the loop. Or a machine can pay another machine without a human even being involved. And if you play that forward, one step forward, you say, well, ‘why is that interesting?’ Well it is interesting because there is a set of stuff that computers are better than humans at - and strictly speaking there is only one thing that computers are better than humans at - and that is that computers are better than humans at deterministically executing some set of instructions on some future time horizon. That is literally what computer code is: Do this and the same thing happens every time. If you think about the world, a lot of the world is ‘here is a huge pile of money’ and ‘here are a bunch of rules about that money’ - who has access to that money, and when that money can move and on some future time horizon I need you to execute some set of instructions: That’s a will, that’s a trust, that’s an escrow, that’s a mortgage, that’s a heloc, that’s an options contract, it’s a securities contract, like literally a hundred trillion dollars of the world is ‘here is a pile of money and here is a bunch of rules around that money and how that money can move around.’ So now what you have is an infrastructure where money is digital, computers can take ownership of money, and since computers are strictly better at executing instructions, it is such a perfect match for this hundred trillion dollar slice of the world that has previously been untouched because software couldn’t actually solve those problems natively that we think over the next 20 to 30 years this programmable money stack is just going to eat up that 100 trillion dollars of the world. It feels to us a lot like the early 1990s…” - OpenWebCollective_
There are a couple of ways we can look at ‘Decentralized Finance.’ On its most fundamental level, it is the organization of liquidity, behind certain ‘tokenized’ representations of value. On a more advanced level, it is how these already existing primitives are able to interact with one another.
<center>DeFi 1.0 - Basic Liquidity Primitives. </center>
<center>DeFi 2.0 - Composability between value flows of DeFi 1.0.</center>
<center>Composable DeFi - New building blocks of liquid primitives in the form of tokenized value.</center>
<br/>
<br/>
In its current state, DeFi has existed for less than five years, and has only recently accrued sufficient liquidity to initially ‘stress test’ the fundamental design of DeFi 1.0 products, and a select few DeFi 2.0 products. We stand at the very, very beginning of this industry cluster. In order to properly understand the promise of DeFi and how it relates to the future of finance, we can start by comparing it to existing Centralized Finance, as well as TradeFi:
## DeFi Compared to Centralized Finance and TradeFi
Compared to CeFi, DeFi purports to do the following:
<br/>
<br/>
* Automate access to finance based upon smart-contracts on-chain, removing human and institutional bias against past behavior of certain actors.
* Value and reserves of liquidity are ‘communally sourced’ by different stakeholders as opposed to centrally created or mandated from a Federal Reserve (and then distributed to commercial banks).
* Access is global and participation is only limited to your access to the internet and your capacity to participate in the ‘rules of the protocol’.
![](@site/static/img/bootcamp/mod-em-3.1.1.png)
Meanwhile, DeFi in relation to TradeFi diverges strongly in the following areas:
* In DeFi there is continuous revenue accrual, with fully transparent metrics on the growth and success of the protocol. In TradeFi shareholders owning stock are rewarded annually, and are also reliant on ‘earnings reports’ to be released.
* Access to tokens is global with no barrier to entry: Any individual of any age, with an internet connection and sufficient capital can participate in token offerings and purchases. Whereas, in TradeFi individual markets are built around specific rules from different jurisdictions.
![](@site/static/img/bootcamp/mod-em-3.1.2.png)
**Understanding DeFi in the History of Transaction costs: New Institutional Economics and Theories of Growth.**
The comparisons above of DeFi between CeFi and TradeFi, are especially relevant for attempting to make sense of the inherent value proposition of DeFi to the global economy and financial markets - at scale. This is most easily explained, surrounding the notion of _transaction costs:_
A transaction cost refers to the expenses incurred from the exchange of materials or services between economic agents.[^1] As this exchange is the crucial determinant of marginal utility and supply and demand dynamics within a market, transaction costs are directly related to the health and performance of an economy: low transaction costs, allowing for more frequent and fluid exchange of goods, bolsters economic growth. High transaction costs, resulting in less frequent and more costly exchange of goods, hinders economic growth.
DeFi offers the world the ability to drastically reduce transaction costs - not only between two humans, but between two software systems, managed by smart contracts! This improvement in how value is managed, holds the promise of:
1. Increasing the flexibility of transactions - from anywhere, any time, with liquidity already available (no more waiting for liquidity events!).
2. Increasing the rate and trust inherent to transactions - moving beyond institutions, jurisdictions, and geopolitical interference, to simple self-executing code on massive open, public ecosystems.
3. Increasing the ease with which users can participate in transactions with one another or code itself - Accessing the internet is the only barrier to entry, no one requires a license, there is no ‘credit check’, or ‘gated community’ and anyone in the world can participate.
While we are only at the very, very beginning of the emergent world of decentralized finance, from both a practical and theoretical perspective, it is clear that DeFi is well positioned to radically transform the ‘game’ for how money is routed and shared globally.
## A Broad Look at DeFi Protocols:
Amidst buzzwords and confusing terminology, it is easy to come to a very simple model for making sense of a DeFi protocol, once it becomes clear that the fundamental value proposition revolves around distributed liquidity, and how the distributed liquidity interacts with user behavior and the tokenization of value:
<br/>
When you look at a ‘DeFi’ project, you start by understanding it through the following lenses:
<br/>
<br/>
* What activity is the user engaging with? In short, the ask - to lend, trade, stake, collateralize, swap, etc.
* How does that activity impact the liquidity that is supplied on the protocol? From what the user is provided, is a new asset created? The user asset swapped for another one? And so forth.
* How does the dynamic between user activity, and protocol liquidity change with 1) more users, 2) more liquidity, 3) drastic loss of users, and 4) drastic loss of liquidity?
* How does the protocol take profit, and where is that profit directed?
* Is there a token for the protocol and what is its utility or purpose?
And importantly, it is much easier to make sense of a single DeFi protocol or dApp, once you understand how they may interact with one another: For example, stable coins like USDC and USDT as a mechanism for stable swaps on DEXs. This framework is a simple way of getting a _basic understanding_ on how a decentralized financial system may operate.
## A Nomenclature of DeFi Tooling
Zooming in even further, when we look at specific DeFi projects, there are certain variables that tend to remain relevant irrespective of the exact design of the product in question. These variables include:
* **Asset Tokenization:** What tokens are involved? How many are listed on the protocol in question? What is the nature of the tokens? Are there different types of tokens?
* **Protocol Owned Liquidity:** Where does the liquidity come from on the protocol? Are there terms for locking the liquidity? Who sources the liquidity? How stable has the liquidity been over time?
* **Total Value Locked:** How much value is locked on the protocol in a liquidity pool?
* **Volume:** How much value is actively utilized on the daily? This could be traded, collateralized, loaned, and so forth.
* **Transaction Costs:** How much does it cost to operate a transaction on the protocol?
* **Yield:** What incentives are there for liquidity providers to pool their liquidity on the protocol? How does this change based on the types of tokens pooled as well as the duration of time they are pooled for?
* **Liquidations / Removals:** Are any positions closed based on market dynamics? Are any liquidity providers removing their liquidity? How frequently and comparative to the amount of inflows?
* **Fees / Revenue:** Does the protocol charge a fee for participation? How much revenue does the protocol make over different time frames? What impacts revenue of the protocol?
## The DeFi Matrix
The DeFi Matrix [was coined by Balaji in early 2021](https://twitter.com/balajis/status/1364626032771272706), to refer to the capacity for any type of asset, currency, or token to eventually be tradeable against each other. This would apply first between Fiat systems and stable coins on-chain, and then expand into the larger world of tokenized stocks, bonds, commodities, tokens, NFTs, and so forth.
<br/>
The implications of this DeFi matrix are the following:
<br/>
* **Composability Across Systems:** Fiat / Stable coin pairs, Fiat / Crypto pairs, crypto / crypto pairs, synthetic / crypto pairs, and so forth. To the extent that any type of asset can in principle be paired with another asset for swapping and trading.
* **Liquidity vs. Currency:** When swaps across different composable pairs becomes more common, the need for ‘cash’ or a specific currency is less relevant or needed.
* **Constant Liquidity vs. Liquidity Events:** Traditionally, liquidity events would allow funds and participants to open or close positions as they like when there is a liquid market capable of supporting their order. In DeFi, liquidity is constantly open to add or remove from pools, from anywhere at any time.
## DeFi Today - and the Future Tomorrow?
Before we look into specific examples for these different types of systems, we need to understand what code-secured finance means for the future of financial systems.
Today, we operate in a curious monetary environment where money is centered around the nation state, and where international finance between institutions is very frequently siloed, slow, and bureaucratic.
The fundamental question that DeFi proposes is the following:
_How can contract-based execution of financial activities - built into the very fabric of the internet - alter how we handle value; locally, nationally, and globally? How do new forms of tokenized value moving on-chain impact the development of DeFi?_
While we will revisit these questions towards the end of this module, it is no exaggeration to say that DeFi is an initial foray into this new future of finance. Entities[ like BlackRock already see the writing on the wall:](https://twitter.com/Vic_Vinegar_GMI/status/1598905515253575680?s=20&t=L5w9RT3v_px1pgX0flLNWQ) The future of finance is one that is global, decentralized, operating at internet-speeds, and accessible for anyone. And if you are listening to this, you should pay very close attention because you are going to be building this future over the coming three decades.
---
## Notes
[^1]:
Ronald Coase, “The New Institutional Economics,” _The American Economic Review_ 88, no. 2 (1998): 72 – 74, 73. |
---
id: nfts
title: NFTs for Web 2 Applications
sidebar_label: NFTs for Web 2.0 Apps
---
# NFTs for Web 2 Applications
At the first stage of our Web 3 transformation, let’s decentralize ownership of our digital assets using blockchain technology. By doing this, we can create a user-owned economy, where digital assets are exchanged and traded without any participation or control from the developers. Later, we’ll discuss how to bring it to the next level by adding Fungible Tokens into the mix.
As we discussed previously, in the Web 3 world, NFTs are used to represent ownership of an asset. This can be anything a user owns, e.g. in case of a game this can be a character, upgrade, crafting material, skin, etc. However, since NFTs are living on the blockchain, and the rest of the application resides on traditional servers, we need to find a way to connect these different worlds together.
## Blockchain-Enabled Application Architecture
First of all, let’s outline a typical architecture of a Web 2 application. In most cases, a classic client-server model is used:
<div align="center">
<img src="/docs/assets/web3/nfts-1.png" alt="image" width="150" />
</div>
In such architecture, we usually have 3 layers:
- Database - stores application’s data. This can be a single database, or several databases of different types, but this is mostly an implementation detail - for our purposes we can view it as a single logical database.
- Server - a centralized web-server. It may be implemented using different architecture patterns (monolithic, microservices, serverless) and technologies, but again, we can consider it as a single logical server.
- Client - client side application user directly interacts with. Different client types are possible: web, mobile or desktop. There is a difference between these clients in regards to blockchain integration, which we’ll discuss later.
Now, let’s compare it to a dApp architecture:
<div align="center">
<img src="/docs/assets/web3/nfts-2.png" alt="image" width="400" />
</div>
We can notice that there is a common component in these architectures - the client application. This means we can use it as a junction point to connect them together.
<div align="center">
<img src="/docs/assets/web3/nfts-3.png" alt="image" width="400" />
</div>
A keen reader may notice an additional connection between the Server and RPC Node. This is required because in a client-server architecture clients cannot be trusted. That’s why every action performed from the client should be validated by a backend server. But in our case everything is complicated by the fact that we essentially have two backends: Web 2 server and a smart contract, so two possible validation flows are possible:
- Client performs an action on a server, which involves blockchain data. In this case the server should talk to the blockchain and verify that valid data is provided.
- Client performs an action on a smart contract, which involves server-owned data. Since the smart contract can’t talk to the server directly to verify it, we should use a different way to verify the authenticity of the data. In blockchain terminology, such a server is called an [Oracle](https://en.wikipedia.org/wiki/Blockchain_oracle).
We’ll explore how to implement both of these approaches later.
By now, we've reached the point where the type of our client begins to matter. Specifically, problems arise from the dApps payment model - user’s pay for the blockchain infrastructure using gas, so money goes directly to infrastructure providers. Also, users make payments directly on the blockchain, without using any intermediaries, like banks or payment services. This approach is at odds with mobile app stores (Google Play Store and Apple App Store) - they don’t allow any payments on their respective mobile platforms without their cut. Although some shifts in policy are starting to happen (e.g. [Apple vs Epic Games duel](https://en.wikipedia.org/wiki/Epic_Games_v._Apple)), at the time of this writing getting blockchain-enabled applications into the stores will probably get vetoed by reviewers. There are some ways to bypass these limitations, e.g. by not using Play Store on Android, but all of these ways are either sub-par in terms of usability or involve some risk of getting banned by stores. That’s why for mobile applications an alternative approach is needed.
Sometimes, to move forward we need to take a step back. In our case, to solve a problem with mobile clients we can return to our initial concept of having two clients - one for blockchain integration, and another one for Web 2 server. Blockchain client can be a usual web application, which isn’t subject to any constraints from stores. It can also serve as a connection point between blockchain and our existing application.
![image](/docs/assets/web3/nfts-4.png)
In this architecture the mobile client is still allowed to talk to the blockchain, but only in a read-only way, which doesn’t require wallet connection or any payments. All actions on the blockchain happen on the Web Client instead.
Further in this guide we’ll use such dual-client architecture, since simpler architecture with a single client can be directly derived from it by merging two clients together.
At this point, our architecture covers almost everything we need to start building our application. However, since we want to build a user-owned economy, we need a marketplace where it’ll happen. An obvious choice is to put this marketplace into the web client, but there’s one gotcha. If we recall the smart contract’s storage model, it’s not suitable to serve complex data queries, so an indexer should be used to aggregate data from blockchain into a proper database.
![image](/docs/assets/web3/nfts-5.png)
By now, every building-block is in place and we can start exploring how to implement this architecture in practice.
## NFTs in Web 2 Applications
In order to implement a fully functional application using a hybrid Web 2 - Web 3 architecture, a lot of technological challenges have to be addressed, like authentication and authorization, seamless NFTs usage in client and server, and proper NFT storage model. In the following sections we’ll take a closer look at this and describe common patterns and approaches.
### Authentication and Authorization
Since our digital assets are represented as NFTs on blockchain, in order to use them in our Web 2 application, a server needs a way to authorize their usage. The basic idea is pretty simple - it can just read data from blockchain by calling a smart contract method and check an owner’s account id. For such flow, we have 3 actors:
* Client that wants to use some digital asset (NFT).
* Smart Contract for NFTs. Should be implemented according to [NEAR NFT standards](https://nomicon.io/Standards/NonFungibleToken/).
* Server that verifies ownership of NFT and uses it in its internal logic.
A general flow looks like this:
![image](/docs/assets/web3/nfts-6.png)
However, such an authorization process cannot be performed without authentication, so the server also needs a way to authenticate a user.
Recall that the user's identity on a blockchain is represented by a key pair. However, since in NEAR a user may have multiple key pairs and an account is a separate entity, the authentication procedure is a bit more complicated.
To authenticate our requests, we can use public-key cryptography - a client can sign a request using a user’s private key, and then a server can verify the signature and key ownership. A typical request with authentication may look like this:
```javascript
{
"payload": { /* request-specific payload */ },
"accountId": "account.near",
"publicKey": "...",
"timestamp": 1647091283342,
"signature": "..."
}
```
where:
* `accountId` – user’s account id on NEAR.
* `publicKey` - public key of the key pair used for signature, must be either Functional or Full access key for the provided account.
* `timestamp` - current datetime, must be verified on server. It’s needed to prevent [replay attacks](https://en.wikipedia.org/wiki/Replay_attack). Alternative to timestamps is usage of [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce), but it’s more complicated.
* `signature` - signature of the request payload and other fields. Usually, a payload is hashed beforehand.
Depending on the implementation, request body, headers, or other side channels can be used to transfer authentication data - exact implementation depends on used technologies and protocols.
Server can use this data to authenticate a request using the following approach:
![image](/docs/assets/web3/nfts-7.png)
3 authentication steps are performed on the server:
1. Signature verification - if the signature is correct, we are sure that the client really has the private key for the provided public key. Also, this proves that request data hasn't been modified in transit.
2. Timestamp verification - prevents replay attacks. Server can verify that the request’s timestamp is not too old (e.g. has been created no more than 10 seconds ago).
3. Public key ownership verification - by calling [view_access_key method](../../5.api/rpc/access-keys.md), we can make sure that the provided public key is really associated with the provided account.
Such authentication approach is the simplest one, but has a few major drawbacks:
* Performing a REST API call to RPC Node is quite expensive to do each time from the performance perspective.
* We can’t sign requests from the mobile client, since it usually should be disconnected from the blockchain due to store policies, and hence doesn’t have a key pair.
* A NEAR account is required in order to start using the application, which complicates the onboarding process.
To solve the first problem, we can simply issue a JWT token or authenticate connection in some other way after a successful NEAR account authentication, so the it will serve as “login” of sorts:
![image](/docs/assets/web3/nfts-8.png)
While this may be enough for some applications, it doesn’t address the last 2 problems. In order to solve all of them, we can use a hybrid authentication approach with 2 accounts:
1. “Classic” Web 2 account - all clients can use this account to call a server. For example, this can be a simple username/password or OAuth 2 login with a JWT token.
2. NEAR account - can be used from non-mobile clients only. Instead of performing NEAR account auth each time we need to use it, we can do it a single time in order to “connect” this account to our primary Web 2 account and store Classic-NEAR account connection in our server database. In this way we solve all problems - server doesn’t need to authenticate NEAR account each time it wants to perform an authorization, instead it can read an associated NEAR account from its own database.
With such hybrid approach, different authentication methods are used for blockchain and server:
<div align="center">
<img src="/docs/assets/web3/nfts-9.png" alt="image" width="400" />
</div>
NEAR account connection sequence can be implemented in a very similar way to the already described NEAR authentication method, where at the end we store an authenticated account in our database:
![image](/docs/assets/web3/nfts-10.png)
There’s one more improvement we can make to this flow. Since a Web Client uses both accounts, a user is forced to login using both Web 2 login method (e.g. login/password) and NEAR Wallet. This is not ideal from the UX perspective, so we can simplify it by introducing a “Login with Wallet” method to our server, which would work when a user already has a wallet connected. We can do this in a similar way to the account connection flow:
![image](/docs/assets/web3/nfts-11.png)
Now, as we’ve discussed possible approaches for authentication, let’s summarize it as an overall login flow for our clients:
![image](/docs/assets/web3/nfts-12.png)
Of course, this is just one possible flow, and a different solution can be assembled from described building blocks. The most important considerations for choosing right authentication flow are following:
* Type of your client - for web/desktop clients, or sideloaded Android clients, it’s possible to use Wallet as a single authentication method. For mobile clients installed from a store, a hybrid approach with multiple auth methods should be used.
* Target audience - if you target regular users that are not familiar with blockchain technologies, having a hybrid auth method to simplify onboarding might be better than forcing users to learn blockchain before trying your application.
#### Blockchain Auth & Auth
So far, we’ve discussed authentication and authorization on the Web 2 server’s side. But what about Web 3 smart contracts? Everything is much more straightforward in this case.
Since everything is public data on the blockchain, we don’t need any authentication for read calls. For transactions, each is signed by an account’s private key, and authentication is performed by the network. More details on transaction signing can be found [in the docs](../protocol/transactions.md).
Authorization, on the other hand, must be performed on a smart contract itself, the simplest way is just to check whether caller is allowed to perform an action:
```rust
assert_eq!(
env::predecessor_account_id(),
self.tokens.owner_id,
"Unauthorized"
);
```
### NFT usage
After we’ve learned how to authenticate users and how to authorize NFTs usage, let’s find out how we can actually use them in our application.
Since we essentially have two backends in our application - server and smart contract(s), they both can use NFTs for different purposes:
* Server usually uses NFTs for actual functional purposes, e.g. by treating NFT as an in-game character, it can read its properties and stats and apply them using some logic.
* Smart contract is responsible for NFTs ownership, as well as NFTs creation, modification and burning (destruction).
This is the point where the NFT data storage model comes into place. Let’s recall, that there are 3 possible options:
1. Store data in a smart-contract (on-chain).
2. Store data in an [off-chain decentralized storage](../../1.concepts/storage/decentralized-storage.md), like IPFS (off-chain).
3. Store data in an application itself (in-application).
First 2 approaches provide good decentralization, but make NFT harder to work with, especially if we need to modify its properties. Let’s consider usage options depending on a storage model used:
1. On-chain storage:
* Server can read data from the blockchain by making an API call. Server can’t directly modify data, it should make a smart contract call instead (by issuing a transaction).
* Smart contract can directly read/modify NFT data.
* Clients can read all data directly from the blockchain.
2. Off-chain storage:
* Server can read data from storage by making an API call. Data on the off-chain storage is usually immutable, so no modifications are possible.
* Smart contract cannot read data directly, an Oracle should be used. Data cannot be modified from it.
* Clients should read data from both blockchain and off-chain storage.
3. In-application storage:
* Server can read/modify data from its own database.
* Smart contract cannot read data directly, an Oracle should be used. Data cannot be modified from it.
* Clients should read data from both blockchain and server.
Depending on a particular use case, any approach, or combination of them, can be used. The simplest case is when we don’t have any dynamic NFT data, and we can easily divide data by domains:
* Data that is used by smart contracts is stored on-chain.
* Other data is stored either off-chain or in-application.
<div align="center">
<img src="/docs/assets/web3/nfts-13.png" alt="image" width="400" />
</div>
In this approach the server needs to read data from the smart contract, and, optionally, from an off-chain storage (like IPFS or Database).
This will work well for simple use cases, but everything becomes more complicated if we need to have some dynamic data associated with NFTs. E.g we may want to have experience points associated with our game character. Such data can be stored either on-chain or in-application (off-chain storage is also possible, but it’s more involved, so we won’t discuss it here).
In case of in-application storage, data can be modified by a server without any problems, but there are few drawbacks:
* In order to read this data, clients should make an API call to the server. This adds a centralized point for our NFT, and may not be suitable for all applications.
* If a smart contract requires this data, a server should serve as a [Blockchain Oracle](https://en.wikipedia.org/wiki/Blockchain_oracle), which complicates things.
If we want our server to serve as an oracle for our smart contract, the easiest way is to cryptographically sign server’s data and verify it on the contract’s side (server’s public key that was used for signing should be stored in a contract in this case).
In order to prevent replay attacks, signed data should include a timestamp, which should also be verified. However, there’s one trick to this - smart contracts can’t access current time, since it would make them non-deterministic. Instead, transaction signature time can be used - it can be accessed using `env::block_timestamp()` function.
![image](/docs/assets/web3/nfts-14.png)
In order to avoid all these complications, we can instead store dynamic data on-chain, and use smart contract calls to update it.
<div align="center">
<img src="/docs/assets/web3/nfts-15.png" alt="image" width="500" />
</div>
Such an approach has one drawback - in order to call a smart contract’s method, a transaction should be created by the server, and in order to create a transaction it must be signed using an account’s key. That’s why a separate NEAR account should be created to be used by the server. Actions on the smart contract can be configured to authorize only this account, so regular users will be disallowed from modifying such data.
Yet another option is to store data on the server-side, but a smart contract can authorize only a server account for calls that rely on this data. As with the previous scenario, the server must have its own NEAR account.
<div align="center">
<img src="/docs/assets/web3/nfts-16.png" alt="image" width="500" />
</div>
In general, the approach of storing dynamic data on the Smart Contract side is much easier, but an important constraint should be considered - storing data on the blockchain is not cheap, so an appropriate method can be chosen depending on a scenario.
By now, we’ve covered methods to store and interact with NFTs from our application, an exact strategy should be chosen depending on use cases and constraints. A few things to remember:
* Storing NFTs data in a centralized storage (like an application's database) goes against Web 3 philosophy, and should be used sparingly and with care.
* Storage on the blockchain is not cheap, so decentralized off-chain storages can be used to store large data.
* Storing and using dynamic NFT data is quite tricky, and should be carefully designed. If such dynamic data is needed by smart contracts, it’s better to store it inside this contract if possible.
### NFT minting
So far, we’ve discussed only how to use NFTs in the application, but how do they get created?
In the blockchain world, creation of new NFTs is usually called minting. And as with traditional digital assets, there are few ways how to create them:
* Users can mint them directly. This can be done by either allowing creation of NFTs from scratch, or by using more complex processes, like breeding or upgrading. The most famous example of such process is breeding in [CrytoKitties](https://www.cryptokitties.co/) game - new NFTs are created by combining existing ones. With this approach users usually have to pay to cover the storage and gas cost of NFTs creation.
* NFTs can be distributed by the developer to a set of users - it is usually called [NFTs airdrop](https://www.investopedia.com/terms/a/airdrop-cryptocurrency.asp). Most often this is used as a marketing strategy to kickstart NFTs usage in applications. Storage and gas costs in this case are covered by developers.
* NFTs can be bought on a market or obtained from the lootbox. Depending on an exact strategy, costs can either be paid by a user or by developer. Also, in this case NFTs sometimes can be minted on-demand, to avoid paying upfront costs.
An exact strategy used for NFTs minting depends on application use cases. However, almost always there’ll be an `nft_mint _function` defined in a smart contract, which will handle creation of new tokens. This function itself isn't defined [in the standard](https://nomicon.io/Standards/NonFungibleToken/) and is up to the application to implement, but the standard library provides a core implementation for it - [mint_internal](https://docs.rs/near-contract-standards/latest/near_contract_standards/non_fungible_token/core/struct.NonFungibleToken.html#method.internal_mint). On top of this function an additional logic, e.g. for authorization, can be added:
```rust
#[payable]
pub fn nft_mint(
&mut self,
token_id: TokenId,
receiver_id: AccountId,
token_metadata: TokenMetadata,
) -> Token {
assert_eq!(
env::predecessor_account_id(),
self.tokens.owner_id,
"Unauthorized"
);
let token = self
.tokens
.internal_mint(token_id, receiver_id, Some(token_metadata));
return token;
}
```
This approach is quite simple, but everything becomes a bit complicated if we want to provide some on-demand minting functionality to avoid paying upfront costs. For example, we may want to create a lootbox with a set of predefined items appearing with some probability.
One approach is to handle this logic on a server side, in this case the server will call `nft_mint` function with computed parameters. However, in this case developers will have to pay the cost of minting. If we want to avoid this, loot box logic can be moved into the smart contract itself. If users want to open a loot box, he can call a smart contract function and pay for this action (e.g. by using NEAR or Fungible Tokens). Developers would only need to pay for a lootbox configuration costs, like possible items and their probabilities.
## Blockchain Onboarding
Before designing an onboarding strategy, the target audience should be carefully analyzed. As we briefly mentioned before, users can be divided into two broad buckets:
1. Users that are already familiar with blockchain, have their own wallets and understand cryptocurrency basics.
2. “Casual” users that aren’t familiar with blockchain and don’t know much about it.
If only the first category is targeted, then everything is quite simple - users are already familiar with main concepts, and will have no problem connecting their own wallet or creating a new one. However, if we want to target the second category of users as well, a strategy has to be developed to make onboarding into the blockchain world as smooth as possible. While a lot relies on proper UX and is very application-specific, a few architectural patterns and technologies exist to simplify this process: custodial wallets, NEAR drops, Prepaid Gas and Implicit Accounts.
[Custodial Wallet](https://www.coindesk.com/learn/custodial-wallets-vs-non-custodial-crypto-wallets/) is a wallet which is managed by a third party. In our case, a wallet can be created and stored on a server side, and all blockchain operations could be done using the server as a proxy.
![image](/docs/assets/web3/nfts-17.png)
In this way, users can remain unaware about the intricacies of blockchain until they are comfortable enough to claim ownership of this account. Once they are ready, the server can transfer the account's ownership and remove it from the server. However, despite simplifying UX for the users, such approach has a few significant drawbacks:
* Users should trust our application to manage their accounts.
* Accounts creation is not free, so unless developers want to pay for it, funds should be transferred from a user to cover this cost. Traditional payment methods can be used, like PayPal or Apple/Google Pay. However, such an approach should be used with care for mobile applications due to app stores policies. Alternatively, NEAR Implicit Accounts can be used to avoid paying for account creation.
* Unless we want to leave a custodial wallet as the only supported wallet type, we need to support both types of wallets (custodial and non-custodial) in our application. This will increase implementations complexity, since we need to support 2 transaction types:
* Server-signed transactions in case of custodial wallet.
* Client-signed transactions in case of non-custodial wallet.
As we mentioned above, [Implicit Accounts](../protocol/account-id.md#implicit-accounts-implicit-accounts) can be used to avoid paying account creation costs. This is especially useful for custodial wallets, since it allows us to create a NEAR Account free of charge. Basically, they work like an Ethereum/Bitcoin-style account by using a public key as an account id, and later can be converted to a full NEAR account. However, they have drawbacks as well. First of all, human-readable account names cannot be used. Also, if we want to convert it to a proper NEAR account, which can support Functional Call keys, the account creation fee still has to be paid.
While being very powerful, custodial accounts are quite complex and tricky to implement. An alternative approach to ease users onboarding is to simplify creation of a wallet itself. In NEAR, we can do this using [NEAR Drops](https://near.org/blog/send-near-to-anyone-with-near-drops/). It allows us to generate a link that guides users through a quick wallet creation process. However, the same problem as for the custodial accounts applies - creation of an account is not free. That’s why, such a link has NEAR tokens attached to it to cover account creation cost and to serve as an initial balance for a newly created wallet. And as with custodial accounts, funds should be transferred from a user to cover this cost using traditional payment channels.
Another option to simplify onboarding is usage of the [Prepaid Gas](../protocol/gas.md#what-about-prepaid-gas-what-about-prepaid-gas) concept. For example, we can issue a Functional Call key that allows users to interact with blockchain without having an account created. In this case funds will be drawn from the developer's account. This can be used for demo purposes, or to allow users without a NEAR account to perform some smart contract actions.
## NFT Marketplace
At this point, we’ve covered in detail how to integrate NFTs into our Web 2 application, but we’ve stayed away from the economy part. The essential part for having a functioning economy is a marketplace where users can freely trade and exchange their NFTs. Such a marketplace usually consists of a smart contract and a client application. This smart contract is closely integrated with a NFT’s smart contract using the cross-contract calls. The reason for having a separate smart contract is two-fold:
* This provides a better separation of concerns - we can modify and upgrade our marketplace independently from the NFT contract.
* Multiple marketplaces can be used - e.g. we can have an internal marketplace, and in addition to it users can list their NFTs on external marketplaces. This is possible because a common NFT standard exists that all marketplaces can rely on.
General flow of a simple marketplace integration can look like this:
![image](/docs/assets/web3/nfts-18.png)
1. Client calls the [nft_approve](https://nomicon.io/Standards/NonFungibleToken/ApprovalManagement#2-approval-with-cross-contract-call) method on the NFT smart contract. This will approve Marketplace Smart Contract to sell this NFT.
2. After approving an account, NFT smart contract issues a cross-contract call to the Marketplace to create a sale object. Arguments for this call are provided as part of the `nft_approve` call.
3. Another user wants to buy the NFT on sale, so he issues a call to the marketplace contract offering to buy it. An exact call signature for such action is not standardized and depends on marketplace implementation.
4. If an offer to buy a NFT is valid, Marketplace issues an [nft_transfer_payout](https://nomicon.io/Standards/NonFungibleToken/Payout) call to transfer the NFT and return payout information. This information is used by the Marketplace to distribute profits from the sale between recipients. In the simplest case, all profits go to a seller.
Such flow looks relatively simple, but a few important details are missing.
First of all, in order to create a sale, storage needs to be paid for. Usually, the seller is the one who needs to pay for it, but other models are possible - e.g. marketplace or application developers could cover the cost. If we want users to pay for a sale, an approach with storage reservation can be used:
* Before approving NFT for sale, a user should reserve storage on the Marketplace contract to cover sale storage requirements.
* After the NFT is bought or delisted, the user can withdraw storage reservation (remember, that in NEAR storage staking model is used, so data can be deleted and locked tokens refunded).
While this model is relatively straightforward, it’s not ideal from the UX perspective - users must make a separate action to reserve storage if they want to sell their NFTs. To improve this, we can combine `nft_approve` call with storage reservation, and automatically refund back the storage cost after the sale is removed.
![image](/docs/assets/web3/nfts-19.png)
Another missing thing is how a client can read data about available sales. Of course, sales information can be read directly from a smart contract, but available data structures are not optimized for searching or filtering. Also, we would have to join data from the NFT and Marketplace contracts on the client side, which isn’t efficient. In order to solve these problems, an indexer can be used to aggregate data into a suitable database, where data can be stored in a way optimal for retrieval (e.g. a relational database or an ElasticSearch index can be used).
![image](/docs/assets/web3/nfts-20.png)
This is just one example of how a marketplace can be designed, but with it we’ve covered all basic concepts and problems. Most important points to remember:
* It’s better to implement a marketplace as a separate contract.
* Storage management should be carefully designed, with UX in mind.
* In order to implement a proper searching/filtering functionality, a separate indexing service is needed.
An example of a simple marketplace [can be found here](../../3.tutorials/nfts/8-marketplace.md). A more sophisticated marketplace may allow purchases with Fungible Tokens as payment.
## Implementing Components
Now, let’s explore our choice of libraries, frameworks and third-party solutions that can be used to implement our architecture.
#### Client & Server
First of all, how can we interact with blockchain from our clients?
If we need read-level access only, we can simply use the [REST API](https://docs.near.org/api/rpc/setup), so it can be integrated into any language and technology without any problems. But everything becomes more complicated if we need to post transactions from a client. Remember, that transaction should be signed with a private key which is stored in a wallet:
* In case of a Functional Call key, it can be obtained from the wallet and used directly by the client.
* In case of a Full Access key, the user should be redirected to the wallet to approve a transaction.
A [JavaScript API](/tools/near-api-js/quick-reference) exists to cover all of these scenarios. It has all of the necessary functionality to integrate Web/Node.JS applications with blockchain. This SDK is a perfect choice for the Web-based clients, but it’s not suitable for desktop or mobile based clients. Other libraries can be used for them:
* [.NET Client](https://github.com/good1101/NearClientApi/tree/master/NearClient) - suitable for Unity or Xamarin.
* [Swift](https://github.com/near/near-api-swift)
* [Python](https://github.com/near/near-api-py)
* [Unity](https://github.com/near/near-api-unity)
Same SDKs and libraries can be used for servers. The only difference is that a server cannot interact with a Wallet, so it must have access to a Full Access key, which should be stored and accessed in a secure way.
Also, another solution is available if a server uses a technology that doesn’t have NEAR SDK available for - we can create a separate (micro)service using the Node.js, which would handle all blockchain interactions:
<div align="center">
<img src="/docs/assets/web3/nfts-21.png" alt="image" width="450" />
</div>
An example of such a proxy server [can be found here](https://github.com/near-examples/near-api-rest-server).
#### Contracts
As we discovered in a previous section, for our application we need two smart contracts: for NFT and for Marketplace. There are two options on how to get them - use in-house implementation or some third-party/SAAS solution. Both options are viable and have different pros/cons.
If we want to create our own contract, we are fully in control and can implement anything we want. An obvious drawback, of course, is that it will take time and money to build it. Third-party solutions, on the other hand, are limited in their functionality and often cannot be easily extended. Also, they usually have some upfront costs and/or usage fees.
For an in-house NFT contract implementation a few resources can be used as a starting point. First of all, a [Rust library](https://docs.rs/near-contract-standards/latest/near_contract_standards/index.html) is available which implements most of the standard. Another option is to build an entire contract from scratch, a good guide on how to do this is available by [this link](../../3.tutorials/nfts/0-intro.md).
Implementing an own Marketplace contract is more involved since there is no standard implementation. A few examples:
* [Basic marketplace example](../../3.tutorials/nfts/8-marketplace.md)
* [Paras ](https://paras.id/)marketplace contract - [source](https://github.com/ParasHQ/paras-marketplace-contract/tree/master/paras-marketplace-contract/src).
As for third-party solutions, the most complete one is [Mintibase](https://www.mintbase.io/), which provides a full suite of components for NFTs integration - including contracts, indexer, API and a web client:
![image](/docs/assets/web3/nfts-22.png)
Another option is to roll-out an own NFT contract and integrate with one of the third-party marketplaces, e.g. with [Paras](https://paras.id/) ([integration docs](https://docs.paras.id/nft-smart-contract-integration)).
![image](/docs/assets/web3/nfts-23.png)
The major advantage of an external marketplace is the fact that they usually run their own indexer and expose collected data via an API, so we don’t have to implement these components. However, they usually have their fee for providing them, so a cost-benefit analysis should be conducted before using them.
#### Off-chain storages
Previously, we’ve discussed that storage on the blockchain is not cheap, so in most cases some decentralized storage solution should be used. A few options are available:
* [IPFS ](https://ipfs.io/)- one of the first decentralized storage solutions, which is widely used in the blockchain world. However, in order to make sure that data is preserved on the network, an IPFS node(s) should be maintained.
* [Arweawe](https://www.arweave.org/) - blockchain-based decentralized storage.
* [Filecoin](https://filecoin.io/) - another blockchain-based storage.
* [nft.storage](https://nft.storage/) - a free service built on top of the IPFS and Filecoin.
A more in-depth overview of such solutions is available [in the docs](../storage/decentralized-storage.md). In general, there's no “silver bullet”, so different solutions should be evaluated and the most suitable chosen. The main concerns while choosing a solution are availability guarantees, and cost.
#### Indexer
As we already determined, an indexing service is needed in order to support marketplace functionality. It usually consists of 3 components:
* Indexer - processes transactions from a NEAR network and puts extracted data into a database.
* Database - database of choice to store extracted data.
* Indexer API - an API layer on top of the database.
<div align="center">
<img src="/docs/assets/web3/nfts-24.png" alt="image" width="150" />
</div>
While any technology of choice can be used to implement Database and API, an indexer itself is usually implemented using Rust, since a [framework is available](https://github.com/near/nearcore/tree/master/chain/indexer) for this language. Guide how to implement your own indexer can be found [here](../../4.tools/indexer4explorer.md).
Usually, an indexer works by extracting data from [Events](https://nomicon.io/Standards/EventsFormat), which are basically just structured log messages written during contract execution.
[The Graph](https://thegraph.com/en/) is an alternative to building an indexer from scratch. This is an Indexer-as-a-Service solution, which simplifies their creation and deployment. Guide on how to create a NEAR indexer is available [by this link](https://thegraph.com/docs/en/supported-networks/near/).
#### Automated Testing
Automated testing of the code is one of the pillars of modern software development. But how do we test our dApp?
Recall that a smart contract is a pure function, which can be easily tested using Unit Tests. Guide on how to write them is available [here](../../2.build/2.smart-contracts/testing/unit-test.md), and some examples can be found here. Another important kind of tests that is supported by NEAR are E2E tests, they can be executed either deploying contract code to either the local network environment (more info [here](../../2.build/2.smart-contracts/testing/introduction.md)), or directly to `testnet`, more info [here](../../2.build/2.smart-contracts/testing/integration-test.md)).
Having both types of tests is equally important to ensure continuous quality of smart contracts, especially since contract upgrades usually aren’t easy to perform (remember, that in DAOs upgrade itself might be governed by a community vote).
## Non-Functional Concerns
Last, but not least, let’s cover important non-functional concerns for our architecture.
### Security
The most important thing to remember during the entire development is security, and especially the security of smart contracts. Since their code is public and an upgrade procedure is not trivial, it should be carefully audited for security issues and logical exploits.
Another important thing that should be kept secure is a user's private key. In most cases, only Functional Call keys should be directly accessed from a client, and Full Access keys should be kept in a wallet. However, in some cases a Full Access key might have to be used directly (e.g. in case of server transaction signing scenarios). In such a case, it must be kept in a secure location and treated as a most sensitive secret, since its compromise might lead to a full account takeover.
In general, before deploying an application to the NEAR mainnet, it’s a good idea to conduct a full security audit.
### Scalability and Availability
Another concern is scalability and availability of a solution. There are a lot of ways to scale traditional servers, but how do we scale our blockchain and make sure it’s always available?
Since blockchain is decentralized, it provides us with high-availability by design, and NEAR provides a great scalability by employing Proof-of-Stake consensus and sharding. However, in order to interact with a network, we need an RPC Node. NEAR maintains publicly available nodes for its networks (listed [here](https://rpc.mainnet.near.org/status)), but it doesn't provide any performance or availability guarantees for them. So, in order to make sure our architecture is scalable and fault tolerant, we need to maintain our own cluster of RPC nodes, typically behind a load balancer.
<div align="center">
<img src="/docs/assets/web3/nfts-25.png" alt="image" width="150" />
</div>
Information on how to set up an RPC node is available [here](https://near-nodes.io/rpc).
Also, to guarantee availability and scalability of a whole system, all used third-party services should be reviewed as well. For example, if IPFS is used as a storage for NFTs, pinning nodes and IPFS gateway should be scalable and fault tolerant.
### Costs
When building a Web 3 application, it’s important to remember that cost calculation is somewhat different from Web 2 applications. Additional costs can be broken down into several categories:
1. Smart Contracts deployment costs. While deploying on NEAR testnet or local environment, it’s essentially free of charge. However, when deploying into the mainnet, developers will be charged for storage and gas cost. Gas cost for a contract deployment transaction is relatively small (around 0.04$ at the time of writing). On the other hand, storage costs can be quite substantial, e.g. a 150KB contract (compiled) will cost around 20$.
2. Smart Contracts usage cost. In Web 3, users pay for smart contract calls, so in order to make sure users aren’t discouraged to interact with a contract due to a high cost, it should be optimized to incur the lowest cost possible. This is especially important for storage costs, since gas is relatively cheap.
3. If we want to use a privately hosted RPC node for better availability, its operational costs should be taken into account as well. Cost breakdown can be found [here](https://near-nodes.io/rpc/hardware-rpc), a rough estimation is about 290$ per node per month (and remember that we need at least 2 nodes for redundancy).
4. Cost of a privately hosted indexer (if it’s used). More information can be found [here](/concepts/advanced/near-indexer-framework), a rough estimation for the costs is about 100$ per month.
5. Third party services costs.
|
---
id: anatomy
title: Basic Anatomy
hide_table_of_contents: true
---
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import {CodeTabs, Language, Github} from "@site/src/components/codetabs"
import {ExplainCode, Block, File} from '@site/src/components/CodeExplainer/code-explainer';
Let's illustrate the basic anatomy of a simple "Hello World" contract. The code on this page comes from our [Hello NEAR repository](https://github.com/near-examples/hello-near-examples) on Github.
<ExplainCode languages={["js", "rust"]} >
<Block highlights={{"js": "1", "rust": "1"}} fname="hello-near">
### Importing the SDK
All contracts will import the **NEAR SDK**, enabling them to [access the execution environment](./environment.md), [call other contracts](./crosscontract.md), [transfer tokens](./actions.md), and much more
You can also use third-party libraries, thought some might not work due to the limitations of the contract runtime
</Block>
<Block highlights={{"js": "4-17", "rust":"5-7,20-31"}} fname="hello-near">
### Contract's Class / Structure
The contract is described through a `Class` / `Struct` :
- The attributes define which data the contract stores
- The functions define its public (and private) interface
</Block>
<Block highlights={{"js": "3"}} fname="hello-near">
### Contract Class Decorator
Note that the contract's class is decorated with `@NearBindgen`. This decorator tells the SDK which class defines the contract, so it knows:
1. What to fetch from storage when the contract is loaded
2. What to store when the contract is done executing
3. The methods that are exposed to the outside world
**Note:** Only one class can be decorated with the `@NearBindgen` decorator
</Block>
<Block highlights={{"rust": "4,19"}} fname="hello-near">
### Contract Struct Macro
Note that the contract's struct definition and the implementation are decorated with macros
The `#[near(contract_state)]` macro tell the SDK that this structure defines the contract's state, so it knows:
1. What to fetch from storage when the contract is loaded
2. What to store when the contract is done executing
The `#[near]` macro tells the SDK which functions are exposed to the outside world
**Note:** Only one struct can be decorated with the `#[near(contract_state)]` macro
</Block>
<Block highlights={{"js": "5", "rust": "6,10-16"}} fname="hello-near">
### Storage (State)
We call the data stored in the contract [the contract's state](./storage.md).
In our Hello World example, the contract stores a single string (`greeting`), and the state starts initialized with the default value `"Hello"`
**Note:** We will cover more about the contract's state in the [state section](./storage.md)
</Block>
<Block highlights={{"js": "8-10", "rust": "22-24"}} fname="hello-near">
### Read Only Functions
Contract's functions can be read-only, meaning they don't modify the state. Calling them is free for everyone, and does not require to have a NEAR account
**Note:** We will cover more about function types in the [functions section](./functions.md)
</Block>
<Block highlights={{"js": "13-16", "rust": "27-30"}} fname="hello-near">
### State Mutating Functions
Functions that modify the state or call other contracts are considered state mutating functions. It is necessary to have a NEAR account to call them, as they require a transaction to be sent to the network
**Note:** We will cover more about function types in the [functions section](./functions.md)
</Block>
<File
language="js"
fname="hello-near"
url="https://github.com/near-examples/hello-near-examples/blob/main/contract-ts/src/contract.ts"
start="2"
end="18"
/>
<File
language="rust"
fname="hello-near"
url="https://github.com/near-examples/hello-near-examples/blob/main/contract-rs/src/lib.rs"
start="2"
end="32"
/>
</ExplainCode> |
# Refunds
When execution of a receipt fails or there is some unused amount of prepaid gas left after a function call, the Runtime generates refund receipts.
The are 2 types of refunds:
- Refunds for the failed receipt for attached deposits. Let's call them **deposit refunds**.
- Refunds for the unused gas and fees. Let's call them **gas refunds**.
Refund receipts are identified by having `predecessor_id == "system"`. They are also special because they don't cost any gas to generate or execute. As a result, they also do not contribute to the block gas limit.
If the execution of a refund fails, the refund amount is burnt.
The refund receipt is an `ActionReceipt` that consists of a single action `Transfer` with the `deposit` amount of the refund.
## Deposit Refunds
Deposit refunds are generated when an action receipt fails to execute. All attached deposit amounts are summed together and
sent as a refund to a `predecessor_id` (because only the predecessor can attach deposits).
Deposit refunds have the following fields in the `ActionReceipt`:
- `signer_id` is `system`
- `signer_public_key` is ED25519 key with data equal to 32 bytes of `0`.
## Gas Refunds
Gas refunds are generated when a receipt used the amount of gas lower than the attached amount of gas.
If the receipt execution succeeded, the gas amount is equal to `prepaid_gas + execution_gas - used_gas`.
If the receipt execution failed, the gas amount is equal to `prepaid_gas + execution_gas - burnt_gas`.
The difference between `burnt_gas` and `used_gas` is the `used_gas` also includes the fees and the prepaid gas of
newly generated receipts, e.g. from cross-contract calls in function calls actions.
Then the gas amount is converted to tokens by multiplying by the gas price at which the original transaction was generated.
Gas refunds have the following fields in the `ActionReceipt`:
- `signer_id` is the actual `signer_id` from the receipt that generates this refund.
- `signer_public_key` is the `signer_public_key` from the receipt that generates this refund.
## Access Key Allowance refunds
When an account used a restricted access key with `FunctionCallPermission`, it may have had a limited allowance.
The allowance was charged for the full amount of receipt fees including full prepaid gas.
To refund the allowance we distinguish between Deposit refunds and Gas refunds using `signer_id` in the action receipt.
If the `signer_id == receiver_id && predecessor_id == "system"` it means it's a gas refund and the runtime should try to refund the allowance.
Note, that it's not always possible to refund the allowance, because the access key can be deleted between the moment when the transaction was
issued and when the gas refund arrived. In this case we use the best effort to refund the allowance. It means:
- the access key on the `signer_id` account with the public key `signer_public_key` should exist
- the access key permission should be `FunctionCallPermission`
- the allowance should be set to `Some` limited value, instead of unlimited allowance (`None`)
- the runtime uses saturating add to increase the allowance, to avoid overflows
|
Pyth Price Feeds Launch on NEAR Protocol Bringing Equity, Commodities, and Market Data On Chain
NEAR FOUNDATION
November 30, 2023
Pyth, the largest first-party provider of real-time market data for crypto, equities, FX, and commodities to more than 40 blockchains, has launched on NEAR protocol. Pyth, whose services are used by more than 80 market participants — including Jane Street, CBOE, Binance, OKX, and Bybit — brings high-fidelity, high frequency financial market data to the NEAR blockchain natively for the first time.
Previously, Pyth had deployed its feeds to Aurora, the EVM chain built on NEAR. But today Pyth data feeds are fully compatible with NEAR Protocol.
The announcement is a boon to the burgeoning DeFi ecosystem built on top of NEAR, which stands to benefit from data feeds that update every 300 milliseconds.
While other oracle providers use third-party data providers or relayers, Pyth’s data comes from institutions directly. Additionally, Pyth does not use price triggers to prevent certain prices from being pushed. Pyth uses Confidence Intervals to ensure continuous price availability. This new metric allows projects to consume Pyth’s price feeds during the most volatile market conditions.
The Importance of Oracles
Oracles are an important part of any DeFi ecosystem, since they are the information bridges between blockchains and databases. Although oracles could be built by the developers of DeFi projects, out-of-box, decentralized oracles are helpful for builders to start quickly without losing time and effort creating their own oracles.
“Celebrating a new era of data reliability and trust, Douro Labs is thrilled to announce the seamless integration of Pyth Network with the NEAR blockchain,” says Abhimanyu Bansal, Head of Partnerships at Douro Labs.
“This strategic partnership empowers developers on NEAR with real-time, accurate data feeds, and as we bridge the gap between the physical and digital worlds this integration propels us towards a future of decentralized applications that are not only secure but also truly informed.”
Pyth has a robust network that is able to deliver price data even during sizable events. During the LUNA/UST incident in May ‘22, Pyth managed to track the LUNA price very accurately during the UST de-peg, while other networks stopped updating the price, causing inaccurate price data.
In less than a year since Pyth’s launch, the network secured more than $2.0B in total value. Pyth has facilitated over $70 billion in trading volume and received over a million client downloads from passionate developers. Pyth supports 350+ low-latency price feeds across digital assets, equities, ETFs, forex pairs, and commodities.
|
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
# Standards
<DocCardList items={useCurrentSidebarCategory().items}/>
## Table of Contents
- [Fungible Token](Tokens/FungibleToken/README.md)
- [Core Standard](Tokens/FungibleToken/Core.md)
- [Metadata](Tokens/FungibleToken/Metadata.md)
- [Events](Tokens/FungibleToken/Event.md)
- [Non-Fungible Token](Tokens/NonFungibleToken/README.md)
- [Core Standard](Tokens/NonFungibleToken/Core.md)
- [Metadata](Tokens/NonFungibleToken/Metadata.md)
- [Approval Management](Tokens/NonFungibleToken/ApprovalManagement.md)
- [Enumeration](Tokens/NonFungibleToken/Enumeration.md)
- [Royalty Payout](Tokens/NonFungibleToken/Payout.md)
- [Events](Tokens/NonFungibleToken/Event.md)
- [Storage Management](StorageManagement.md)
- [Events Format](EventsFormat.md)
|
---
id: dex
title: Decentralized Exchanges (DEX)
hide_table_of_contents: false
---
import {FeatureList, Column, Feature} from "@site/src/components/featurelist"
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import BOSGetPrice from "./dex/bos/get-price.md"
import BOSSwap from "./dex/bos/swap.md"
import BOSGetPools from "./dex/bos/get-pools.md"
import BOSGetDepositBalances from "./dex/bos/get-deposit-balances.md"
import WebAppGetPrice from "./dex/web-app/get-price.md"
import WebAppSwap from "./dex/web-app/swap.md"
import WebAppGetPools from "./dex/web-app/get-pools.md"
import WebAppGetDepositBalances from "./dex/web-app/get-deposit-balances.md"
import CLISwap from "./dex/near-cli/swap.md"
import CLIGetPools from "./dex/near-cli/get-pools.md"
import CLIGetDepositBalances from "./dex/near-cli/get-deposit-balances.md"
import SmartContractSwap from "./dex/smart-contract/swap.md"
import SmartContractGetPools from "./dex/smart-contract/get-pools.md"
import SmartContractGetDepositBalances from "./dex/smart-contract/get-deposit-balances.md"
A Decentralized Exchange (DEX) is an application that allows users to trade tokens (native & fungible tokens) through smart contracts.
![dex](/docs/primitives/dex.png)
In brief, DEXs work by having [pools of token pairs](https://guide.ref.finance/products/overview/pooling) (e.g. NEAR-USDC) that users can deposit tokens into.
The ratio of the tokens in the pool determines the exchange rate for a swap. Indeed, swapping is adding tokens to one side of the pool while removing tokens from the other side of the pool.
:::info
This docs refer to [Ref Finance](https://www.ref.finance/), a community built DEX in NEAR.
Please check their [docs](https://guide.ref.finance/developers-1/cli-trading) for more information.
:::
---
## Query Token Exchange Rate
One can query the exchange rate of a token pair by calling the `get-token-price` method on the DEX contract.
<Tabs groupId="code-tabs">
<TabItem value="⚛️ Component" label="⚛️ Component" default>
<BOSGetPrice />
</TabItem>
<TabItem value="🌐 WebApp" label="🌐 WebApp">
<WebAppGetPrice />
</TabItem>
</Tabs>
---
## Query Whitelisted Tokens
Anyone list tokens for sale in the DEX. This is why, in order to protect users, the DEX contract has a list of whitelisted tokens that can be traded.
<Tabs groupId="code-tabs">
<TabItem value="🖥️ CLI" label="🖥️ CLI">
```bash
near view v2.ref-finance.near get_whitelisted_tokens
```
</TabItem>
</Tabs>
<details>
<summary> Examples Response </summary>
```bash
'wrap.near',
'usdt.tether-token.near',
'berryclub.ek.near',
'farm.berryclub.ek.near',
'token.v2.ref-finance.near',
'token.paras.near',
'marmaj.tkn.near',
'meta-pool.near',
...
```
</details>
---
## Register in the DEX
In order to use the contract, make sure to register your account in the DEX by paying for the storage you will use in order to keep track of your balances.
<Tabs groupId="code-tabs">
<TabItem value="🖥️ CLI" label="🖥️ CLI">
```bash
near call v2.ref-finance.near storage_deposit '' --accountId <account> --amount 0.1
```
</TabItem>
</Tabs>
---
## Deposit funds
In order to swap tokens, one must first deposit tokens into the DEX. For this, you will need to transfer the FT you want to swap to the DEX contract.
<Tabs groupId="code-tabs">
<TabItem value="🖥️ CLI" label="🖥️ CLI">
```bash
near call token.v2.ref-finance.near ft_transfer_call {"receiver_id": "v2.ref-finance.near", "amount": "1000000000000", "msg": ""} --gas 300000000000000 --depositYocto 1 --accountId <account>
```
</TabItem>
</Tabs>
:::danger
Do **NOT** transfer **NEAR** tokens to Ref Finance. Instead, call `near_deposit` in the [`wrap.near`](https://nearblocks.io/address/wrap.near) contract, attaching the amount of NEAR you want to swap.
This will mint `wrap.near` for you, which you can then transfer to Ref Finance.
:::
---
## Get Deposit Balances
Query your deposit balances by calling the `get_deposits` method:
<Tabs groupId="code-tabs">
<TabItem value="⚛️ Component" label="⚛️ Component" default>
<BOSGetDepositBalances />
</TabItem>
<TabItem value="🌐 WebApp" label="🌐 WebApp">
<WebAppGetDepositBalances />
</TabItem>
<TabItem value="🖥️ CLI" label="🖥️ CLI">
<CLIGetDepositBalances />
</TabItem>
<TabItem value="📄 Contract" label="📄 Contract">
<SmartContractGetDepositBalances />
</TabItem>
</Tabs>
---
### Query Pools
DEXs work by having multiple pools of token pairs (e.g. NEAR-USDC) that users can deposit tokens into.
<Tabs groupId="code-tabs">
<TabItem value="⚛️ Component" label="⚛️ Component" default>
<BOSGetPools />
</TabItem>
<TabItem value="🌐 WebApp" label="🌐 WebApp">
<WebAppGetPools />
</TabItem>
<TabItem value="🖥️ CLI" label="🖥️ CLI">
<CLIGetPools />
</TabItem>
<TabItem value="📄 Contract" label="📄 Contract">
<SmartContractGetPools />
</TabItem>
</Tabs>
---
## Swap tokens
In order to swap a token for another, you need to [have funds](#deposit-funds), and there needs to [**exist a pool**](#query-pools) that has **both tokens** on it.
<Tabs groupId="code-tabs">
<TabItem value="⚛️ Component" label="⚛️ Component" default>
<BOSSwap />
</TabItem>
<TabItem value="🌐 WebApp" label="🌐 WebApp">
<WebAppSwap />
</TabItem>
<TabItem value="🖥️ CLI" label="🖥️ CLI">
<CLISwap />
</TabItem>
<TabItem value="📄 Contract" label="📄 Contract">
<SmartContractSwap />
</TabItem>
</Tabs>
---
## Additional Resources
1. [Claim Fungible Tokens from Lockup](https://near.org/near/widget/ComponentDetailsPage?src=whtt.near/widget/Draft-0) - the example how to claim locked tokens from the `lockup.burrow.near` contract.
2. [BSC Dex Collection](https://near.org/near/widget/ComponentDetailsPage?src=bluebiu.near/widget/Bsc.Swap.Dex) - the example of how to build simple swap page for a DEX.
|
Summer of Shipping on NEAR Heats up with Horizon’s HZN3 Cohort
NEAR FOUNDATION
April 2, 2024
The NEAR Horizon Accelerator (HZN) is continuing to nurture early-stage open founders by launching its third cohort, HZN3. As part of NEAR’s Summer of Shipping, HZN3 will encourage accountability, community, and deploying products that amplify chain abstraction.
Established as an equity-free program, HZN3 is designed to deliver mentorship, technical support, and tactical education to empower founders in navigating the complexities and hurdles associated with building a thriving, successful project.
With a focus on crypto-native go-to-market strategies and refinding the tech stack, HZN3 will be a vital resource for founders aiming to scale their projects. It underscores NEAR’s commitment to fostering innovation and supporting the next wave of open web projects, contributing significantly to the ecosystem’s diversity and resilience.
HZN3 is a chain-agnostic program and welcomes builders from any ecosystem. This approach is part of fulfilling NEAR’s vision for a unified, user-friendly open web. Here’s everything you need to know about the HZN3 cohort and how to join.
Empowering Open Web Innovation with HZN3
The HZN3 Accelerator Program, NEAR’s third cohort under the Horizon banner, will be a structured, eight-week journey for open web founders, emphasizing sustainable growth. This equity-free approach aligns with NEAR’s dedication to founders success and autonomy.
Specifically geared towards early-stage Web3 founders, HZN3 is a launchpad for projects at any development stage, from idea to MVP. The program’s core objectives are to furnish participants with mentorship, one-on-one technical support, and education tailored to the nuances of launching and scaling in the crypto space.
While HZN3 does not provide direct funding, its focus is on providing invaluable resources and a network that far exceeds monetary support. The HZN3 Program runs from May 20th – July 12th, 2024, capped with a Demo Day live at ETH CC in Brussels, Belgium HZN3 will be an intensive, hands-on experience, crafted to sharpen go-to-market strategies and refine technical stacks, ensuring projects are not just visionary but viable and market-ready.
The application period, spanning from March 18th to May 10th, 2024, invites early-stage founders to step forward with their visions, irrespective of their blockchain foundation, fostering a diversity rich cohort. Selected participants can anticipate a kickoff meeting to outline the road ahead, ensuring founders are prepared for the intensive, growth-oriented journey in HZN3.
Building on Previous HZN Alumni Success
The HZN3 program will take its cue from the achievements of previous HZN alumni projects that have laid the groundwork for the upcoming cohort. The previous 50+ participants from HZN’s programs include Gravvity, Quest, Superchargd, Plato, Shard Dog, and Contented, illustrating HZN’s tangible impact.
These projects have navigated the initial stages of development and launch, successfully securing significant external capital and collectively raising over $20 million. These funding successes validate the value and trust investors place in HZN-supported initiatives and highlight HZN’s effectiveness in preparing founders for the pitching and funding process.
The accelerator’s focus on mentorship, technical support, and tactical education has also equipped these projects with the necessary tools for scalability and market penetration. Through HZN, founders gain financial backing and receive a comprehensive foundation for sustained growth, network expansion, and strategic positioning moving forward.
HZN’s commitment to fostering innovation and supporting early-stage projects contributes significantly to the diversity and resilience of the NEAR ecosystem, ensuring a vibrant future for open web innovation.
Apply to HZN3 and Join NEAR’s Vision for Chain Abstraction
HZN3 applications are open from March 18th to May 10th, 2024, welcoming visionaries eager to scale their projects. Interested founders can apply directly through HZN’s application page, where they’ll find detailed instructions and requirements. Founders building on any blockchain are encouraged to apply, as HZ3 is a chain-agnostic program.
HZN3 also plays a critical role in NEAR’s broader chain abstraction narrative by attracting diverse, high-quality projects across multiple blockchains. By supporting founders regardless of blockchain or ecosystem, HZN3 will contribute to the broader vision of chain abstraction. This approach is key for driving the adoption of the chain abstraction stack.
Through HZN3, NEAR reinforces its commitment to an open web that thrives on diversity, collaboration, and shared success.
Seizing Open Web Opportunities with HZN3
As an equity-free, accelerator program, HZN3 is a unique opportunity to bootstrap and jumpstart any project. Founders won’t want to miss out on key resources, network expansion, and strategic development insights they’ll receive during the course of the program.
Potential applicants should apply before May 10th, 2024, to secure a spot in the upcoming HZ3 cohort. For more details, visit HZN’s application page to join the community discussion, connect with peers and mentors, and brainstorm about how your project can be a part of the open web’s future. |
A Deep Dive into Private Transactions on NEAR
DEVELOPERS
April 22, 2020
Last week, we announced a collaboration with ZeroPool that will add support for private transactions to the NEAR Protocol. In NEAR today, all transactions are public—similar to Bitcoin and Ethereum. That means that—for every transaction—the sender, the receiver, and the amount transacted are all public. This is what allows everyone to audit the ledger and confirm that all the transactions are valid and no tokens are spent twice.
In many cases, it is desirable to transact in a way where only the participants involved in the transaction can have any insight into it. Achieving this while maintaining the ability to validate the correctness of the ledger is a complex task involving non-trivial cryptography.
In this blog post, I will dive deep into the internals of how private transactions will be implemented on NEAR so that no information about the participants or amounts are revealed—all without sacrificing the ability to validate the correctness.
UTXO tree
While NEAR generally uses the account model, private transactions use the unspect transaction output (UTXO) model instead. Each UTXO is a tuple (amount, receiver, salt) where amount is the amount of tokens transferred, receiver is the public key of the receiver of tokens, and salt is just some random number.
All the UTXOs are stored in a merkle tree of a predefined height. The height of the tree defines how many transactions the pool can process throughout its existence.
Each leaf of the tree is either an UTXO, or null, indicating a vacant spot that can in the future be occupied by a new UTXO. Once a spot is occupied, it never frees up. Initially, all the leaves are nulls.
The actual UTXO is never revealed to anyone but the receiver. Instead, the leaves of the merkle tree are hashes of the UTXOs—thus the need for the salt. Without the salt, if Alice knows Bob’s public key, she can brute-force different amounts and see if the hash of amount, Bob’s public key appears as the leaf of the tree, thus deanonymizing a transaction sent to Bob.
Transactions
Let’s say Alice wants to send some tokens privately to Bob. The tokens that belong to Alice are those in the UTXOs in which the receiver is equal to Alice’s public key. To make a private transfer, Alice creates a transaction of the following form:
The transaction has exactly two inputs and exactly two outputs (the exact number of input and output UTXOs doesn’t have to be two but does need to be the same for all the transactions). The inputs are some existing UTXOs that correspond to some leaves of the merkle tree, and the outputs are brand-new UTXOs that will be appended to the tree.
When Alice is sending the transaction, if she actually publishes the two input UTXOs that are being spent, she will link the transaction to the transactions that produced those UTXOs. The goal of the pool is to make sure that such links cannot be established and thus the input UTXOs cannot be published.
How can we implement the transactions in such a way that the validators can confirm that it spends some existing UTXOs without revealing the actual UTXOs being spent?
ZeroPool, like many other privacy-preserving transaction engines, uses zero-knowledge succinct non-interactive arguments of knowledge (zk-SNARKs) for this purpose.
Zero-knowledge arguments of knowledge for a particular computation allow producing cryptographic proofs of the following form:
Given public input 1, public input 2 …
I know such private input 1, private input 2 …
That [some claim]
The way such arguments of knowledge work is outside the scope of this writeup. For more on this topic, this blog post provides a great overview with a lot of details.
For the purposes of the private transactions, in the most naive way, the argument of knowledge can have the following form:
Given the merkle root, and two hashes OUT_HASH1 and OUT_HASH2,
I know four such UTXOs IN1, IN2, OUT1, OUT2, two merkle proofs P1 and P2 and a private key x,
That hashes of OUT1 and OUT2 are correspondingly OUT_HASH1 and OUT_HASH2, and the receiver in IN1 and IN2 is equal to the public key X that corresponds to x, and the merkle proofs P1 and P2 are valid proofs of inclusion of IN1 and IN2 in a tree with the given merkle root, and the sum of amounts in IN1 and IN2 is equal to the sum of amounts in OUT1 and OUT2.
The transaction then consists of merkle_root, out_hash1, out_hash2, argument of knowledge, and nothing in the transaction reveals the recipients of the output UTXOs nor links the output UTXOs to the particular input UTXOs. Moreover, even the amount transacted is not revealed in the transaction.
For example, in the figure above, say the first and third UTXOs in the merkle tree have Alice as the recipient and amounts of $100 and $17 correspondingly. Alice knows those two UTXOs but has no insight into any other UTXO in the tree. If she wants to send $42 to Bob, she creates a transaction that uses both of her UTXOs as inputs and creates two new outputs: one sending $42 to Bob and another sending the remaining $75 to herself. She reveals the UTXO that is intended for Bob to Bob. But the remaining UTXOs are not known to anyone but her. Moreover, even the hashes of the input UTXOs are not revealed to anyone.
The smart contract that maintains the pool, once it receives such a transaction, verifies the argument of knowledge. If it checks out, it appends the two new UTXOs to the tree:
Once Bob receives the UTXO from Alice, he waits until the hash of the UTXO appears in the tree. Once it does, Bob has the tokens.
The problem with this naive approach is that the same input UTXO can be spent twice. Since nobody but Alice knows the hashes of the input UTXOs, the pool cannot remove the spent UTXOs from the merkle tree because it doesn’t know what to remove to begin with.
If Alice creates two different zero-knowledge arguments that both spend the same two inputs, everybody will be able to verify that both transactions spend some UTXOs existing in the merkle tree but will have no insight into the fact that those UTXOs are the same in the two transactions.
To address this problem, we add a concept of a nullifier. In the simplest form for a particular UTXO the nullifier is a hash of the UTXO and the private key of the receiver of that UTXO. We then change the argument of knowledge for the transaction to the following:
Given the merkle root, and two hashes OUT_HASH1 and OUT_HASH2, and two more hashes NULLIFIER1 and NULLIFIER2
I know four such UTXOs IN1, IN2, OUT1, OUT2, two merkle proofs P1 and P2 and a private key x,
That hashes of OUT1 and OUT2 are correspondingly OUT_HASH1 and OUT_HASH2, and the receiver in IN1 and IN2 is equal to the public key X that corresponds to x, and the merkle proofs P1 and P2 are valid proofs of inclusion of IN1 and IN2 in a tree with the given merkle root, and the sum of amounts in IN1 and IN2 is equal to the sum of amounts in OUT1 and OUT2, and hash (IN1, x) is equal to NULLIFIER1 and hash (IN2, x) is equal to NULLIFIER2
Note that any transaction that spends a particular UTXO will have the same NULLIFIER computed because the NULLIFIER only depends on the hash of the UTXO and the private key that uniquely corresponds to the public key in the UTXO. And since the NULLIFIER in the argument of knowledge above is in the “Given” clause, which is public, if two transactions that spend the same UTXO are ever published, everybody will be able to observe that they have the same NULLIFIER and discard the later of the two transactions.
Also note that, for as long as the hash used to compute it is preimage resistant, the NULLIFIER reveals nothing about either the input UTXO or the private key of the receiver.
Depositing, Withdrawing
The transactions described above work great to move assets within the pool. But for the pool to be of any use, there must be a way to move assets from outside the pool into the pool and from the pool back outside of it.
To that extent, the private transaction format is extended to have an extra field called delta, such that the sum of the amounts in input UTXOs is equal to the sum of the amounts in the output UTXOs plus delta:
Given the merkle root, and two hashes OUT_HASH1 and OUT_HASH2, two more hashes NULLIFIER1 and NULLIFIER2 and a value delta
I know four such UTXOs IN1, IN2, OUT1, OUT2, two merkle proofs P1 and P2 and a private key x,
That hashes of OUT1 and OUT2 are correspondingly OUT_HASH1 and OUT_HASH2, and the receiver in IN1 and IN2 is equal to the public key X that corresponds to x, and the merkle proofs P1 and P2 are valid proofs of inclusion of IN1 and IN2 in a tree with the given merkle root, and the sum of amounts in IN1 and IN2 is equal to the sum of amounts in OUT1 and OUT2 plus delta, and hash (IN1, x) is equal to NULLIFIER1 and hash (IN2, x) is equal to NULLIFIER2
Note that the delta is in the given clause and is thus public.
When such a transaction is processed on NEAR, if the delta is negative (i.e., so that more tokens enter the private transaction than exit it), the extra tokens are deposited to the sender’s account. If the delta is positive (i.e., more tokens exit the transaction than enter it), such a transaction is only valid if the remaining tokens are attached to it.
Transaction fees
Private transactions do not allow linking between the newly created UTXOs and the UTXOs that were used as inputs. However, for any transaction to be included on the NEAR chain, the transaction sender must pay for gas and thus must have native NEAR tokens in the sending account. Those tokens somehow got to that account, which creates linkability and largely defeats the purpose of the private transactions.
To address the problem, we introduce a new role in the system called relayer.
Say Alice wants to send a transaction to Bob and wants to use Ryan as the relayer. The gas fee for the transaction is less than Ⓝ1 and Alice is willing to pay Ryan Ⓝ1 for submitting the transaction to the chain.
Alice, who might not have an account on NEAR at all, creates a private transaction in which the sum of the two input UTXO amounts is Ⓝ1 less than the sum of the output UTXO amounts. The remaining Ⓝ1 is withdrawn to the account of the submitter of the transaction. Ryan collects the transaction from Alice, confirms the validity of the transaction, and submits it from his account, spending less than Ⓝ1 in gas but receiving Ⓝ1 as the result of the transaction.
Alice ends up submitting the transaction without revealing herself and Ryan receives a small payout. Note that no party needs to trust the other in this interaction: Ryan cannot tamper with the transaction in any way and thus can only either submit it or do nothing. So, the biggest risk for Alice is the possibility that her transaction is not submitted (in which case she can ask another relayer to submit it). Ryan verifies the transaction before submitting it and thus doesn’t risk spending gas and not receiving his payment unless another relayer front ran them.
Further improvements
The model described so far is a fully functional pool for private transactions. In this section, I will briefly mention several other aspects that improve the security or usability of the pool:
Discovering payments
When describing the transactions above, I mentioned that when Alice sends tokens privately to Bob, she shares the newly created UTXO with him. This requires Alice communicating with Bob off-chain, which is undesirable. Instead, the pool can be extended to store all the UTXOs encrypted with the public keys of their recipients. When Alice sends money to Bob and creates two new UTXOs, she encrypts the UTXO that has Bob as the recipient with Bob’s public key.
On his end, Bob monitors all the newly created UTXOs and tries to decrypt each one with his private key. Once he gets to the UTXO created by Alice, the decryption succeeds, and Bob discovers their UTXO using exclusively on-chain communication.
Decoupling signing and proving
When Alice creates a transaction, she needs to create a complex proof that in particular uses the knowledge of her private key. Thus, the machine that computes the proof needs access to the private key, which is undesirable.
Generally, it is preferable to have the private keys on some external hardware device that only has limited functionality, such as signing messages. Computing arguments of knowledge is generally way outside the capabilities of such hardware devices.
To accommodate these devices, we make the key generation create three keys instead of two:
Private Key, Decryption Key, Public Key
Here, a message encrypted with the Public Key can be decrypted with the Decryption Key. Similarly, a signature created with the Private Key can be verified having access to the Decryption Key. Only the public key is revealed publicly. The decryption key is stored on the device that computes transaction proofs and the private key is stored on the external device that can only sign messages.
We can then alter the argument of knowledge in the following way:
Given the merkle root, and two hashes OUT_HASH1 and OUT_HASH2, and two more hashes NULLIFIER1 and NULLIFIER2
I know four such UTXOs IN1, IN2, OUT1, OUT2, two merkle proofs P1 and P2, a decryption key d and a signature s,
That hashes of OUT1 and OUT2 are correspondingly OUT_HASH1 and OUT_HASH2, and the receiver in IN1 and IN2 is equal to the public key X that corresponds to d, and the merkle proofs P1 and P2 are valid proofs of inclusion of IN1 and IN2 in a tree with the given merkle root, and the sum of amounts in IN1 and IN2 is equal to the sum of amounts in OUT1 and OUT2, and hash (IN1, d) is equal to NULLIFIER1 and hash (IN2, d) is equal to NULLIFIER2, and s is a signature on a message (IN1, IN2, OUT1, OUT2) that is valid against d
When Alice then wants to create a transaction, she uses the hardware device to sign (IN1, IN2, OUT1, OUT2). She then uses the signature s to generate the proof on the machine that only has access to the decryption key.
Note that without access to the hardware device one cannot generate s and thus cannot spend money—even if they get access to the machine that is used for proving.
Supporting more tokens
The private transactions are not limited to the native NEAR tokens. With a very slight modification, the pool can be generalized to support any tokens using the same anonymity pool for all of them. The exact construction is outside the scope of this write-up, however.
Outro
Besides collaborating with NEAR, ZeroPool also builds private transactions for Ethereum and is primarily funded by the community. Consider supporting them on Gitcoin.
Educational Materials
This write-up is part of an ongoing effort to create high-quality educational materials about blockchain protocols. Check out this video series in which we dive deep into the design of various protocols—such as Ethereum, Cosmos, Polkadot, and others—as well as our other technical write-ups.
Supporting Early Stage Blockchain Companies
If you are an entrepreneur in the web3 space, consider joining our accelerator with mentors from tier1 companies and investment firms in the space:http://openwebcollective.com/. We help with all the aspects of building the business, including identifying the market, business development, marketing, and fundraising.
Stay in Touch
We are NEAR, an open source sharded blockchain protocol. You can deploy your first fully functional decentralized application to NEAR within minutes from our fully functional web-based IDE.
Follow us on Twitter to get updates about our new educational materials, while keeping tabs on our progress toward the decentralized future. |
---
title: Recruitment Resources
sidebar_label: Recruitment Resources
sidebar_position: 1
---
---
With NEAR being among the most interoperable and developer friendly Layer 1’s, developers of any technical background should find building on NEAR proves to be a great experience.
:::info on this page
* Career Portals
* Community Hubs
:::
## Discover Talent & Post Open Roles
### [NEAR Careers Portal](https://careers.near.org/jobs)<svg width="13.5" height="13.5" aria-hidden="true" viewBox="0 0 24 24" class="link__logo iconExternalLink_node_modules-@docusaurus-theme-classic-lib-next-theme-IconExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>
Discover open roles available within the NEAR Ecosystem, and you can also post open roles within your team as well.
---
## Recruitment Support
### [![Black Freelancer](@site/static/img/logo_blackfreelancer.svg)](https://www.blackfreelancer.com/)<svg width="13.5" height="13.5" aria-hidden="true" viewBox="0 0 24 24" class="link__logo iconExternalLink_node_modules-@docusaurus-theme-classic-lib-next-theme-IconExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>
BlackFreelancer is a hub for black creatives across the globe to showcase their work and get hired.
### [![BEExperience](@site/static/img/logo_beexperience.svg)](https://beexperience.io/)<svg width="13.5" height="13.5" aria-hidden="true" viewBox="0 0 24 24" class="link__logo iconExternalLink_node_modules-@docusaurus-theme-classic-lib-next-theme-IconExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>
The HUB of education and recruitment within Web3. Beexperience provides services to hiring entities, as well as individuals seeking employment.
* Help with connecting candidates to open vacancies.
* HR and Technical screening interviews to garantuee talent.
* Educational frameworks to help with onboarding and upskilling
* Providing facilities for instructor lead workshops both virtually and in person
* Web3 LinkedIn framework
<!-- ### [![NEAR Week](@site/static/img/logo_nearweek.svg)](https://nearweek.com/)<svg width="13.5" height="13.5" aria-hidden="true" viewBox="0 0 24 24" class="link__logo iconExternalLink_node_modules-@docusaurus-theme-classic-lib-next-theme-IconExternalLink-styles-module"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg>
Community-driven newsletter. It covers anything and everything within the NEAR Ecosystem. If you're looking for an extra dose of NEAR-focused news, look no further. -->
|
NEAR Horizon and Encode Club: Accelerating Blockchain Mastery for Builders
NEAR FOUNDATION
May 9, 2023
NEAR Horizon and Encode Club have joined forces with a singular mission: to simplify the entry into the Web3 sphere. This partnership forms a structured pathway, offering builders and founders a seamless transition into the blockchain world. Anchoring their efforts on practical solutions, NEAR Horizon and Encode Club aim to foster an inclusive and accessible future in the ever-evolving decentralized landscape.
Uniting Encode’s developer training expertise with NEAR’s advanced tech, the partnership goes beyond facilitation. It directly trains builders, fueling growth and actively shaping an open Web3.
Encode x NEAR Horizon: Four steps to blockchain expertise
This inclusive program is meticulously designed to accommodate everyone from those new to blockchain to well-versed industry professionals, promoting skill development and exploration in Web3.
Here’s what to expect:
Encode x NEAR Horizon Educational Series: The journey commences with a four-week program of building awareness of Web3 and NEAR Technology. These sessions aim to demystify blockchain technology, making it approachable for newcomers while offering valuable insights for seasoned professionals. From introductory presentations to in-depth technical demos, the educational series lays a solid foundation for all participants.
Encode x NEAR Horizon Bootcamp: An intense eight-week program offers a deep dive into the world of blockchain development. Participants engage in live classes, practical assignments, and collaborative group projects — all under the expert guidance of seasoned instructors. The bootcamp offers a hands-on learning experience, accelerating the participants’ transition from theory to practice.
Encode x NEAR Horizon Hackathon: A four-week hackathon that supports builders in launching high-quality projects. This event is designed to challenge participants and allow them to apply their newfound skills. With technical workshops, mentorship, and continual support, the hackathon provides an excellent platform for budding developers to build, learn, and innovate.
Encode x NEAR Horizon Accelerator Program: This eight-week program focuses on nurturing the most promising hackathon projects and ecosystem builders. By offering mentorship and weekly workshops, the accelerator program aims to transform innovative ideas into operational startups, contributing to the growth and diversity of the NEAR ecosystem.
In essence, this partnership between NEAR Foundation and Encode Club is more than just an event — it’s a comprehensive roadmap to blockchain mastery, designed to educate, engage, challenge, and inspire all who embark on the journey.
Cultivating talent: Encode x NEAR Horizon growth strategy
The program offers a well-structured process for developers to learn, practice and build startups while receiving mentorship support from Encode and NEAR Horizon. The program’s impact extends beyond individual growth, as it also fosters a thriving environment for the NEAR ecosystem and Web3 developers.
Don’t miss the chance to be part of this enriching experience — an opportunity that promises to strengthen the NEAR ecosystem while nurturing the next generation of Web3 developers. Embark on a rewarding blockchain journey with the NEAR Horizon and Encode Club partnership. Whether it’s the educational series, hackathon, bootcamp, or accelerator program, NEAR Horizon and Encode provide the resources and opportunities you need to succeed in the world of blockchain. Your blockchain adventure starts here.
To start, create a NEAR Horizon project profile and register to the Encode x NEAR Horizon program here. Stay updated on Encode Club’s programs via their website, Twitter, and Discord, and join a community that shares your passion for Web3 innovation and growth. NEAR Horizon was recently launched, read the press release here, and register in the NEAR Horizon platform here. |
Announcing the Launch of Pagoda, the World’s First Web3 Startup Platform
DEVELOPERS
February 19, 2022
At ETHDenver 2022, a top blockchain conference and hackathon, we proudly announced the launch of Pagoda: the world’s first Web3 startup platform. The Pagoda vision is to empower developers with a fully Web3-native toolset for building, maintaining, and scaling blockchain-based startups.
Open Source, Integrated: Open Services for Developer-Entrepreneurs
In the first seven years of smart contract blockchains, building out across the Web3 tech stack has made it easier to build blockchain-based products and services. But even as the time from idea to working prototype has shortened with improved tooling, it’s still painful for engineers to monitor and maintain those prototypes and mature them into efficient, growth-ready businesses.
Enter Pagoda, the first integrated Web3 startup platform and end-to-end solution for developer-entrepreneurs.
The blockchain ecosystem still largely relies on many Web2 tools – especially the tools required to monitor an app’s performance and to track adoption and growth. These aren’t designed to work with Web3 products and come with all the platform risks that Web3 seeks to avoid. Every service we use now in Web2 needs to be rebuilt to integrate with Web3, to support the principles of users owning their own data and blockchain-based accounts.
Pagoda’s objective is to offer Web3 native, fully decentralized versions of these tools at every layer of the stack, from the base blockchain protocol all the way up to the application and marketing/distribution layers. The NEAR ecosystem consists of many open source projects that can be integrated as “open services”: a familiar, cohesive development experience on top of a decentralized toolset. By providing interactive tutorials, scalable infrastructure, and operational analytics that are truly Web3 native, Pagoda better integrates them into one simple interface.
Growing the NEAR Ecosystem: the Best Choice for Founders
Beginning in 2018, NEAR Inc’s original mandate was to build the NEAR Protocol and launch MainNet, which we did in October 2020. From there, we focused on maintaining and evolving the protocol – notably with the launch of sharding, which started in late 2021 – and improving the developer experience.
Now we are a team of 70+ members across 20 countries. Pagoda will continue to contribute to the development of the NEAR ecosystem, as Near Inc did, by building and maintaining the protocol, SDKs, and APIs, while building out more tools and services at every layer of the stack.
The core Pagoda product is the Developer Console.
Integrating the Web3 Stack: Pagoda Developer Console
The Pagoda Developer Console integrates open source, Web3-native tools across the entire stack, making it easier than ever for developer-entrepreneurs to build, maintain, and scale blockchain-based businesses.
The transition from developer to entrepreneur happens faster in Web3, and it’s getting easier all the time to launch a product. Actually scaling that product requires not just developer tools, but a whole range of tools to support and grow post-launch – all of these are integrated in the Developer Console. This includes a DAO to manage upgrades to applications, deep on-chain analytics, and even triggers and alarms in case of unexpected events. Connecting to users directly becomes even more important as a Web3 product grows, so founders also need easy ways to launch ownership tokens, NFTs for marketing, and notifications for simple communication with users. All of these tools need to be Web3-native from the ground up and seamlessly integrated in a single experience: this is the vision for founders on Pagoda.
As the NEAR Ecosystem expands and more tools are created, Pagoda will continuously integrate them into the product stack. It’s still early days for the Developer Console, but we encourage all developer-entrepreneurs to try it out and explore the future of Web3 startups.
Try the Pagoda Developer Console Today
To start exploring the Developer Console and sign up for news and updates from Pagoda, visit pagoda.co and follow on Twitter at @PagodaPlatform. |
```js
import { Wallet } from './near-wallet';
const DAO_CONTRACT_ADDRESS = "primitives.sputnik-dao.near";
const wallet = new Wallet({ createAccessKeyFor: DAO_CONTRACT_ADDRESS });
await wallet.callMethod({
method: 'act_proposal',
args: { id: 0, action: "VoteApprove" },
contractId: DAO_CONTRACT_ADDRESS,
gas: 300000000000000,
});
```
:::note
Available vote options: `VoteApprove`, `VoteReject`, `VoteRemove`.
:::
_The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_ |