text
stringlengths
46
74.6k
NEAR Launches Nightshade Sharding, Paving the Way for Mass Adoption DEVELOPERS November 15, 2021 Today is a momentous day for the NEAR blockchain and the NEAR ecosystem: The launch of Simple Nightshade, the first step toward a fully sharded and secure blockchain. Since NEAR released the design for the protocol back in 2019, it was always meant to be a sharded blockchain. However, when preparing for the launch in early 2020, we realized that there was no need to launch a completely sharded network. Sharding is a very complex piece of technology – which we’ll be explaining in detail over the coming weeks on our Medium blog – and the network was brand new. It didn’t need to be capable of handling hundreds of millions of transactions at launch. Since then, the average number of daily transactions has risen to more than 300k. With the emergence of more and more projects building on NEAR, the number of transactions is only going to increase in the coming months. While the network is still currently using only 13% of the total capacity, we wanted to start the transition to sharding now to avoid any unpleasant surprises and ensure we can support all the applications on NEAR. Today is the start of that transition. Below, we’ll briefly discuss how sharding — a partitioning of the NEAR protocol — splits the work of processing transactions across many participating nodes. We’ll also offer some details on why this matters for NEAR’s booming community of developers and users. Simple Nightshade Today, the code for phase 0 was successfully deployed to the mainnet – it can take several hours or days for the code to be integrated by all network participants. This phase, nicknamed Simple Nightshade, will kickstart a year of changes and additions to the NEAR blockchain that when complete, will make it super-fast, incredibly secure, and capable of onboarding millions of users into the world of Web3 without skipping a beat. In this initial phase, we will shard the state, but not processing – meaning the blockchain will still be validated by all the network’s validators. The state will be split into four shards, significantly increasing the throughput of the network. Before sharding, blockchains would become congested as the project became more popular. In this step, we have built a mechanism to split a shard into multiple parts through live upgrades, which will serve as the foundation for dynamic resharding in the future – more on that later. Meanwhile, because every shard is still validated by all validators, the safety guarantees remain the same. What does this mean for users? It means they get the same simple, easy-to-use experience, but with increased speed and performance. One of blockchain’s biggest challenges has been scalability: how does a network grow to handle increased activity without compromising on security? Our solution to that question is Nightshade Sharding. While there are many new blockchains claiming to have thousands of transactions per second (TPS) and many layer 2 scaling solutions, due to their non-sharded designs, they would all hit an upper limit of what the network could handle eventually. NEAR’s Nightshade Sharding, on the other hand, allows NEAR Protocol to scale linearly with the number of shards, thereby having the ability to satisfy the demand for transactions as more and more users start to use NEAR. Ultimately it prepares NEAR for mass consumer adoption of billions of users. What does this mean for developers? Similar to users, developers will not have to change existing processes in order to take advantage of the increase in speed and scalability. Thanks to Nightshade’s homogeneous design, developers are not exposed to the details of sharding from the very beginning and they will remain unaffected by this upgrade. More specifically, internally we treat cross-contract calls the same regardless of whether two contracts are on the same shard. Therefore, developers should expect no changes to their experience of developing on NEAR. What does Nightshade Sharding change about the network’s performance? While transactions per second are often used as a measure of a network’s speed, there are many other factors that go into how quickly a blockchain can verify a transaction. At NEAR, network congestion, transaction finality and cost are all parts of the puzzle when it comes to assessing how ‘quick’ a network is. For reference, for token transfers, on one shard we can do 800-1000 TPS and with the upcoming sharding with four shards, we will be able to do a minimum of 2500-3000 TPS. Ultimately, NEAR’s Nightshade is theoretically limitless (by increasing the number of shards) and can handle millions of transactions per second. What comes after Phase 0? Late in 2022, Phase 1 will begin. In this phase, we introduce a new role: chunk-only producers, who only validate one shard. They produce chunks (shard blocks) for some specific shard and only need to run inexpensive hardware, without sacrificing the security of the network. The introduction of chunk-only producers also helps increase the total number of validators and improve the decentralization of NEAR as a whole. Once this phase is complete, we will have 200-400 validators and only a fraction of them (block producers) need to run more expensive hardware. Phase 2: Nightshade In this phase, we finish the implementation of challenges, thereby eliminating the need for any validators to track all the shards. Once this step is completed, both state and processing will be fully sharded. This will also further lower the hardware requirements of running a block producer on NEAR, making the network more accessible for validators. We expect to deliver phase 2 in 2023. Phase 3: Dynamic Resharding After phase 2 is complete, we will have a fully functional sharded mainnet with a fixed number of shards. In phase 3, we want to expand on that and create the ability for the network to dynamically split and merge shards based on resource utilization. This will make NEAR almost infinitely scalable and resilient to short-term usage spikes. We expect to deliver phase 3 in 2023. Eventually, the network itself will dynamically adjust the number of shards based on their utilization and no validators will need to validate all the shards. Sharding is not the final phase of evolution for NEAR Protocol. Rather, we hope it’s just the beginning. We are simultaneously working on a number of improvements on the protocol level to build a secure, user-friendly, and scalable blockchain that can support mainstream usage and adoption. After sharding more and more validators could be recruited to ensure the network remains congestion free. An ecosystem primed for growth In addition to the work on the protocol by NEAR Inc, NEAR Foundation is creating an ecosystem for developers, entrepreneurs, and enterprises to thrive with ambitious funding programs including $800 million worth of global ecosystem funding (now valued at $1.2 billion). We’re also seeing a thriving gaming, metaverse, and NFT ecosystem emerging, not to mention a DeFi ecosystem that has gone from strength to strength since mainnet launch one year ago. For consumers, we’re making strides forward to make the crypto experience even easier to use. From simple, language-based wallet names, to two-factor authentication, and staking baked right into the wallet. This is just the beginning of a period of explosive growth at every level. We can’t wait to show you what’s coming next. Get Started Today If you’re looking to build on NEAR, check out our developer resources. If you’re an entrepreneur and want to get started, head for our Founders space. If you’re looking to create DAOs and Guilds, check out our Community Page.
NEAR in March: Unchain Fund, SailGP, and DAOs NEAR FOUNDATION April 1, 2022 The NEAR community’s extraordinary momentum continued into March, with a number of exciting launches, partnerships, hackathons, and more happening across the ecosystem. While the events unfolding in Ukraine had a profound effect on many of the teams in the NEAR ecosystem, projects continued to deliver on their roadmaps as a testament to the community’s resiliency and borderless collaboration. For a first hand account of what this experience was like, check out Maria Yarotska’s Medium post on her experience working on MetaBUILD II while fleeing the conflict. Let’s have a look at what happened throughout the NEAR ecosystem in March. NEAR and SailGP Partner on new DAO for sports teams NEAR announced a multi-year partnership with SailGP, one of the world’s fastest growing sporting events, to explore the sale of a new team to a DAO (Decentralized Autonomous Organization) to be built on NEAR. The SailGP DAO will combine professional sports with community-focused engagement, bringing together sports fans and crypto users alike. This new DAO team could join the SailGP starting line-up for Season 4 in 2023. SailGP and NEAR will partner on a number of exciting new projects to inspire Web3 developers building on the blockchain, as well as collaborate on NFT and gaming, events ticketing, mobile app integration, and more. “We welcome NEAR to the SailGP family and we are looking forward to them participating in the most exciting racing on-water, featuring the world’s best sailors,” SailGP Founder Larry Ellison said. Orange DAO selects NEAR as web3 startup partner Shortly after partnering with Sail GP, NEAR Foundation announced another exciting project—this one with Orange DAO, a crypto collective created by Y Combinator alums that backs web3 startups. Orange DAO selected NEAR as its preferred layer 1 blockchain for web3. In return, 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.” Orange DAO will leverage NEAR’s strengths to back past, present, and aspiring Y Combinator founders. The DAO will do this by helping founders apply to and get accepted into YC; funding pre-and post-YC projects; as well as mentoring founders and helping with recruitment and customer acquisition where possible. NEAR Foundation’s funding of Orange DAO will vest over four years, and the Foundation will also support YC founders with time and resources. Unchain Fund launches DAO to collect donations for Ukraine On February 25, Unchain Fund, a new DAO fund, launched on the NEAR ecosystem to help collect crypto donations for citizens caught up in the conflict in Ukraine. Created on AstroDAO, a DAO-launching platform built on NEAR, Unchain Fund raises funds for humanitarian purposes in Ukraine, including evacuation, shelter, food, and more. In under a month, Unchain collected over $7 million USD and counting across a range of cryptocurrencies including, BSC, ETH, Harmony, NEAR, and Polygon. Over 700 volunteers are currently helping out with Unchain Fund in one way or another, and the effort continues to grow. “Crypto became the largest driver for humanitarian help as well as some of [the] military help for Ukraine,” said Illia Polosukhin, co-founder of NEAR. “You can create a full system, an NGO system in days. Instead of [the] months it would take to create a new nonprofit, set up bank accounts, get all the legal structure, make sure that people can wire money to it without problems.” MetaBUILD 2 hackathon winners Over the last three months, NEAR developers and entrepreneurs from around the globe have been building projects for the MetaBUILD 2 hackathon. This virtual-physical event was a great opportunity to witness the NEAR Community’s creativity and innovation. By building on NEAR’s simple, scalable, and secure blockchain, the MetaBUILD 2 hackathon projects are helping lay the foundation for a better future. A future in which millions of new users and developers create and share completely new journeys. Like the first hackathon, MetaBUILD 2 offered a total of $1 million in prizes. Nearly 4,000 participants joined, submitting over 356 projects—of which, 186 were eligible—for NFTs, DeFI, Gaming, DAOs, infrastructure apps and tools, and EVM apps. For the NEAR MetaBUILD 2 hackathon, there were Welcome and Natives tracks, as well as 35 Sponsor Challenges. Check out the list of winning MetaBUILD 2 projects. NearPay debit card bridges crypto and fiat Earlier this month, NearPay, the NEAR ecosystem’s first debit card and payments widget, announced its waitlist. NearPay had hoped to attract 1,000 users but the wait list grew to 18,000 in less than a week. Built by Switzerland-based Kikimora Labs, NearPay bridges fiat and crypto in a single seamless user experience. Slated for a late 2022 release, NearPay debit will be both a physical card and mobile-based app, with feature sets designed for consumers, developers, and merchants, allowing individuals, businesses, and other organizations to make instant transactions and payments using their preferred cryptocurrency, including NEAR. “The cards will be NEAR-oriented but support other cryptocurrencies as well,” says Ivan Ilin, Chief Operating Officer at NearPay. “For businesses, we support two scenarios: fiat-to-crypto to a user’s wallet and fiat-to-crypto to a merchant’s wallet for a certain order. We work with NFT marketplaces, DeFi projects, and many others.” “For developers, we provide a simple API with an SDK,” he adds. “The integration is possible with a website or a mobile application. We provide a merchant dashboard where one can see all the transaction statistics.” A Deep Dive into DAOs If 2021 was the year of the NFT, then 2022 is the year of the DAO. As Web3’s popularity continues to grow amongst end-users and developers, so has the interest in and launches of DAOs. And it’s easy to see why: these decentralized autonomous organizations empower communities instead of centralizing data, power, and money in the hands of big Silicon Valley firms. To capture the explosive growth of DAOs on the NEAR ecosystem, the NEAR Foundation published a 5-part series on these unique Web3 creations, including a DAO primer, a spotlight on NEAR’s DAO launchpad Astro, life-changing DAOs, and more. Capsule.Social’s Blogchain launches writer program for Ukrainian migrants Capsule.Social’s Blogchain, a decentralized publishing platform for writers, launched this month and quickly followed this up with a new writer program designed for Ukrainian migrants. Through this program, a number of Ukrainian writers have been sharing their personal stories, experienced during Russia’s war on Ukraine. Blogchain gives these Ukrainians and many other writers a user-friendly interface, created with powerful decentralized functionality, that also includes censorship-resistant content hosting, payment to creators in either crypto or fiat money, and community governance. Follow the Capsule.Social Twitter for stories from Ukrainians and other writers publishing on the decentralized Blogchain platform. ICYMI: NEAR’s Road to Decentralization In early March, NEAR Foundation published a 4-part series “Road to Decentralization”, in which it explore the various ways in which the network is being decentralized to the community. Since launch, NEAR Foundation has been committed to decentralizing the network as part of the larger effort to build a fast, secure, and scalable blockchain. For the full details on this process, read “Road to Decentralization” parts: 1: Decentralization Road Map 2: A Deep Dive into Aurora 3: Empowering the Guild Community 4: Building Bridges
NEAR Developer Research: Validating the NEAR DevX Tech Stack – Round 2 DEVELOPERS October 29, 2020 Update: We’ve quickly filled up the available sessions for this round of research, and will not be taking on any more participants. The post will remain on the blog for those interested in getting a peek at what we’re up to. For those interested in participating, check back for round 3! After a successful first round of research diving into the developer experiences of AssemblyScript and Rust earlier this month, we’re back in action with ROUND 2. This is a compensated opportunity to contribute to the future success of NEAR and help shape the future of developer experience for the community. Validating the NEAR DevX Tech Stack The next big decision we welcome the community to participate in is how we will support AssemblyScript in addition to Rust as a WASM source. We want to test our assumptions about the value propositions of these languages with community developers in order to make an informed, evidence based decision on what we choose to support, and to what extent. Round 1 of this initiative focused on reading and discussing a set of pre-written contracts. For Round 2, we want to walk through setting up and deploying a simple contract with our developer participants in order to compare and contrast the experience between languages. If selected, participants who complete a session with us will be compensated with $50 of value in the form of a gift card or tokens depending on location. If interested in participating, fill out this invite form to connect with our team. You do not have to have participated in Round 1 to participate in Round 2. What you’ll do It’s easy to join and we’re open to feedback from community members from around the world. After a quick survey and remote interview we’ll ask you to complete a few simple dev tasks and provide your feedback to the team. Pre-interview Survey New participants will be asked to complete a short pre-interview survey about their development experience to help us categorize feedback. Remote Interview (15 min) At the start of the session, new participants will be interviewed about their development experience and their opinions about the tools that we’re testing. Remote Technical Exercises (35 – 60min) Each participant will be asked to complete a series of short tasks focused on customizing a smart contract on NEAR, and to share their thoughts along the way. Participants will be asked to: Use create-near-app to generate new projects in Rust and AssemblyScript Edit contract code to pass a set of pre-written unit tests Build and deploy the contract to the NEAR Testnet Verify that the contract works as expected and troubleshoot any issues You’re a great fit if you fall into any of the following categories: … you’re a developer with experience in Javascript / Typescript … you’re a developer with experience in AssemblyScript … you’re a developer with experience in Rust … you’re a developer with experience in Solidity … you’re interested in getting some hands-on time with some of the basic NEAR developer tooling.
NEAR Wallet’s Evolution in 2023 NEAR FOUNDATION January 11, 2023 NEAR Foundation and Pagoda, along with the Wallets Working Group, have conducted extensive community discussions over the last several months about the evolution of wallets in the NEAR ecosystem. In keeping with the Foundation’s goal to empower the community and continue to decentralize the ecosystem over time, the focus since NEARCON has been to expand the wallet offerings to NEAR users and to decentralize the NEAR Wallet. MyNearWallet is now open source and under the stewardship of Developer DAO to maintain as a public good. (Pagoda took over MNW after Kikimora ceased operations in December due to funding issues.) DevDAO announced this week that they are accepting applications for teams to take over maintenance of MyNearWallet to evolve the product while keeping it open source for the benefit of the developer community. For more information about how to apply, visit the Developer DAO gigs board on NEAR Social. If you have been using MyNearWallet or wallet.nearpages.wpengine.com, you don’t need to take any action. MyNearWallet service will not be interrupted in this transition and, in fact, users can expect product improvements over time from the chosen maintainer team. The goal is to offer more wallet options to users across the NEAR ecosystem and to decentralize the development of wallet products across the developer community. Pagoda will continue maintaining wallet.nearpages.wpengine.com. Over time, the NEAR wallet will integrate into the forthcoming NEAR Discovery product. But for now, no action is needed from users. Legacy wallet users may consider migrating to another wallet now that an expanded range of options is available via Wallet Selector, which will soon live on wallet.nearpages.wpengine.com. Numerous wallets optimizing for a variety of user types, security requirements, and use cases are already available, with more on the way in Q1. NEAR’s commitment to serving as the de facto entry point to Web3 remains intact. Building without limits is about continuously improving on industry standards and delivering the best possible experiences to developers and users alike.
The Creator Economy in Practice: Arroz Estúdios CASE STUDIES April 12, 2021 Arroz Estúdios is a Lisbon based Art Studio that has been open for more than two and a half years. With more than eight thousand members, the studio space boasts a physical area of fourteen Estúdios, two galleries, a co-working space, an outdoor bar and pizzeria, a garden and a venue capable of fitting more than 500 people. Arroz Estúdios is the future of the creator economy, and a fast learner of all things relating to the intersection of Art and Crypto. As one of the biggest projects of its kind in the city of Lisbon, Arroz started experimenting with Createbase, Digital Art and Non-Fungible Tokens in the fall of 2020. After successfully having launched a physical / digital art exhibition earlier this year, Arroz Estúdios has partnered up with the NEAR Foundation to host another exhibition for aspiring artists – this time with studio space available for low income artists! Planting A.I.R. (Artists in Residence)! Having secured funding from the NEAR Foundation, Arroz Estúdios is hosting a first-of-its kind event that will provide five artists with a four to eight week residency. During this time, the artists will not only have the opportunity to dive into the emerging world of digital art, they will also be documenting their journey for the NEAR community of creators to follow along. As stated in the proposal, Arroz Estúdios offers the following as part of the program: Studio space Learning resources Equipment & Materials Career support & development Workshops (with our studio holders Art Progression Now) Exhibition opportunities (inside the Estúdios and with Art Progression Now) How To Apply? A three week open call was launched last week. Interested artists can submit past work, their educational background, their artistic field of interest, existing portfolio, project proposal, detailed project schedule, CV and motivational letter. For more information in Portuguese click here. If you are ready to apply, the Open Call Submission Form can be filled out here. “We have had about 50 people already apply to exhibit with us for the next Rare Effect Exhibition, which is a huge uptake relative to the last one. The NFT space is changing so rapidly: Reaching out to people now compared to 6 months ago – everyone knows what an NFT is which means we can reach out to more artists, while also putting forward a great opportunity for Portuguese Artists!” – Steven A New Frontier For Artists: The Creator Economy Createbase is a community for creators/projects on Mintbase, an NFT minting platform on NEAR which is also based out of Lisbon- a growing hub for crypto and tech. With artists from all over the world familiarizing themselves with NFTs and the future of creator owned, creator distributed art, Arroz Estúdios is pioneering one of the first physical spaces for jumpstarting a creator economy in Lisbon. The goal of the initiative aligns with the fundamental values grounding the original development and growth of Arroz Estúdios: To promote freedom of expression. To provide a safe space for anyone coming to the studio to create anything they would like to express or imagine. To integrate with local communities and to promote Portuguese art on an international level. In the context of the Planting A.I.R. event, this will provide low-income artists in Portugal with a platform to showcase their art to the world. To bring international artists to Lisbon and Portugal for both events and learning purposes. As with previous events, Arroz Estúdios will be using the upcoming Planting A.I.R. project launch to attract musicians and artists from around the world to the growing creative hub in Lisbon. To find out more about the Arroz Studio event check out their approved proposal here. To join the growing community of Artists on NEAR Protocol, jump into the Createbase telegram chat! If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR documentation to get started.
--- id: predeployed-contract title: Pre-deployed Contract sidebar_label: Pre-deployed Contract --- > Learn how to easily receive fungible tokens without doing any software development by using a readily-available FT smart contract. ## Prerequisites To complete this tutorial successfully, you'll need: - [A NEAR testnet account](https://testnet.mynearwallet.com) - [NEAR-CLI](/tools/near-cli#setup) ## Using the FT contract ### Setup - Log in to your newly created account with `near-cli` by running the following command in your terminal: ```bash near login ``` - Set an environment variable for your account ID to make it easy to copy and paste commands from this tutorial: ```bash export NEARID=YOUR_ACCOUNT_NAME ``` :::note Be sure to replace `YOUR_ACCOUNT_NAME` with the account name you just logged in with including the `.testnet`. ::: - Test that the environment variable is set correctly by running: ```bash echo $NEARID ``` ### Receiving Fungible Tokens NEAR has deployed a new Fungible Token contract to the account `ft.predeployed.examples.testnet` which allows users to freely receive some `gtNEAR` - a new fungible token aimed to promote the power of teamwork! Each `gtNEAR` is equal to `1e24 yocto-gtNEAR` similar to how 1 $NEAR is equal to 1e24 yoctoNEAR. Using this pre-deployed contract, let's get some gtNEAR! Start by calling the method `ft_mint` which is a custom function implemented on this contract in order to send your account some `gtNEAR`! The following command will send `0.01 gtNEAR` to your account. ```bash near call ft.predeployed.examples.testnet ft_mint '{"account_id": "'$NEARID'", "amount": "10000000000000000000000"}' --accountId $NEARID ``` <details> <summary>Example response: </summary> <p> ```json Log [ft.predeployed.examples.testnet]: EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_mint","data":[{"owner_id":"benjiman.testnet","amount":"10000000000000000000000","memo":"FTs Minted"}]} Transaction Id Fhqa8YDLKxnxM9jjHCPN4hn1w1RKESYrav3kwDjhWWUu To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/Fhqa8YDLKxnxM9jjHCPN4hn1w1RKESYrav3kwDjhWWUu '' ``` </p> </details> - To view tokens owned by an account you can call the FT contract with the following `near-cli` command: ```bash near view ft.predeployed.examples.testnet ft_balance_of '{"account_id": "'$NEARID'"}' ``` <details> <summary>Example response: </summary> <p> ```json '2250000000000000000000' ``` </p> </details> ***Congratulations! You just received your first Team Tokens on the NEAR blockchain!*** 🎉 👉 Now try going to your [NEAR Wallet](https://testnet.mynearwallet.com) and view your FTs in the "Balances" tab. 👈 :::note Pre-deployed Contract The contract used in this section has been modified such that you can infinitely get `gtNEAR` by calling `ft_mint`. This function is not part of the FT [standards](https://nomicon.io/Standards/Tokens/FungibleToken/Core) and has been implemented for the purpose of this tutorial. ::: --- ## Final remarks This basic example illustrates all the required steps to call an FT smart contract on NEAR and receive your own fungible tokens. Now that you're familiar with the process, you can jump to [Contract Architecture](/tutorials/fts/skeleton) and learn more about the smart contract structure and how you can build your own FT contract from the ground up. ***Happy minting!*** 🪙 :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `3.4.0` :::
--- title: Overall BOS description: Overview of the NEAR Blockchain Operating System (BOS) sidebar_position: 1 --- # Blockchain Operating System (BOS) The OS for an open web ### Highlights: * A new OS, built for a more free and open web, that is inherently secure, decentralized, easy to develop on, easy to onboard to, accessible to everyone, open source, and transparent. * It removes the complexity from Web3 by allowing developers to build on any chain while having their apps be easily discoverable, and giving users a single identity across every experience that they can set up without any crypto. ### What it is: Built to be an open source alternative to Google, Apple, Amazon, Facebook, & Microsoft, the BOS is a secure, transparent, and accessible, carbon neutral platform that clears out the complexity of the Web3 space. The BOS removes the challenge of blockchain development by allowing developers to build on any chain, code in familiar languages, and use thousands of components to create innovative apps that are easy to distribute and get discovered. It gives users the ability to connect directly with an ever growing number of people, communities, and apps, while maintaining control over their data, without needing any crypto to get started. And it opens up a broad range of new capabilities and revenue streams to enterprises without the need for Web3 expertise. ### Why it matters: The current digital world is built on a centralized model in which a handful of large companies control much of the web, limiting accessibility, diversity, and creativity. This harms developers and users alike by creating an environment in which the main measure of success is the amount of data you control rather than by the quality of the apps and experiences you create. It is a system that benefits the few rather than the many. The promise of Web3 was to push back against this centralized system, but one of its biggest virtues, decentralization, has also been one of its biggest challenges. To choose to develop in the Web3 space developers had to learn complicated languages, and choose a specific blockchain with the hope that their project would be found. This made it complicated, and unappealing, for developers to enter the space, which in turn resulted in a lack of real use cases being developed, keeping mainstream adoption little more than a dream. The BOS changes all of that. The BOS unites the Web3 space by allowing developers to build on any blockchain while removing the complexity of swaps, exchanges, and multiple logins and identities. It also makes it possible for developers of all backgrounds to get started building right away with composable apps and the ability to code in Javascript. Its focus on simplicity, easy onboarding without the need for crypto, and discoverability benefits developers, enterprises, and users alike. And with a focus on projects that bring real value to end users, the BOS opens the door to true mainstream adoption of Web3. ### Who it’s for: * Developers - BOS provides developers with an easy to use, secure, and highly distributed Web3 gateway. They can quickly build apps on a decentralized front end using pre-existing components and a familiar coding experience. With just a few lines of Javascript developers can build on any chain, get their projects easily discovered, and seamlessly onboard users. * Enterprises - Enterprises can easily build new technological capabilities, roll out new products and experiences that increase user engagement, and create opportunities for new revenue. With seamless onboarding everything can be up and running quickly, removing barriers for entry for both enterprises and their users. * End-users - With simple onboarding without the need for crypto, a robust ecosystem of apps, and an engaged and growing community, the BOS provides users an easy entry point in a better digital world that gives them the user experiences they’ve come to expect, along with privacy, control over their data, and the ability to connect directly with other people and communities while having their voices be heard. ### Features: * FastAuth * A seamless web2 style onboarding experience that allows users to easily create an account for any app on the BOS without the need for crypto. It dramatically lowers the threshold for adoption and opens the door to bringing billions of web2 users into the web3 space. * Gateways * Access points for web 3 apps that allow developers to quickly add, and easily maintain, new experiences and functionality to their apps. It adds more value for end-users, simplifies development, and provides developers more entry points for their apps, increasing discoverability. * Developer Enablement * Built for any developer interested in open-source and decentralization, not only Web3 natives. It creates an accessible entry point for BOS with a comprehensive set of tools and capabilities to get developers started quickly. * Universal Search * A comprehensive search experience that is able to help users quickly find everything apps and components to people to connect with. It increases discoverability and usability in BOS by providing users with a Web2 style search experience. * Trust and Safety Content Moderation * A scalable, decentralized content moderation system built on the BOS for Web3 platforms with a focus on automation, user experience and adherence to legal requirements. It provides users with features that enable them to govern their own online experience. * NEAR Tasks * A new gig-economy platform powered by NEAR BOS that gives anyone the opportunity to quickly and easily earn $NEAR. It is a way to bring more users into the Web3 space and understand what tasks they are willing to complete to earn crypto.
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 }); const response = await wallet.viewMethod({ method: 'nft_token', args: { token_id: "1" } }); ``` _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> ```json { "token_id": "1", "owner_id": "bob.near", "metadata": { "title": "string", // ex. "Arch Nemesis: Mail Carrier" or "Parcel #5055" "description": "string", // free-form description "media": "string", // URL to associated media, preferably to decentralized, content-addressed storage "media_hash": "string", // Base64-encoded sha256 hash of content referenced by the `media` field. Required if `media` is included. "copies": 1, // number of copies of this set of metadata in existence when token was minted. "issued_at": 1642053411068358156, // When token was issued or minted, Unix epoch in milliseconds "expires_at": 1642053411168358156, // When token expires, Unix epoch in milliseconds "starts_at": 1642053411068358156, // When token starts being valid, Unix epoch in milliseconds "updated_at": 1642053411068358156, // When token was last updated, Unix epoch in milliseconds "extra": "string", // anything extra the NFT wants to store on-chain. Can be stringified JSON. "reference": "string", // URL to an off-chain JSON file with more info. "reference_hash": "string" // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. } } ``` </details> </TabItem> <TabItem value="Paras" label="Paras"> ```js const tokenData = fetch("https://api-v2-mainnet.paras.id/token?token_id=84686:1154"); ``` _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> ```json { "status": 1, "data": { "results": [ { "_id": "61dfbf27284abc1cc0b87c9d", "contract_id": "x.paras.near", "token_id": "84686:1154", "owner_id": "bob.near", "token_series_id": "84686", "edition_id": "1154", "metadata": { "title": "Tokenfox Silver Coin #1154", "description": "Holding this silver coin in your wallet will bring you health and happiness \uD83D\uDE0A", "media": "bafkreihpapfu7rzsmejjgl2twllge6pbrfmqaahj2wkz6nq55c6trhhtrq", "media_hash": null, "copies": 4063, "issued_at": null, "expires_at": null, "starts_at": null, "updated_at": null, "extra": null, "reference": "bafkreib6uj5kxbadfvf6qes5flema7jx6u5dj5zyqcneaoyqqzlm6kpu5a", "reference_hash": null, "collection": "Tokenfox Collection Cards", "collection_id": "tokenfox-collection-cards-by-tokenfoxnear", "creator_id": "tokenfox.near", "blurhash": "U7F~gc00_3D%00~q4n%M_39F-;RjM{xuWBRj", "score": 0, "mime_type": "image/png" }, "royalty": { "tokenfox.near": 1000 }, "price": null, "approval_id": null, "ft_token_id": null, "has_price": null, "is_creator": true, "total_likes": 8, "likes": null, "categories": [], "view": 4 } ], "count": 1, "skip": 0, "limit": 10 } } ``` </details> :::info See the [Paras API documentation](https://parashq.github.io/) for the full list of methods. ::: :::note Paras API methods returns data from all NFT contracts in NEAR. You might want to pass more parameters like `contract_id` or `owner_id` to make the response more accurate. ::: </TabItem> <TabItem value="Mintbase" label="Mintbase"> ```js const tokenData = fetch("https://graph.mintbase.xyz", { method: "POST", headers: { "mb-api-key": "anon", "Content-Type": "application/json", "x-hasura-role": "anonymous", }, body: JSON.stringify({ query: ` query getToken{ tokens: nft_tokens( where: { token_id: { _eq: "84686:1154" } } ) { tokenId: token_id ownerId: owner contractId: nft_contract_id reference issuedAt: issued_at copies metadataId: metadata_id } } `, }), }); ``` _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> ```json { "ok": true, "status": 200, "contentType": "application/json", "body": { "data": { "tokens": [ { "tokenId": "84686:1154", "ownerId": "bob.near", "contractId": "x.paras.near", "reference": "bafkreib6uj5kxbadfvf6qes5flema7jx6u5dj5zyqcneaoyqqzlm6kpu5a", "issuedAt": "2022-01-13T05:56:51.068358", "copies": 4063, "metadataId": "x.paras.near:5210047642790498956c9669d6a37b98" } ] } } } ``` </details> :::note In the future, users may be required to register using an api key. For now, simply passing the valueanon for `mb-api-key` will work. ::: :::tip Check how to do this also using the [`Mintbase JS`](https://docs.mintbase.xyz/dev/mintbase-sdk-ref/data/api/tokenbyid) ::: </TabItem> </Tabs>
--- id: debug-rpc-and-debug-pages title: Debug RPC and Debug Pages sidebar_label: Debug RPC and Debug Pages sidebar_position: 9 --- Recently, we’ve added a set of debug pages, that allow you to see more details about how your node works. ## Enabling debug page Debug support must be enabled in the `config.json` (auto-generated by `neard` with `init` command) ``` cd ~/path_to_nearcore/nearcore cargo run --package neard -- init # generates config.json on ~/.near/config.json vim ~/.near/config.json # update "enable_debug_rpc" ``` The file should be generated on the path `~/.near/config.json` with these default values. ``` "rpc": { ... "enable_debug_rpc": true } ``` And restarting your node. After this, you can go to `"/debug"` page to see links to all the sub-pages. > Important: If you’re a mainnet validator, we’d suggest you to firewall-protect access to debug pages & APIs. Some debug API calls are quite expensive and if someone spams them, they can overload the system and impact your block production speed. ## Information on debug pages Most of the debug pages should be self-explanatory, but here’s a quick overview of what they offer: ### Last blocks: * quick overview of the most recent blocks - including their gas usage, time spent, who was responsible for producing the block/chunk etc. ![](/images/debug_last_blocks.png) ### Network info * Shows you information about the currently reachable validators, about the state of your peers, and the routing of messages that are sent towards the validator ![](/images/debug_network.png) ### Epoch info * shows you information about current (and past) epochs - when did they start, how many validators etc * information about validator stakes, upcoming proposals & kickouts * the history of validators in the previous epochs * and shard sizes ![](/images/debug_epoch_info.png) ## Chain & chunk info page * shows you information about the recent blocks & chunks: * * when chunks were requested, what parts are we waiting for, how long did download take etc etc. ![](/images/debug_chain_chunk.png) ### Sync page ![](/images/debug_sync.png) shows the status of the sync (header sync, block sync etc) - and how many blocks are remaining it also show the status of the catchup - when you’re requesting to track a new shard ### Validator page * this page is the most complex one - as it shows the consensus layer: * * when your node sent approvals * * when your node is about to produce a block - it shows received approvals, chunk headers ![](/images/debug_validator.png) Thanks to this page, you can debug why a given block wasn’t produced, or why it didn’t contain a chunk. In the image above, the block 3253009 didn’t contain the chunk for shard 3, let’s understand why: * This node was a block producer for this block (otherwise this row would be empty) - at at some time "F", it received a first approval from one of the other validators. * Then more approvals and chunks started coming (for example munris.factory has sent chunk0 at time `F + 62ms` and `boot2.node` sent the approval at time `F + 528 ms` * At one moment, this node received the 2/3 of the approvals needed – this happened exactly at `F + 617 ms` - which we’d call the time "T". * At this time, it was still missing chunk from shard 3 - so it decided to wait a little. * 600ms later (so at time T + 643 ms) - it got tired of waiting and it produced the block WITHOUT chunk3 * In this example, we can see that verse2 was able to deliver the chunk eventually – but that was far too late (as it arrived more than 1.3 seconds after time T). For the block 3253014 - the situation was similar, but producer of chunk 4, was able to deliver it before the 600 ms cutoff (block arrived at `T + 430ms`) - which allowed this block producer to create the block 1 ms later (as all chunks were present). ### Approval history: At the bottom of the validator page, you can see “approval history” table: ![](/images/debug_approval.png) This shows all the approvals that your node has sent. When everything is running fine, you’ll see that your node is regularly sending approvals for the next blocks (from block X to block X+1). Once there are some missing blocks etc, the node might decide to start sending ‘skip’ requests (basically saying - please ignore the blocks in the middle and build a new block Y on top of block X ) This table becomes very useful during debugging reasons why blocks weren’t produced - as sometimes the block producer might not get the approvals. And using this page, we can check whether approval was generated and at what time.
NEAR After NEARCON In Numbers COMMUNITY September 30, 2022 Anyone who made the trip to Lisbon for NEARCON 2022, or tuned in via the YouTube livestream or Twitter, knew NEARCON was a smashing success. The vibe was something to behold. From devs and builders to other visionaries and champions of NEAR, NEARCON showcased the ecosystem and community at its very best—with boundless energy for creating without limits. This is an energy that was also palpable to the press. Everything came together to produce awe-inspiring momentum that is being sustained well beyond NEARCON’s aftermath. Let’s take a look at NEAR by the numbers in the wake of NEARCON to see just how the NEAR community is building without limits. 20M Accounts and 200M Transactions Coming out of NEARCON, the total amount of NEAR accounts hit a new high of 20 million. To be sure, this was an ecosystem and community effort. But Sweat Economy, who presented at NEARCON, is responsible for onboarding 14 million new users into the NEAR ecosystem with their move-to-earn app. That’s 20x growth since this time last year! Thanks to NEAR’s Nightshade sharding—Phase 1 of which was announced at NEARCON—this onboarding of the masses unfolded without a hitch. This example of NEAR’s infinite capacity is proof that it can welcome millions more users across the 800+ apps running on the protocol. Earlier this month, NEAR also hit a new milestone of 200 million on-chain transactions. Next up? 250 million. The ecosystem is growing by leaps and bounds, and doing so in a crypto winter. 21 Global Media Partners NEARCON was a major hit this year with members of the international press. All told, the conference attracted 21 global media partners, with CoinDesk leading the pack as NEAR’s top tier sponsor. Other major media outlets joined NEAR from around the world, including Cointelegraph, the Defiant, Coinpost Japan, W3volution Spain, and Business Insider Africa. Over 250 Pieces of Media Coverage Naturally, with so many global media partners, there is quite a lot of great news to share. Seven NEAR announcements and five partnership stories were pushed out to the global media. All together these ecosystem stories attracted 256+ pieces of coverage including a fantastic show roundup video by CryptoBanter, a hugely influential crypto YouTube channel that has over half a million subscribers. While US media outlets led with most of the NEARCON coverage, NEAR’s flagship conference also saw consistent reporting from media in India, Korea, Vietnam and beyond. Media Coverage Breakdown by Country Africa – 5 pieces of coverage Brazil – 5 pieces of coverage China – 5 pieces of coverage French – 8 pieces of coverage German – 2 pieces of coverage Italy – 4 pieces of coverage India – 18 pieces of coverage Japan – 2 pieces of coverage Korea – 11 pieces of coverage Spain – 5 pieces of coverage UK – 12 pieces of coverage US – 25 pieces of coverage Vietnam – 5 pieces of coverage Global – 150+pieces of coverage $100M Entertainment Fund Perhaps the biggest story to come out of NEARCON was the launch of NEAR’s $100 million entertainment fund. It captivated the press, appearing in coverage from international news outlets such as CoinDesk, International Business Times, Journal Du Coin France, China’s leading crypto title Panony , CoinPost Japan and Coin Press Korea. And rightly so. By partnering with Caerus for this new $100 VC Fund and Lab, NEAR will help push new Web3 innovation in culture, media, and entertainment. This fund now places NEAR at the forefront of changing how creative projects are financed, produced, and distributed, as well as how it’s consumed, owned, and monetized. 11 Visionary ‘Women of Web3 Changemakers’ Another big campaign launched at NEARCON—the Women of Web3 Changemakers. A partnership with Forkast News, thisinitiative celebrated 11 exceptional women shaping the future of Web3. The campaign attracted a great deal of interest from a global audience, with mentions in CoinDesk, Fintech Finance, and Yahoo Finance. NEAR Digital Collective (NDC) and Phase 1 Sharding announcements NEAR Co-founder Illia Polosukhin gave an exclusive interview with CoinDesk about the NEAR Digital Collective (NDC). This interview was syndicated in various media outlets across Africa, Brazil, and China. CoinDesk also covered NEAR’s Phase 1 Sharding news, which made significant waves in the developer community as well as international headlines. Meanwhile, Pagoda announced their Pagoda Console—a ‘one stop’ tool shop that gives devs all the kit they need to build Web3 apps. NEAR hubs launch in India and Vietnam NEARCON also witnessed the launch of two major regional hubs—Vietnam and India. NEAR Foundation worked closely with the Vietnamese press to amplify the story locally, and with great success. Vietnam’s major tech titles covered the announcement, including Zing news. NEAR Foundation replicated this approach with India’s media outlets, garnering coverage in major titles such as YourStory, the local equivalent of TechCrunch. Interviews were also secured with Reuters, Bloomberg and Times of India. Other stories from the NEAR ecosystem NEAR Foundation pushed out announcements on Tether (USDT) going live on NEAR, Sender Wallet’s $3.5 million funding round, and Few and Far’s ambition to grow the NEAR NFT ecosystem. There were also announcements for NEAR’s partnership with Fireblocks, which will bring innovative crypto technologies to new global institutional investors, and SWEAT Economy’s tokenomics. As with many of the other stories and announcements from NEARCON, these stories had mass global appeal. Coverage could be found in The Block, Cointelegraph, Forbes India, and CryptoTVPlus Africa. The sheer amount of positive press comes at a critical time for NEAR. The entire ecosystem and the wider Web3 world are building through a crypto winter but also battling other macroeconomic forces, post-Covid trauma, and climate change. It’s a time for resilience and creativity in how the NEAR and Web3 communities rethink and refashion the internet, and more importantly, the world. NEARCON demonstrated to the people across the globe that the protocol, ecosystem, and community will not be deterred. Builders and investors are still flocking to NEAR to build the next generation of decentralized apps. This is what creating without limits looks like. And it’s just the beginning!
--- NEP: 181 Title: Non Fungible Token Enumeration Author: Chad Ostrowski <@chadoh>, Thor <@thor314> DiscussionsTo: https://github.com/near/NEPs/discussions/181 Status: Final Type: Standards Track Category: Contract Created: 03-Mar-2022 Requires: 171 --- ## Summary Standard interfaces for counting & fetching tokens, for an entire NFT contract or for a given owner. ## Motivation Apps such as marketplaces and wallets need a way to show all tokens owned by a given account and to show statistics about all tokens for a given contract. This extension provides a standard way to do so. ## Rationale and alternatives While some NFT contracts may forego this extension to save [storage] costs, this requires apps to have custom off-chain indexing layers. This makes it harder for apps to integrate with such NFTs. Apps which integrate only with NFTs that use the Enumeration extension do not even need a server-side component at all, since they can retrieve all information they need directly from the blockchain. Prior art: - [ERC-721]'s enumeration extension ## Specification The contract must implement the following view methods: ```ts // Returns the total supply of non-fungible tokens as a string representing an // unsigned 128-bit integer to avoid JSON number limit of 2^53; and "0" if there are no tokens. function nft_total_supply(): string {} // Get a list of all tokens // // Arguments: // * `from_index`: a string representing an unsigned 128-bit integer, // representing the starting index of tokens to return // * `limit`: the maximum number of tokens to return // // Returns an array of Token objects, as described in Core standard, and an empty array if there are no tokens function nft_tokens( from_index: string|null, // default: "0" limit: number|null, // default: unlimited (could fail due to gas limit) ): Token[] {} // Get number of tokens owned by a given account // // Arguments: // * `account_id`: a valid NEAR account // // Returns the number of non-fungible tokens owned by given `account_id` as // a string representing the value as an unsigned 128-bit integer to avoid JSON // number limit of 2^53; and "0" if there are no tokens. function nft_supply_for_owner( account_id: string, ): string {} // Get list of all tokens owned by a given account // // Arguments: // * `account_id`: a valid NEAR account // * `from_index`: a string representing an unsigned 128-bit integer, // representing the starting index of tokens to return // * `limit`: the maximum number of tokens to return // // Returns a paginated list of all tokens owned by this account, and an empty array if there are no tokens function nft_tokens_for_owner( account_id: string, from_index: string|null, // default: 0 limit: number|null, // default: unlimited (could fail due to gas limit) ): Token[] {} ``` ## Notes At the time of this writing, the specialized collections in the `near-sdk` Rust crate are iterable, but not all of them have implemented an `iter_from` solution. There may be efficiency gains for large collections and contract developers are encouraged to test their data structures with a large amount of entries. ## Reference Implementation [Minimum Viable Interface](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/non_fungible_token/enumeration/mod.rs) [Implementation](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/non_fungible_token/enumeration/enumeration_impl.rs) ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/). [ERC-721]: https://eips.ethereum.org/EIPS/eip-721 [storage]: https://docs.near.org/concepts/storage/storage-staking
Chain Signatures Launch to Enable Transactions on Any Blockchain from a NEAR Account DEVELOPERS March 26, 2024 Today at BUIDL Asia in Seoul, Korea, NEAR Co-Founder and NEAR Foundation CEO Illia Polosukhin announced the launch of Chain Signatures on NEAR. Chain Signatures enable NEAR accounts, including smart contracts, to sign transactions for any blockchain. This is powered by a decentralized MPC network which uses NEAR staking and Eigenlayer ETH restakers for security. Chain Signatures currently supports Bitcoin, Ethereum, Cosmos chains, DogeCoin, and XRP Ledger and will soon support Solana, TON Network, Polkadot, and others. How Chain Signatures Work Chain signatures introduce threshold signatures for any blockchain, controlled by NEAR accounts & smart contracts. A NEAR account, which can also be a smart contract thanks to the NEAR account model, can request that the NEAR validators or MPC nodes sign an arbitrary payload, which could be a transaction for some other blockchain, and get a signed payload back to then send to the destination chain. This is made possible by building an account-based decentralized Multi-Party Computation (MPC) network, allowing NEAR accounts to control multiple addresses on various chains and ensuring that the users are the only ones who can request signatures for transactions. Chain Signatures uses an account-based pattern, as opposed to a deposit-based or bridge-based pattern, as most other MPC networks currently in production do. The Chain Signatures MPC network functions as a decentralized signer for NEAR accounts and smart contracts, managing requests to addresses on different blockchains while placing zero burden on the user to manage these. The first of its kind, Chain Signatures is a major advancement in DeFi adoption by enhancing cross chain interoperability and unlocking a new variety of use cases for mainstream users and Web3 builders. Chain signatures makes it easier to build DeFi products for particular chains and assets (while utilizing assets from other chains e.g. USDC/T, SOL, etc). For example, users can use XRP as collateral to borrow USDC, or trade DOGE for SOL. The launch of Chain Signatures delivers an elevated user experience that simplifies the transaction process while increasing accessibility to liquidity on non-smart contract chains such as Bitcoin, DogeCoin, XRP Ledger, and more. This also means that Chain Signatures let app developers serve all ecosystems at once from one interface rather than having to commit to a single chain or pool of liquidity. The Chain Signatures MPC network is launching with Eigenlayer as a key partner and will be secured by Eigenlayer ETH restakers and NEAR stakers. The initial operator set is a trust-minimized network of ten node providers, which includes some top Eigen AVS infrastructure providers, using a Proof of Authority security model at launch. The future state is a permissionless network of node operators based on staking requirements and slashing conditions, planned to roll out in the coming months. Multichain Gas Relayer Launching alongside Chain Signatures is the Multichain Gas Relayer, which removes the need to have the native gas token of another chain in order to transact. This is a big hurdle for users today, often requiring purchasing multiple tokens on exchanges and sending them to different accounts just to complete a single cross-chain action. Now, with the Multichain Gas Relayer, users can just use NEAR or NEP-141 tokens to cover gas on any chain, not just NEAR or EVM chains. This unlocks true multichain account abstraction. Whereas cross-chain bridges vary significantly depending on which assets are bridging to which chains, chain signatures makes transacting on smart contract and non-smart contract chains possible from a single account or interface, while simultaneously unlocking liquidity that wouldn’t have been accessible before. For a longer technical deep dive on Chain Signatures and the Multichain Gas Relayer, see this post from February 2024 about NEAR account aggregation technologies. New Web3 Design Patterns with Chain Signatures Chain Signatures unlocks a range of powerful new use cases for application builders and DeFi developers while also enabling much simpler user interfaces across different contexts. Smart contracts on NEAR will be able to custody assets on any chain (since they can sign transactions on any chain via chain signatures), and maintain user balances similar to how single chain lending protocols or DEXs do now. For example, a user will be able to atomically swap their BTC in a Bitcoin account for another user’s ETH in an Ethereum account. This works because they can first deposit into accounts on these respective chains that are fully controlled by a NEAR smart contract, which will then settle the trade and allow the user’s to withdraw their “new” assets post-trade. DeFi on non-smart contract chains: NEAR smart contracts can sign transactions for non-smart contract chains like Bitcoin, Celestia, Bittensor, XRP Ledger, and others. This enables DEXs, lending protocols, and other DeFi apps to be built using the native assets of these chains, unlocking previously inaccessible liquidity. Bridgeless cross-chain DeFi: Since NEAR smart contracts can custody assets on any chain, users can build truly cross chain applications such as RFQs, orderbooks, AMMs, lending protocols, and more. It is also possible to build swaps and other apps without bridges and message passing layers, meaning that new chains and assets can be added at launch. Additionally, chain signatures can be used to build two-way bridges to non-smart contract chains, using NEAR as the intermediate chain. Multichain Account Abstraction: A single NEAR account can manage any number of accounts on any number of chains. This means users can get ERC 4337-like functionality (natively supported by NEAR) without deploying any new smart contracts (so they can use non-EVM and non-smart contract chains), or needing to update their accounts on each individual chain. Chain Signatures also enables users to pay for gas costs on various chains with USDC, including non-EVM chains. Instantly multichain apps at launch: Thanks to Chain Signatures and the Multichain Gas Relayer, app developers don’t need to commit to a single chain when they start building––now, they can make many chains accessible to their users immediately after launching and dramatically increase their addressable market of users. Advancing the Chain Abstraction Vision Chain Signatures advances the NEAR ecosystem’s vision of Chain Abstraction, or the idea that Web3 hurdles should be abstracted away from user interfaces for the sake of simplicity and accessibility. Many of these hurdles arise with multichain use cases as users need to deal with long lists of accounts on different chains, manually move assets between them, and manage all the related security. Now, with Chain Signatures, users can simply create and secure one account and then start transacting on any network in Web3. Chain Signatures also help dapp developers deliver better multichain experiences to their users and get access to all available liquidity across blockchains. As Illia noted, “Since day one, the NEAR ecosystem has focused on simplifying access to Web3 for developers and mainstream users. Chain Signatures is the next step in that journey, making it significantly easier to transact on any blockchain while also defragmenting liquidity across the ecosystem. This will enable the next generation of truly decentralized apps to deliver much more powerful experiences and address the entire market of Web3 users.” Live Use Cases In the Ecosystem Several projects in the NEAR ecosystem are already building with Chain Signatures to introduce new design patterns and experiences to users. More information on the node provider ecosystem as well as news about additional projects building with Chain Signatures across Web3 is coming in the next few weeks. SWEAT Economy, a top ten most used decentralized app (dApp), utilizes Multichain Gas Relayer to let users send transactions from NEAR to BNB chain and pay for the gas in SWEAT tokens earned in-app. East Blue, a Bitcoin Layer 2, uses NEAR Chain Signatures to develop Bitcoin DeFi use cases that were not possible until now, providing a new way to extend Bitcoin with smart contract logic. LiNEAR is building a multichain, multi-asset restaking framework on top of Eigenlayer, enabling non-ETH assets including NEAR to be restaked and used for securing applications. Mintbase, an NFT infrastructure platform, enables NEAR-based Mintbase wallet holders to purchase Ethereum NFTs directly. Start Building with Chain Signatures Chain Signatures makes possible a range of new use cases for Web3 developers and users alike, opening up an exciting new design space and expanding the landscape of multichain apps and experiences utilizing Chain Abstraction. Builders and developers interested in getting started with Chain Signatures can visit the documentation or explore code examples and begin building today. Projects looking for support implementing Chain Signatures can register their interest here.
NEAR Validator Upgrade Allows Hundreds To Help Secure The Network DEVELOPERS November 29, 2021 Since the NEAR Mainnet launch in October 2020, we have seen steady growth in the number of validators. Today, NEAR has roughly 60 validators on mainnet, with many more wanting to join. Nevertheless, the extremely high threshold of 3.6M $NEAR makes it challenging for new validators to join. This was certainly not our intention when we designed the current validator selection algorithm more than three years ago. That’s why we’re upgrading our validator process. At present, the issue with the current algorithm is that the maximum number of validators allowed by the protocol is only achievable when everyone has an equal amount of stake. In practice, this is unrealistic. The NEAR Ecosystem is working to add more validators to the blockchain to further decentralize the network. After reviewing a number of options, we made the decision to change the protocol’s validator selection process. This will take place in two steps: the top 100 proposals by stake amount will be listed as potential validators. The second step will be to ensure the number of tokens staked is high enough to maintain the security of the network. While 3.5 million $NEAR is very high, we want to avoid making the new number too low. Improving access, one step at a time Compared to the existing selection algorithm, this seemingly simple change requires a lot of heavy lifting behind the scenes. NEAR’s target block speed of 1 second means that any validator selection process must be extremely fast while continuing to maintain the security of the network. This means the change requires very fast sampling from a discrete probability distribution. NEAR’s core developer team is happy to announce that this change has now been implemented, allowing more validators to join NEAR. This is great news for validators as it will dramatically reduce the barrier of entry to mainnet and makes it easier for them to maintain their seats. If more than 100 proposals are submitted, the threshold will simply be the stake of the 100th proposal, provided that it’s larger than the minimum threshold*. We expect to reach 100 validators soon after Mainnet is upgraded to this change—leading to a 60% increase in the number of validators we have active today. Other than the change to the validator selection process, everything else remains the same. Validators still produce blocks proportional to their stake and receive rewards accordingly. 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 to add another 200 validators to 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, and to onboard validators onto the NEAR Mainnet, we have collaborated with the Open Shard Alliance to release a bootcamp to help train new validators. If you’re interested in joining our bootcamp, you can find more information here. If you’d like to start running your nodes on Testnet and Mainnet, head to the Open Shards Alliance server on Discord. * The minimal threshold depends on the total amount of stake, which at this point we estimate it to be 67,000 NEAR.
--- id: nft title: Non-Fungible Tokens (NFT) 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 BOSMintNFT from "./nft/bos/mint.md" import BOSBuyNFT from "./nft/bos/buy.md" import BOSQueryNFT from "./nft/bos/query.md" import BOSTransferNFT from "./nft/bos/transfer.md" import BOSListNFTForSale from "./nft/bos/list-for-sale.md" import WebAppMintNFT from "./nft/web-app/mint.md" import WebAppBuyNFT from "./nft/web-app/buy.md" import WebAppQueryNFT from "./nft/web-app/query.md" import WebAppTransferNFT from "./nft/web-app/transfer.md" import WebAppListNFTForSale from "./nft/web-app/list-for-sale.md" import CLIMintNFT from "./nft/near-cli/mint.md" import CLIBuyNFT from "./nft/near-cli/buy.md" import CLIQueryNFT from "./nft/near-cli/query.md" import CLITransferNFT from "./nft/near-cli/transfer.md" import CLIListNFTForSale from "./nft/near-cli/list-for-sale.md" import SmartContractMintNFT from "./nft/smart-contract/mint.md" import SmartContractBuyNFT from "./nft/smart-contract/buy.md" import SmartContractQueryNFT from "./nft/smart-contract/query.md" import SmartContractTransferNFT from "./nft/smart-contract/transfer.md" In contrast with fungible tokens, non-fungible tokens (NFT) are unitary and therefore unique. This makes NFTs ideal to represent ownership of assets such as a piece of digital content, or a ticket for an event. As with fungible tokens, NFTs are **not stored** in the user's wallet, instead, each NFT lives in a **NFT contract**. The NFT contract works as a bookkeeper, this is: it is in charge of handling the creation, storage and transfers of NFTs. In order for a contract to be considered a NFT-contract it has to follow the [**NEP-171 and NEP-177 standards**](https://nomicon.io/Standards/Tokens/NonFungibleToken). The **NEP-171** & **NEP-177** standards explain the **minimum interface** required to be implemented, as well as the expected functionality. :::info NFT & Marketplaces Be mindful of not confusing an NFT with an NFT-marketplace. NFT simply store information (metadata), while NFT-marketplaces are contracts where NFT can be listed and exchanged for a price. ::: --- ## Community Projects The easiest way to create and handle NFTs is by using one of the existing community projects. 1. [Paras](https://paras.id/) - a classic NFT marketplace. Just login with your NEAR account, create a collection and share the link with your community. 2. [Mintbase](https://www.mintbase.xyz/) - a marketplace that allows to create NFT collections, and buy NFTs using credit cards or stablecoins. 3. [Enleap](https://enleap.app/) - a no-code launchpad for NFTs. Provides NFT minting, staking, whitelist managing, tracking functionality. --- ## Deploying a NFT Contract If you want to deploy your own NFT contract, you can create one using our [reference implementation](https://github.com/near-examples/NFT) Simply personalize it and deploy it to your account. ```bash near deploy <account-id> --wasmFile contract.wasm --initFunction new ``` :::tip Check the [Contract Wizard](https://near.org/contractwizard.near/widget/ContractWizardUI) to create a personalized NFT contract!. ::: --- ## Minting a NFT To create a new NFT (a.k.a. minting it) you will call the `nft_mint` method passing as arguments the metadata that defines the NFT. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSMintNFT /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppMintNFT /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIMintNFT /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract" default> <SmartContractMintNFT /> </TabItem> </Tabs> :::info See the [metadata standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata) for the full list of `TokenMetadata` parameters. ::: :::warning Values of gas and deposit might vary depending on which NFT contract you are calling. ::: <hr className="subsection" /> ### Minting Collections Many times people want to create multiple 100 copies of an NFT (this is called a collection). In such cases, what you actually need to do is to mint 100 different NFTs with the same metadata (but different `token-id`). :::tip Notice that [minting in Mintbase](#minting-a-nft) allows you to pass a `num_to_mint` parameter. ::: <hr className="subsection" /> ### Royalties You might have noticed that one of the parameters is a structure called royalties. Royalties enable you to create a list of users that should get paid when the token is sell in a marketplace. For example, if `anna` has `5%` of royalties, each time the NFT is sell, `anna` should get a 5% of the selling price. --- ## Querying NFT data You can query the NFT's information and metadata by calling the `nft_token`. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSQueryNFT /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppQueryNFT /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIQueryNFT /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract"> <SmartContractQueryNFT /> </TabItem> </Tabs> --- ## Transferring a NFT Transferring an NFT can happen in two scenarios: (1) you ask to transfer an NFT, and (2) an [authorized account](#approving-users) asks to transfer the NFT. In both cases, it is necessary to invoke the `nft_transfer` method, indicating the token id, the receiver, and an (optionally) an [approval_id](https://nomicon.io/Standards/Tokens/NonFungibleToken/ApprovalManagement). <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSTransferNFT /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppTransferNFT /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLITransferNFT /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract"> <SmartContractTransferNFT /> </TabItem> </Tabs> --- ## Attaching NFTs to a Call Natively, only NEAR tokens (Ⓝ) can be attached to a function calls. However, the NFT standard enables to attach a non-fungible tokens in a call by using the NFT-contract as intermediary. This means that, instead of you attaching tokens directly to the call, you ask the NFT-contract to do both a transfer and a function call in your name. <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="🖥️ CLI" label="🖥️ CLI"> ```bash near call <nft-contract> nft_transfer_call '{"receiver_id": "<receiver-contract>", "token_id": "<token_id>", "msg": "<a-string-message>"}' --accountId <your-account> --depositYocto 1 ``` </TabItem> </Tabs> :::info Optionally, a [`memo` parameter](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core#nft-interface) can be passed to provide more information to your contract. ::: <hr className="subsection" /> ### How Does it Work? Assume you want to attach an NFT (🎫) to a call on the receiver contract. The workflow is as follows: 1. You call `nft_transfer_call` in the NFT-contract passing: the receiver, a message, and the token-id of 🎫. 2. The NFT contract transfers the NFT 🎫 to the receiver. 3. The NFT contract calls **`receiver.nft_on_transfer(sender, token-owner, token-id, msg)`**. 4. The NFT contract handles errors in the `nft_resolve_transfer` callback. 5. The NFT contract returns `true` if it succeeded. #### The nft_on_transfer method From the workflow above it follows that the receiver we want to call needs to implement the `nft_on_transfer` method. When executed, such method will know: - Who is sending the NFT, since it is a parameter - Who is the current owner, since it is a parameter - Which NFT was transferred, since it is a parameter. - If there are any parameters encoded as a message The `nft_on_transfer` **must return true** if the NFT has to be **returned to the sender**. --- ## Approving Users You can authorize other users to transfer an NFT you own. This is useful, for example, to enable listing your NFT in a marketplace. In such scenario, you **trust** that the marketplace will only transfer the NFT upon receiving a certain amount of money in exchange. <Tabs groupId="code-tabs"> <TabItem value="🖥️ CLI" label="🖥️ CLI"> ```bash near call <nft-contract> nft_approve '{ "token_id": "<token-unique-id>", "account_id": "<authorized-account>", "msg": "<json-structure>" }' --accountId <your-account> --depositYocto 1 ``` </TabItem> </Tabs> :::info If the `msg` parameter is included, then a cross-contract call will be made to `<authorized_account>.nft_on_approve(msg)`. Which in turn will make a callback to `nft_resolve_transfer` in your NFT contract. ::: --- ## List a NFT for sale Basic NFT contracts following [the NEP-171 and NEP-177 standards](https://nomicon.io/Standards/Tokens/NonFungibleToken) do not implement marketplace functionality. For this purpose, there are ecosystem apps such as [Paras](https://paras.id/) or [Mintbase](https://www.mintbase.xyz/), that use dedicated marketplace contracts. In order to put a NFT for a sale on a marketplace you need to do two actions: 1. Cover data storage costs in the marketplace contract. 2. Approve the marketplace to sell the NFT in your NFT contract. <br /> <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSListNFTForSale /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppListNFTForSale /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIListNFTForSale /> </TabItem> </Tabs> --- ## Buy a NFT Basic NFT contracts following [the NEP-171 and NEP-177 standards](https://nomicon.io/Standards/Tokens/NonFungibleToken) do not implement marketplace functionality. For this purpose, there are ecosystem apps such as [Paras](https://paras.id/) or [Mintbase](https://www.mintbase.xyz/), that use dedicated marketplace contracts. <Tabs groupId="code-tabs"> <TabItem value="⚛️ Component" label="⚛️ Component" default> <BOSBuyNFT /> </TabItem> <TabItem value="🌐 WebApp" label="🌐 WebApp"> <WebAppBuyNFT /> </TabItem> <TabItem value="🖥️ CLI" label="🖥️ CLI"> <CLIBuyNFT /> </TabItem> <TabItem value="📄 Contract" label="📄 Contract" default> <SmartContractBuyNFT /> </TabItem> </Tabs> --- ## Additional Resources 1. [NFT Tutorial](/tutorials/nfts/js/introduction) (NEAR examples, JavaScript SDK) - a set of tutorials that cover how to create a NFT contract using JavaScript. 2. [NFT Tutorial](/tutorials/nfts/introduction) (NEAR examples, Rust SDK) - a set of tutorials that cover how to create a NFT contract using Rust. 3. [NFT Tutorial by Keypom](https://github.com/keypom/nft-tutorial-series) (a fork of the NEAR example tutorial). 4. [Paras API documentation](https://parashq.github.io/). 5. [Mintbase API documentation](https://docs.mintbase.xyz/dev/mintbase-graph). 6. [Mintbase JS SDK](https://docs.mintbase.xyz/dev/mintbase-sdk-ref) - a set of methods to get data from blockchain, interact with Mintbase contracts, etc.
NEAR Community Update: April 5, 2019 COMMUNITY April 5, 2019 We’ve already open sourced our code on Github so developers can follow along as the blockchain and its tooling comes together. Frankly, open-sourcing the protocol development is table stakes and every credible next-generation protocol has already done this. As we begin expanding our ecosystem and polishing up the application layer that supports developers and their end-users, we’d also like to apply a similar openness to our other development efforts. To that end, we’re experimenting with an “open design” process where anyone can see our product development work on Discord in the #PRODUCT channels. Join us and jump in. Let’s build the future together. Community and Events Congratulations to the 3 winning teams at the Nueva Hacks hackathon, “Team H II R” (addressing teen depression), “Credit Secured” (better credit scores) and “Team Biased” (eliminating media bias). Recent Events [Berlin] Mar 25: NEAR, Fluence and Cosmos DevNet and MainNet Demo Night [SF] Mar 27: Unblocked SF with Erik Trautman of NEAR Protocol [SF] Mar 28: Decentralized Computing with WASM @ Github [Uruguay] Mar 29: Rust Latam conference [San Mateo] Mar 30–31: Nueva Hacks Hackathon Upcoming Events [Sydney] April 8–13: EdCon [SF] April 10: NEAR, Cosmos & Fluence: Devnet & Mainnet Demo Night I [Santa Clara] April 11: NEAR, Cosmos & Fluence: Devnet & Mainnet Demo Night II [Fremont] April 20: Launch Hacks hackathon If you want to collaborate on events, reach out to [email protected] Writing and Content The whiteboard series continues to be a great opportunity for projects to get credible technical exposure and for us to learn from exceptional founders. More in the queue! Ep12: James Prestwich from Summa Ep13: Tom Close from Magmo Unqualified Opinions interview with Ryan Selkis of Messari Our technical documentation also continues to improve every day thanks to heroic efforts from the dev and dev rel teams. Engineering Highlights On the application/development layer, we’ve open-sourced our product development process. Now, anyone can contribute on our chat (http://near.chat) in the #product channels. On the blockchain layer, we’ve been working hard to stabilize and improve the performance on our multi-node TestNet (pre-release). We’ve also added support for containerized deploys! As an anecdote, @Evgeny built a Pokedex live at a WASM meetup hosted by Github. Later, someone said the live demo was so smooth and fast they thought we were cheating by having planted a suggestion in the audience. There were 54 PRs in nearcore from 10 different authors over the last couple of weeks. As always, the code is completely open source on Github. Blockchain Layer Implemented scripts for managing TestNet in the cloud and locally using Docker and GCP. Check out how to do it in the docs. Consolidated testing infrastructure for DevNet and TestNet Implemented layer to manipulate network traffic (similar to Linux traffic control) used for testing Application/Development Layer Command line tool now includes local template generation that includes the ability to test against apps deployed to devnet Devs can now build a contract, deploy to DevNet and deploy a front end to GitHub Pages with `npm run deploy` from template projects Continued work on improving receipts for cross-contract calls. Added persistent collections to NEAR AssemblyScript library Integrated NEAR, React and next.js at our internal hackathon with a fun toy and a cuter example. Updated the UI for the debugger. Made example chess game deployed on GitHub Pages How You Can Get Involved Join us! If you want to work with one of the most talented teams in the world right now to solve incredibly hard problems, check out our careers page for openings. And tell your friends 🙂 Learn more about NEAR in The Beginner’s Guide to NEAR Protocol. 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. Reminder: you can help out significantly by adding your thoughts in our 2-minute Developer Survey.
--- sidebar_position: 2 --- # Reproducible Builds Reproducible builds let different people build the same program and get the exact same outputs as one another. It helps users trust that deployed contracts are built correctly and correspond to the source code. To verify your contract user can build it themselves and check that the binaries are identical. ## Problem If you will build your contract on two different machines, most likely you will get two similar but not identical binaries. Your compiled `.wasm` file is dependent on several factors as the node version used and dependency sub versions. ## Control for Dependencies We recommend sharing lockfiles (and updating them only when dependencies are added or removed) between machines and specifying node versions to ensure that the same dependencies are used.
Future of Blockchain Hackathon: NEAR Recap COMMUNITY May 21, 2020 NEAR participated in the Future of Blockchain Hackathon hosted by StakeZero Ventures. The hackathon started in December 2019 and continued until March 2020. We would like to thank StakeZero Ventures for hosting the event, and all those amazing participants, whom we had a chance to meet and get started building on NEAR. What made this hackathon special? We want to make our resources available for all developers, no matter their technical background and experience with blockchain technologies. To engage students across our initiatives we place extra focus on creating accessible resources, on working directly with university clubs and participating in academic initiatives like the Future of Blockchain Hackathon. In most crypto-related hackathons, participants are either long-time developers from the web2 space or already familiar with developing decentralised applications (dApps). In comparison, the Future of Blockchain Hackathon creates a space for students to get started developing on blockchains by providing more time. Rather than taking place over a weekend, participants have a much longer period to build. In the end, participants are able to showcase a more thoughtful, in-depth project. For further information, head over to their blog. NEAR had more than a dozen teams sign up to participate from a range of backgrounds including everyone from PhD candidates to undergraduate students. Overall, most of the students who participated had never read into blockchain before. Thus, their approach to new challenges was quite different to developers, who already have a mental model in place on how they like to solve challenges. Ultimately, 10 teams submitted a final project, which moved forward into the judging phase. Prizes For the full prize list and projects that have been selected, please refer to the official post by StakeZero Ventures. The second prize went to two amazing projects, ChironCoin and NEAR Finance. ChironCoin enables the sharing of trading algorithms through a platform-specific token. NEAR Finance is a Finance tracking and management extension to the NEAR wallet. The final prize went to Vivid IoV Labs. Our Community Manager Anais had a call with the team to get further insights on their hackathon experiences and learn more about their plan ahead. Interview with Vivid IoV Labs Could you please summarise Vivid? Vivid enables you to see what’s happening anywhere in the world in real-time by making live video streaming requests. What’s happening on the ground right now? How’s the surf? How are the crowds at the protest? These questions get answered in real-time. The startup is a peer-to-peer live-streaming app that leverages blockchain-based micropayments, a concept that wouldn’t be viable on a standard network, to reward content creators in real-time. As a stream gains popularity a payment pool is created incentivising a variety of user types, not just influencers. Location-based bounties help companies engage with users in an interactive way through our platform. Machine learning is used to create a reputation system that will help to maintain an abuse-free experience for participants. How did you come to work together? Did you know each other before? We have in fact only recently met. Each of us applied to UCL & Ripple’s Block-Sprint hackathon as individuals, however, after winning the top award it was clear we had a good team to carry on with and therefore formalised the company, Vivid IoV Labs. Each member of the team has a solid skillset in disparate areas which we think makes us work well together. Where did the idea for your App come from? Is there a backstory? The original idea was seeded when the founders found themselves mutually frustrated at clickbait from content creators and a user experience blighted by ad interruptions. After working on another location-based platform, we saw the opportunity to empower users to receive the viewing experience they want by requesting content within a map interface. Uber for live Streaming! Having been monitoring blockchain developments for a number of years, it was apparent that there was a great opportunity to leverage new tech, such as micropayments, for a new type of app in the booming live streaming market – fundamentally improving the user experience for viewers whilst creating a fairer method for rewarding creators. What importance does blockchain have in building your App? I.e. Why Blockchain? Enables micropayments – we want to help people stream money as this can unlock all manner of opportunities. Payment settlement can be incredibly fast – we want to provide efficient processes and choice for our customers. Supports the web 3.0 economy – we want to onboard customers into the new economy and play our part in providing privacy, transparency and giving users control of their data and assets. Sharing the wealth – we want to provide a fairer way for content producers and publishers to be rewarded for their work. What is your long-term vision for the App? To be the live streaming platform where users get the content they want and creators get paid fairly. Through the platform users can find out what’s happening at a particular place instantly, micro-influencers can fully engage followers with the requested content and are rewarded fairly, and brands can create highly engaging location-based experiences for fans. Why did you choose NEAR vs. any of the other Layer 1 Protocols that were present at the hackathon? Compatibility for micropayments Best developer resources Recommended by people within our network (reputation/word of mouth) For further insights and next steps for Vivid, have a look at their blog. If you have any questions about Vivid, please reach out directly to the founders here and sign-up on their website to be the first to hear about the latest developments. You are a student and want to get started on NEAR? Join us at the University of Washington Blockchain Hackathon from the 22nd to the 24th of May. You can find all information and how to sign-up on their website. How can you get involved? NEAR is hosting several hackathons and has weekly community events. You can find a full list in our events calendar. If you would like to get involved contributing to NEAR’s technical or community efforts, please have a look at the contributor program. We look forward to seeing you get involved. Have questions? Join our Community Chat.
NEAR Strategic Update and Outlook for 2023 NEAR FOUNDATION December 15, 2022 The recent stream of news clearly demonstrates that the world needs Web3. Trust in legacy institutions is breaking down, individual privacy and individual freedom are equally at risk, and the major Web2 platforms we use every day have become monopolies that focus on profit, not people. Yet Web3 also hasn’t fully delivered on its promise to open the web. While important progress has been made, much more needs to be done for this technology to deliver fairer, freer digital systems. Today’s Web3 suffers from inaccessible user experience, siloed applications which are difficult to discover, few real-world use cases, and technology tribalism. Put simply, too much hype and not enough value for users. Since 2018, NEAR has focused on building scalable, secure technology and infrastructure that is easy to use and enables developers to freely create usable applications. Since launching Mainnet in late 2020, the NEAR ecosystem has made incredible progress, becoming one of the top layer-one blockchains with 22 million accounts, 600K monthly active wallets (active defined as 2+ transactions), and 15x growth in users and projects just in the last year. And despite chaos in the market and a major downturn in recent months, NEAR Foundation has sufficient capital to sustain at least five years of operations in bear market conditions thanks to responsible treasury management. While Web3 has yet to deliver on its promises, NEAR Foundation believes that NEAR is the only ecosystem where Web3 promises can be delivered and where mainstream adoption can happen. All the fundamentals have been established for some time and NEAR is charging full-speed ahead into its next growth phase in 2023. This post will cover NEAR’s convictions heading into next year, the strategic approach to drive our next phase, and a look ahead at new areas of product and development. Fundamentals and Convictions NEAR has the best technology in Web3. Provably scalable, easy to onboard and use, developer friendly, secure, and decentralized, with the most advanced account model and onboarding in the blockchain space. NEAR has world-class talent and ample runway. From the core teams at the Foundation and Pagoda, to the incredible NEAR Foundation Council and advisors, to the diverse group of brilliant entrepreneurs building companies, apps, and funds on NEAR, some of the best talent in the world is here on NEAR. And thanks to the Foundation’s responsible treasury management, core ecosystem operations and funding are well-positioned to run for many years to come. Achieving mainstream adoption is about users. Not TVL, not flashy headlines, not cultish maximalism. NEAR focuses on what matters for the long term and the bear market will separate the high quality projects from the ones fueled mostly by hype. Web 2.5 will get us there. Sweatcoin proved that NEAR can support an app with tens of millions of users on open web infrastructure. This is the next phase of adoption: helping another generation of Web2 apps and communities take advantage of the opportunities Web3 offers while providing a richer, more sustainable experience to their users. Strategic Approach Enabling NEAR to make the most of these convictions in today’s climate means committing to the following goals over the next year. Growing usage on NEAR will begin with a top-down approach focused on partnerships. The world-class business development team at the Foundation will focus on working with major applications and brands with substantial, established communities to partner with NEAR on real use cases that drive engagement, such as ticketing and earning. High-traction focus verticals include sports, entertainment, and loyalty. Major partnerships in recent months include Grupo Nutresa, Google Cloud, and Sweat Economy. Any great Web3 ecosystem is an emergent product of a dedicated community of believers. The bottom-up, grassroots approach for the next year on NEAR will empower the community 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). This means the NEAR Foundation will no longer directly allocate capital to projects, instead supporting the community in these decisions and further decentralizing key elements of the ecosystem. These grassroots DAOs will be supported by the NDC, which has achieved initial traction, including launching a new Governance Working Group and plans to roll out a v1 governance infrastructure for the ecosystem early next year. In the new year, the NEAR Foundation will form an early-stage accelerator that will provide support to promising projects and founders on NEAR in areas including education, tech, hiring, legal, UX, and GTM guidance, setting them up to grow into the landmark Web3 projects of tomorrow. Looking Ahead With NEAR’s protocol, infrastructure, and developer tooling already well established, the next step in providing the best user experience to Web3 will be at the discovery layer: the connective tissue that connects applications, tooling, social, earning, and developer components across the open web. This stack is what we call a “blockchain operating system.” Many of the building blocks of the blockchain operating system already exist on NEAR, either as features or apps. These include NEAR Crowd, a gig economy platform with 50% of users transacting every day, and NEAR Social, an on-chain social network with a widget framework that lets developers fork entire app frontends to build new experiences. Combined with upcoming improvements to onboarding, including from EVM wallets (which we’re calling remote accounts), native meta transactions, Keypom, and new chat/social capabilities, NEAR will deliver even more amazing value directly to developers and users. All of these user-centric elements further up the stack, particularly at the app layer, will form the basis for a core component of the NEAR ecosystem’s product and technical focus in 2023. Pagoda, NEAR Foundation, and other key ecosystem participants will work together to deliver the best possible technology with an increasingly integrated and seamless experience for developers and end users. The goal from here is evolving NEAR to be more than just a layer-one blockchain: it will become a global blockchain operating system. It’s still early days, but building is underway and the vision is clear. NEAR is Now NEAR is the place where mainstream adoption of the open web will happen. Soon, anyone in the world—app users, developers, founders, creators—will be able to create without limits. Thank you for reading our NEAR 2023 Strategy Blog Post and/or participating in the NEAR Go Forward Strategy Twitter AMA! If you have questions or comments we would love to hear them!
With MeshFlux, Multimedia Art and Gaming Explore Blockchain Technology COMMUNITY August 10, 2023 The worlds of art and blockchain are no strangers. On NEAR, art can be found on apps like Mintbase, Paras, and many other ecosystem projects. With the MeshFlux project, however, Turkish artist and designer Ufuk Barış Mutlu shows a clear path to how physical artworks can be deeply integrated with the blockchain. With funding from the NEAR ecosystem, Mutlu created MeshFlux — a series of interactive sculptures that highlight one of the fundamental aspects of blockchain technology — the distinction between centralized, decentralized, and distributed networks. To achieve this goal, Mutlu created a series of three interactive sculptures that deliver the experience of these systems’ characteristics through simple gamification. Mutlu recently exhibited MeshFlux at a couple of events. MeshFlux appeared at virtual art platform’s Monoco.io’s physical gallery in Istanbul from May 18 to June 17, 2023, then at Sónar+D Barcelona — the music festival’s digital trade show, from June 15 to June 17, 2023. Making blockchain art accessible to the masses Although crypto natives and blockchain curious might understand these concepts, Mutlu wanted to make his physical artworks that explore the blockchain comprehensible to the average person. To that end, he created physical artwork that explains blockchain by visualizing and gamifying it. “The project’s output consists of three interactive sculptures machined out of aluminum, which are sized similarly to an iPad,” said Mutlu. “The dynamics of the interaction are based on the conventional maze game, where the paths of the mazes represent three different network systems: centralized, decentralized, and distributed networks.” All three maze paths are mapped according to Paul Baran’s original work published in 1964. Steel bearing balls inside the sculptures represent data packets in the network. The usage of multiple bearing balls distinguishes this sculpture from a conventional maze game and visualizes a multi-user network schematic. “I narrowed down my approach to the fundamental principles of blockchain, specifically network models,” Mutlu explained. “To achieve this, I created three maze games using network models as the foundation. These maze games are often associated with children and were constructed using premium and industrial materials to strike a balance between play and serious tech.” Using computers to industrially mill materials — aluminum, in this case — requires designing a digital 3D model, programming the milling machine (referred to as CAM), securing the material into the CNC machine, and using automated cutting tools (CNC) to precisely shape the aluminum block according to the design. “The process allows for accurate and efficient production of objects with complex shapes” explains Mutlu. MeshFlux: NFT meets 3D-printed sculpture Since his focus lies in physical objects, Mutlu wanted to offer the same sculpture as a 3D-printable file functioning as an NFT. His plan was to leverage all the advantages of blockchain technology through the creation of an NFT, while ensuring its potential to be transformed into a physical and tactile artwork. This would, he figured, satisfy the collector’s desire for touch and possession. With part of his NEAR ecosystem grant, Mutlu shot a documentary that explores the process of creating MeshFlux’s physical and digital (blockchain) aspects. NFT versions of MeshFlux are currently available, and Mutlu is working on integrating them with NEAR. Follow Ufuk Barış Mutlu on Instagram.
--- id: onboarding-checklist title: Project Onboarding Checklist sidebar_label: Project Onboarding Checklist sidebar_position: 4 --- # NEAR Project Onboarding Checklist :::info on this page * Communities to join when you start * Support networks while you are building * Networking and Marketing support once your project is built out ::: --- ![](https://s3.us-east-2.amazonaws.com/nearhorizon.assets/wiki/onboard-checklist_banner.png) 👋 Greetings! Welcome to the NEAR ecosystem, it's very exciting to have you here! This invaluable project onboarding checklist has been curated to guide you seamlessly through your journey of building on NEAR. This document includes a treasure trove of critical information and resources, designed not only to integrate you into the vibrant NEAR ecosystem, but to also ensure your project is successful on NEAR! Let this checklist serve as your compass while you build out your project on NEAR. With it, you can confidently navigate the exciting landscape of NEAR, knowing you have great tools and resources at your disposal to build, thrive, and make your mark within the NEAR ecosystem! The checklist is divided into 3 parts : <ul> <li><a href="#-to-start-your-journey">🏁 To Start Your Journey</a></li> <li><a href="#️-while-you-are-building">⚒️ While you are building</a></li> <li><a href="#-once-your-project-is-built-out">🚀 Once your project is built out</a></li> </ul> ## 🏁 To Start Your Journey || <center><h3><strong>Task</strong></h3></center> | <h3><strong>Purpose</strong></h3> | | | :--- | :--- | :----: | | <input type="checkbox" className="onboardCheck" name=""/> |<center><strong>Join the NEAR community & get involved: </strong></center> <br/> <ul><li><a href="https://discord.gg/qmRAacr6ze">NEAR Discord</a> \| <a href="https://t.me/cryptonear">Telegram</a> \| <a href="https://www.reddit.com/r/nearprotocol/">Reddit</a></li><li><a href="https://near.social/">NEAR Social</a></li><li><a href="https://gov.near.org/">NEAR Forum</a></li><li>Twitter:<ul><li>Official <a href="https://twitter.com/nearprotocol">@NEARProtocol</a>, <a href="https://twitter.com/NEARFoundation">@NEARFoundation </a></li><li>Ecosystem news, insights, data : <a href="https://twitter.com/NEARWEEK">@NEARWEEK</a>, <a href="https://twitter.com/near_insider">@NEAR_Insider</a>, etc.</li><ul><li>Follow the growing list of <a href="https://twitter.com/i/lists/1590678464478208001">NEAR news twitter accounts</a>!</li></ul></ul></li></ul>| Stay up to date on the latest news, insights, and to get to know the community better. | | <input type="checkbox" className="onboardCheck" name=""/> | **Create a profile for your project on <a href="https://near.org/horizon">NEAR Horizon</a>, and explore other projects building in the NEAR Ecosystem!** | Ensure your project is on NEAR’s ecosystem dashboard for discoverability by community, as well as VCs/backers and other founders. Know the ecosystem better and find potential collaborators! | | <input type="checkbox" className="onboardCheck" name=""/> | **Learn about NEAR’s Blockchain Operating System, what’s being built on BOS & how to build on BOS:** <br/><a href="https://youtu.be/NGX4_ZlzFzs">BOS Overview</a> \| <a href="https://youtu.be/ImKMvoD0W14">Projects Building on BOS</a> \| <a href="https://bos.gg/#/">EVM Decentralised Frontends</a> \| <a href="https://docs.near.org/bos">BOS Dev Docs</a> | NEAR's Blockchain Operating System (BOS) is an industry-first platform that serves as a common layer for deploying, browsing and discovering open web experiences, compatible with any blockchain | | <input type="checkbox" className="onboardCheck" name=""/> | **Join relevant NEAR [Builder Groups](https://www.nearbuilders.com/) as well as [NEAR Communities](https://wiki.near.org/ecosystem/communities)**| Get involved in discussions around the vertical you're building in, and also Engage with a NEAR community around you and bond with projects that can partner with you! | <br/> ## ⚒️ While you are building || <center><h3><strong>Task</strong></h3></center> | <h3><strong>Purpose</strong></h3> | | | :--- | :--- | :----: | | <input type="checkbox" className="onboardCheck" name=""/> | **Reference the [NEAR Wiki](https://wiki.near.org/) for resources around Legal, Growth & Marketing, Tools/Infrastructure, and more** | NEAR Wiki provides general support | | <input type="checkbox" className="onboardCheck" name=""/> | **Check out some previous and upcoming workshops on how to build on NEAR and what tools are available - [nearworkshops.com](https://www.nearworkshops.com/)** | Learn in real time how to build on NEAR and/or integrate infrastructure & tools available on NEAR| | <input type="checkbox" className="onboardCheck" name=""/> | **Submit major roadmap dates to [NEARWEEK’s calendar](https://nearweek.com/calendar)** | Let the ecosystem know what's coming up, and to gain visibility | | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong>Technical Support</strong></center> <br/><ul><li><a href="https://near.org/developers/get-help/office-hours/">Developer Office Hours</a></li><li><a href="https://wiki.near.org/development/tech-resources">Technical Resources</a></li><li><a href="https://docs.near.org/">Documentation</a></li></ul>| Provide resources for projects that require technical support | | <input type="checkbox" className="onboardCheck" name=""/> | **Refer to NEAR’s [Branding Toolkit](https://near.org/brand) for any posts & content you create/put out including NEAR. <span style={{fontSize: 'larger'}}>Go crazy with the BuiltOnNEAR badge!</span>** | Ensure you are using the most up to date logos & graphics | | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong>Marketing / Community / Events</strong></center><br/> <ul><li><a href="https://wiki.near.org/support/growth">Marketing Resources Wiki Page</a></li><li><a href="https://drive.google.com/file/d/1NsMDzKxFHoKopgEOpf2JGVXI8NzvDrsc/view">NEAR Ecosystem Marketing request</a> form</li><li><a href="https://4efdmh2cgdi.typeform.com/NEARWEEK-event?typeform-source=nearweek.com">Project Event/Milestone Calendar</a> form</li><li><a href="https://wiki.near.org/support/growth#gtmevent-funding">Ecosystem Event Grants Application</a> process</li></ul>| Resources for projects to leverage for marketing & awareness | <br/> ## 🚀 Once you have completed your project || <center><h3><strong>Task</strong></h3></center> | <h3><strong>Purpose</strong></h3> | | | :--- | :--- | :----: | | <input type="checkbox" className="onboardCheck" name=""/> |<center><strong>Shout out & discuss your project in the NEAR community </strong></center><br/><ul><li><a href="https://discord.gg/qmRAacr6ze">NEAR Discord</a> \| <a href="https://t.me/cryptonear">Telegram</a> \| <a href="https://www.reddit.com/r/nearprotocol/">Reddit</a></li><li><a href="https://near.social/">NEAR Social</a></li><li><a href="https://gov.near.org/">NEAR Forum</a></li></ul>|Give a shout-out about your project, get the community engaged, and gain traction | | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong>Ensure your project profile is updated and complete on NEAR Horizon</strong></center> | Ensure VCs, other founders, and community | | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong>Get some tutorials / learn2earn campaigns up!</strong></center><br/><ul><li><a href="https://learnnear.club/">LearnNEARclub</a></li><li><a href="https://app.lazyfi.gg/">LazyFi</a></li></ul>| Explore education platforms on NEAR and get some of your own content on them for users to learn about your project in an engaging way | | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong><a href="https://airtable.com/shrvxDwvMOaBKXzJB">Submit interest</a> to participate in Pitch Events </strong></center> | Let others know about your project; be prepared to connect with VCs| | <input type="checkbox" className="onboardCheck" name=""/> | <center><strong>Discover talent to fill open roles and needs within your team</strong></center><br/><ul><li><a href="https://careers.near.org/jobs">NEAR Ecosystem careers portal</a></li><li><a href="https://beexperience.io/">Beexperience</a></li></ul>| Hire the right people to expand your team and project. |
LiNEAR Protocol Introduces Omnichain Liquid Restaking to Advance NEAR’s Chain Abstraction COMMUNITY March 27, 2024 LiNEAR, the leading DeFi protocol on NEAR with the highest TVL, is planning to enhance the security of NEAR’s Chain Abstracted network through restaking, ensuring a secure future for a chain-agnostic and chain-abstracted Web3 experience. Established by early core contributors to NEAR, LiNEAR has made significant contributions to advancing the ecosystem, beginning with its innovative liquid staking features, notably the Automatic Validator Optimization Algorithm. This algorithm greatly improves the security and decentralization of the NEAR network by dynamically reallocating stakes across as many as 200 active nodes. LiNEAR’s vision has always been enabling easier participation in the decentralized web. With the NEAR ecosystem’s commitment to advancing Chain Abstraction by removing the complexities of blockchain technology for users, LiNEAR is also expanding its offering and focusing on restaking to eliminate barriers to entry for the multichain ecosystem. LiNEAR Protocol will be providing a robust security model through omnichain liquid restaking, avoiding the pitfalls of centralized and permissioned solutions in pursuit of an improved Web3 user experience. Restaking can potentially secure Chain Abstraction infrastructures for three key reasons: it offers instant security by leveraging existing blockchain security mechanisms; ensures capital efficiency by allowing nodes and stakers of a blockchain to participate with minimal additional capital; and promotes base layer alignment, closely bonding the networks with the blockchains which they serve. NEAR‘s Chain Abstraction comprises social authentication, account aggregation, Chain Signatures, and the multichain intent relayer. These elements combine to allow users to transact across various blockchains using a single account and interface, without the need to understand the underlying infrastructure or switch networks. To realize this vision, two new decentralized infrastructures are required: the Chain Signatures MPC network and the Multichain Gas Relayer. The Chain Signatures MPC network functions as a decentralized signer of users’ NEAR accounts, controlling all other accounts on different blockchains. The Multichain Gas Relayer consists of off-chain relayers that listen to and compete to execute users’ intents on different chains. Both infrastructures operate externally to any existing blockchain, including NEAR. LiNEAR’s liquid restaking solution aims to secure the Chain Signatures MPC network, mitigating the risks of centralization. Similarly, the Multichain Gas Relayer would be able to operate in a trustless manner with restaked verification, removing embedded trust assumptions and enabling users to confidently delegate executions to the relayer network. This entire security framework can be supported by $NEAR and $LiNEAR, and other assets such as $SOL, $BTC, and more in the future, ensuring alignment with different blockchains connected through Chain Abstraction. NEAR community members interested in restaking can get started on LiNEAR and help move the network towards a more secure and easy-to-use Web3 world. About LiNEAR LiNEAR Protocol is an innovative omnichain liquidity staking/restaking platform and the leading DeFi protocol on NEAR. It pioneered revolutionary features such as automatic validator optimization, which significantly decentralizes and secures the network by allowing users to re-delegate to 200+ validators. LiNEAR offers seamless multichain restaking across multiple networks, such as NEAR, Ethereum, Bitcoin, Solana, and more, ensuring a secure future for a chain-agnostic and chain-abstracted Web3 experience.
Case Study: OnMachina’s Jonathan Bryce on Building Decentralized Storage for an Open Web NEAR FOUNDATION June 5, 2023 NEAR is a home to a number of amazing apps and projects. These developers, founders, and entrepreneurs are using NEAR to effortlessly create and distribute innovative decentralized apps, while helping build a more open web — free from centralized platforms. The NEAR Case Studies content vertical made a return recently with a case study featuring Pagoda Chief Product Officer Alex Chiocchi, talking about the BOS. For the next entry in the NEAR Case Study series, OnMachina co-founder Jonathan Bryce talks about building decentralized infrastructure on NEAR — specifically, developing decentralized storage for an open web.
NEAR Token Supply and Distribution COMMUNITY June 19, 2020 Last updated: 20201016 (see change log section at the end) NEAR exists to enable community-driven innovation to benefit people around the world. The platform and its surrounding ecosystem rely on the efforts of a broad community of participants, builders, validators, delegators and more to succeed. This post will help you understand how the core facilitating component of the protocol, the NEAR token, is distributed to support the launch of this ecosystem. Using this Post The intent of this post is to give you a clear picture of the initial distribution of tokens for the NEAR protocol. Wherever possible, we’ll use charts and tables to explain, but we’ll also contextualize them with the thinking behind it all. Data is beautiful 🙂 Each section should be self-explanatory but there are some methodological notes at the end. The charts will generally present the most conservative case when there is a choice. The accuracy or certainty of numbers may vary by category, as noted below. Changes to the post will be noted in the Changelog section at the end so it is clear how up-to-date it is and what has changed between versions. About NEAR For those who aren’t familiar, NEAR is a decentralized application platform that secures high value assets like money and identity while providing the performance necessary to make them useful for everyday people. It is built atop a brand new public, proof-of-stake blockchain which uses a novel consensus mechanism called Doomslug and a new sharding approach called Nightshade which splits the network into multiple pieces so that the computation is done in parallel and there is no theoretical limit on capacity. NEAR’s contract-based account model provides the flexibility that other chains only get from second layer components, allowing NEAR to consistently provide better native usability for developers, validators and end-users. NEAR launched its genesis (Phase 0) on April 22, 2020, became community-operated (Phase I) on September 24, 2020, and passed the decentralized vote to enable transfers on October 13, 2020 (Phase II). It is now fully live. Key Facts The following will help you better contextualize the sections below: Genesis Tokens: There were 1 billion NEAR tokens created at genesis. They are being allocated to individuals and organizations on an ongoing basis during the rollout of MainNet. Inflation, transfers and unlocking did not begin until the final phase of MainNet (“Phase II”), which started on October 13, 2020. All charts in this post begin on the date when transfers were enabled (which will be determined by the community). See below for circulating supply. Contract-Based Accounts: NEAR uses a smart-contract-based account model, meaning that each account is actually a smart contract as well. Account names are thus human-readable (eg `foobar.near`) and contain any number of uniquely-permissioned keys. Thus it’s possible to have staking keys separate from transfer keys. Transfer Restriction: Until the network officially reached the Community-Governed MainNet phase (aka “Phase II”), the accounts of token recipients were prevented from directly transferring tokens (but they could still be used to pay for gas or storage, staked, delegated, used to deploy apps, etc). Lockups and Unlocking: The vast majority of tokens are subject to linearly releasing lockups. These lockups are implemented as contract-based locks atop various accounts. Lockups are generally implemented in a linear, per-block fashion instead of in monthly chunks, though some might be implemented that way as well. Lockups begin unlocking when the transition to the final Community-Governed MainNet phase occurs (aka “Phase II”). We use the term “linear lockup” or “linear release” where some other projects use the term “vesting”, so you may know it by that name. Staking and Delegating while Locked: NEAR is a Proof of Stake network where validating nodes put at stake either their own tokens or tokens which have been “delegated” to them by other holders. The number of validating nodes depends on the number of shards in the network but will start at 100. Because of NEAR’s account model, tokens can be staked or delegated even while they are locked. Foundation Delegation: The Foundation is only actively running nodes during the initial phase of the network rollout. Thereafter, as noted in this post, it will shut down its nodes and be limited to delegation. It will only delegate tokens in its endowment. New Issuance and Economics: As per the Economics Blog Post and Economics Paper, 5% of additional supply is issued each year to support the network as epoch rewards, of which 90% goes to validators (4.5% total) and 10% to the protocol treasury (0.5% total). 30% of transaction fees are rebated to the contracts touched by the transaction and 70% are burned. Because of this burning, at high levels of transaction throughput the network could become deflationary. In this post, we assume the pessimistic case of 0 fees. New supply creation does not begin until the transition to the final Community-Governed MainNet phase occurs. Overall Allocation and Supply Schedule There were 1,000,000,000 NEAR tokens created at Genesis on April 22, 2020. This will be allocated in the following way, where each category is described in greater detail in the following sections: “Circulating Supply” is every token that isn’t subject to a lockup at a particular time. The vast majority of the initial supply of NEAR tokens is subject to long-term lockups. So the initial circulating supply is made up of provisions for a community sale, a future distribution activity, a small handful of community contracts and the Foundation’s liquid endowment. All supply that existed at genesis is unlocked by month 60. The chart below shows the increase in circulating supply as tokens unlock and new tokens are minted. The dotted line shows the total supply as it increases due to new issuance (but ignores any burning that would be due to fees). This and all charts begin on the date that transfer restrictions are lifted (“Phase II”): The table below shows the circulating supply for commonly used date milestones: The following chart provides more detail on the components of the circulating supply as it grows over time. Each category is explained in further detail in the following sections. Note again that all genesis tokens are unlocked by the end of month 60. Because the network is secured through running Proof-of-Stake validating nodes, it is relevant to discuss how much stake can participate in validation (directly) or delegation to validators (indirectly). Distribution-oriented categories (like “Community Distribution”) will only participate in delegation when the tokens are received by their intended recipient, so these numbers represent the maximum amount of stake that would theoretically participate in validation. In reality, it will certainly be less. Category Detail Each category is explained in more detail below. Community Grants and Programs A large portion of tokens is devoted to grants and programs which fund community efforts, community projects and community-built technical components. This spans everything from education to events to direct deployment into venture-style funding for projects. A small provision exists for tokens that can be given away or sold in the future. Because these efforts are decidedly long-term in nature, the tokens are released over 60 months. Core Team In 2018 when NEAR built its early momentum, blockchain projects were already imploding with alarming frequency, in part because they set the wrong incentives for their teammates. Some didn’t launch at all and others were abandoned shortly after they did. NEAR is being built by one of the strongest teams in the world, which is spread across multiple continents and many backgrounds. Core team members have been important in the early success of the protocol and they are incentivized to remain active with its development for a long time afterward — every single member has the identical 4-year lockup with a 12-month cliff after launch, which you can see in the chart. Prior Backers Most project funding occurred during a severe crypto bear market and during a period where the crowdsales of the past were no longer feasible. The team’s philosophy when sourcing early backers to support the project was simple: Backers must be long-term oriented. Backers must add value to both the project (eg via actively supporting the team) and the network (eg via validating or delegating stake). Rounds should be structured clearly and transparently so every member has the opportunity to get the same pricing and lockup terms in that round. No single player should control an undue amount of stake Despite the simplicity of these requirements, we were forced to turn away many prospective backers who wanted other incentives. For the record, very few capital allocators are used to being told to write a *smaller* check, but it means that no single backer holds above 3.5% of the initial supply and few have above 1%. Every prior purchaser has a lockup of between 12 and 36 months from transfers unlocking, with the majority at 24 months. Because the first purchase occurred in 2017, some backers will wait over 3 years between their initial purchase and any liquidity and over 5 years to achieve full liquidity. There’s a difference between the larger, typically more institutional, backers and smaller, typically more independent, backers. A well balanced ecosystem has an appropriate number of both. We capped the total contributions from larger backers while encouraging those from smaller backers. To ensure that small participants could still potentially participate in validation during the network’s early stages, the threshold between the two was set at holding 5M tokens at launch. Prior Fundraising NEAR raised from backers in several tranches which are explained below. Early fundraising was done via convertible notes, of which almost all have since converted to tokens. All are expected to fully convert to tokens. These linear lockups and quantities (which, again, release linearly during their time period) can be visualized in the following ways: Community Sale The network at scale will be fully community-driven and that requires making sure the community has the tokens they need. The Community Sale occurred in August 2020 in multiple portions due to some technical difficulties and a desire to improve participation. The total amount that ended up being distributed during the sale period was just over 120M tokens. A maximum of 25M of these tokens were unlocked and the remainder were subject to 12- or 24-month linear lockups. Early Ecosystem It takes a substantial group of people to put together all the pieces which have made the network successful so far. Early Ecosystem includes all of the grants for those who have participated in the network ecosystem thus far, whether as part of the Beta Program to build early apps, building analytics tooling, supporting the incentivized testnet and so on. Lockups for these efforts are typically 6- or 12-months, though a handful have been shorter or longer. It also includes allocations for several programs that haven’t launched yet. One of these unannounced programs contains 30M tokens on a 6-month linear lockup. The largest portion in this category is a provision for a currently-unannounced distribution effort which could involve up to 80M unlocked tokens. For details, please wait for the announcement of this program. Foundation Endowment The NEAR Foundation stood up the initial network nodes and spun them down to focus on coordinating the governance of the ecosystem, funding projects and kicking off remaining distribution activities. The Endowment represents a pool of tokens which are meant to support the Foundation’s operations in the long term and which might be deployed in a wide range of ways. This endowment is split into 2 pieces. The first half, which is not locked up, will likely be deployed across multiple strategies to help ensure the network operates smoothly during its early phases. The second half is subject to a 24 month linear lockup since it is not expected to be accessed during the early days beyond delegation to support decentralization. Both tranches are meant to be deployed in ways which preserve principle wherever possible to ensure long-term availability rather than systematically sold for short-term capital. As a reminder, the Endowment may not be used to run validating nodes directly but could be delegated, as per the previously linked post. As part of the initial rollout, the Foundation accounts will be setting up the lockups and accounts for the rest of holders. Some tokens may still be in these accounts during rollout if recipients are delayed in setting up their respective custody solutions. Operations Grants The technical architecture of the system benefits from the expertise of world-class developers for continuous operation and ongoing development. These efforts will be funded by community-overseen grants that focus on supporting the people who maintain, operate and develop the system itself. These grants are expected to be first initiated during the second half of 2020 and early 2021. The tokens set aside for this purpose are subject to long-term 60-month linear lockups to ensure they are clearly allocated to long-term projects. New Issuance New Issuance is not a factor in the genesis block but represents, at its maximum, a 5% growth rate in the supply of tokens. As always, note that this percentage does not factor in the burning of transaction and storage fees since they cannot be easily estimated at this point. Observed vs Circulating Supply Now that Phase II has happened and transfers are enabled, the team is working to help create more transparency in the circulating supply. As the first part of this, these are some known variations which will occur between the intended circulating supply (as written in this post) and what might be observable on-chain, particularly during early phases of the network: Unclaimed tokens: The biggest variation in circulating supply will be due to unclaimed tokens. These are kept in unlocked accounts until they are claimed (because otherwise they could be claimed), after which almost all of them will have their intended lockups applied. As of the date of Phase II, this number was over 300M tokens. Accounting shifts: Similar to the Unclaimed Tokens, during the earliest days, some accounts which are reserved (particularly for Early Ecosystem) are still having lockups applied. There will also be changes in the delegation from the NF during the first few weeks after Phase II while tokens are consolidated into their intended accounts. All of these activities are intended to help make reality reflect the descriptions and charts above. Some buckets may also have short-term vesting provisions to allow for reclamation during the first few days after locking in case of mistakes. Account creation tokens: Whenever an account is created (including during the claims process), it receives some initial tokens to cover the storage costs. For complex accounts, that could be as high as 40 tokens. This is not accounted for above but these will appear to be unlocked. Inflation lag: There is approximately a 1-week lag between the date when transfers were enabled on the network (Phase II) and when the upgrade will occur to enable inflation on the network. This will result in some of the New Issuance assumptions above being slightly off. This isn’t likely to be significant enough to create major disturbances. As the analytics tools become stronger after launch and tokens are successfully claimed, you can expect convergence between observed and intended categories. Conclusion You can expect additional information over the next several weeks about the project and its activities as the rollout of MainNet continues and distribution begins ramping up. Regardless of your background or intent, there is a way to get involved: Find your place among the teams that drive this forward at https://pages.near.org/careers or get involved directly as a Contributor or Guild Leader at https://pages.near.org/community. If you are a developer, you can jump into the code at https://docs.near.org and if you are already a founder, you can find support for your journey from the Open Web Collective, a platform-agnostic founder community, at https://openwebcollective.com. Finally, if you are interested in analytics and exploring these numbers (or if you find errors/inconsistencies), please feel free to create tools or views and let us know at [email protected]. Everyone benefits from better transparency and analytics! Some of these tools may also be eligible for grants. Appendix A: Methodological Notes Time buckets should be read as “end of month” unless otherwise noted, meaning the bucket for “month 12” includes the initial balance on the first day of that month plus any change within that month. “Month 0” is the only bucket which is typically used to represent genesis without any additional time. The modeling of token releases to represent inflation uses a more simplified average than actual formulas and does not take into account the number of days in a month. Amounts are intended to be accurate but may still contain imprecisions and are subject to change. Appendix B: Change Log 20201016 Many updates. Overall, the expected circulating supply was reduced at genesis and is roughly the same at other major milestones. Updated overall circulating supply charts to reflect changes. Updated the community sale category to reflect reality and shifts due to the additional sale window. This meant a reduction in other categories, particularly the Team (reduced from ~145M to ~140M) and Early Ecosystem (reduced from ~133M to ~117M, including from the unlocked allocation). Updated Early Ecosystem explanation to reflect reduction in unlocked token bucket from 100M to 80M. Minor shifts of ~1-2M each in Operations and Community Grants categories. Added a section explaining potential shifts in observed versus planned circulating supply post-phase-II. Updated copy and links to reflect latest network status. Updated community sale category to reflect actual sale numbers. Added note in Foundation about delegation. 20200811 Fixed legacy mistake in circulating supply in the “Genesis Tokens” section of “About NEAR” to reflect the proper supply. Clarified language around the circulating supply 20200810 Added and separated out a Community Sale category. This has basically the same character as the Small Backers category (where these were located previously) but, in the interest of clarity, it is now separate. It has also been increased to reflect a significantly higher possibility of demand (100M) than originally expected (15M). The increase in token expectation has been shifted from the Community Distribution bucket, which included post-Phase-II sales previously (and are now being optionally allocated to a pre-Phase-II sale to the community). This results in some change in the circulating supply due to shorter lockups in the Community Sale (0, 12 or 24 months) versus the previous Community Distribution bucket (60 months). To reflect the maximum possible allocation of unlocked tokens, initial circulating supply has been increased by 17.5M tokens versus the previous estimate. Updated Backers section to reflect this. Combined remaining Community Distribution amounts into the Community Grants, Programs and Distribution category and updated category description to reflect this. Minor clarifications around the word “Lockup” since this has confused people. In this post, we use “Linear Lockup” or “Linear Release” the way that many other people have used “Vesting” historically. We believe that “Lockup” is still the correct term because, technically, “vesting” items are not yours until they vest whereas locked tokens belong to you from the beginning (they are just locked from being transferred). Updated charts and added horizontal axis description “months since transfers are enabled”. Colors have changed. Fixed title on the Prior Fundraising table. Noted the 30M 6-month program in Early Ecosystem. Minor clarity around Phase II in the intro. 20200724: Updated to reflect the potential for 100M possibly liquid tokens to be available as part of a currently-unannounced program in the Early Ecosystem category, which readjusted amounts available to the post-launch Community Grants and Community Distribution categories. Updated Early Ecosystem balances to reflect that Stake Wars allocations will be unlocked. Updated language on Future Fundraises slightly for clarity. Updated all remaining charts and tables to reflect changes in circulating supply.
--- id: what-is title: What is a Smart Contract? sidebar_label: What is a Contract? --- Smart contracts are pieces of **executable code** that live in a NEAR account. They can **store data**, **perform transactions** in the account’s name, and **expose methods** so other accounts can interact with them. ![img](/docs/assets/welcome-pages/contracts-landing.png) Do not worry if you don't know how smart-contract blockchains work. As a developer, it is sufficient to understand that NEAR smart-contracts: 1. Have **limited** computational resources. 2. Interact with other contracts in an **asynchronous** way. 3. Deal with **real money**, for which security must be a top concern. :::info HTTP Requests and Smart Contracts Smart contracts **cannot perform HTTP requests**, meaning they can't fetch data from outside the NEAR network. ::: --- ## Where do contracts live? Smart Contracts are deployed into [**NEAR accounts**](../../1.concepts/protocol/account-model.md). Any NEAR account can hold a contract, needing to pay for the **contract's code** and the **data it stores**. Once in an account, anyone can interact with the contract. Thanks to the underlying network structure, executing code from a contract is both **fast** (avg. 1.4s finality) and **cheap**. Moreover, **read-only** operations are **free for everyone**. :::tip Storing 100kb costs 1Ⓝ, so deploying a contract generally costs only a few $NEARs. ::: --- ## Development flow Just like any piece of software, smart contracts have a development flow - starting with its creation and ending with monitoring it, all of which we cover in our documentation. ![img](/docs/assets/welcome-pages/contract-lifecycle.png) "build/building-smart-contracts/testing/introduction", The development flow can be summarized as follows: - [**Scaffold**](./quickstart.md): The simplest way to create a project is by starting from a template. - [**Build**](./anatomy/anatomy.md): Write a contract using Rust or Javascript. - [**Test**](./testing/introduction.md): Our Sandbox enables to simulate interactions with one or multiple contracts in a realistic environment. - [**Deploy**](./release/deploy.md): After making sure the contract is secure, developers can deploy the contract into their accounts. - [**Use**](https://mynearwallet.com): Any user can interact with the contract through their NEAR Wallet. - [**Monitor**](../6.data-infrastructure/what-is.md): The contract's activity can be monitored through simple APIs. #### Supported Languages During the whole cycle, developers can choose between [JavaScript](https://www.learn-js.org/) and [Rust](https://www.rust-lang.org/), allowing them to use their favorite language at each step of their journey. <details> <summary> Other languages </summary> Theoretically, you can use any language that compiles to Wasm for developing NEAR smart contract. However, in order to have a user-friendly experience we would need to provide a library that wraps around low-level runtime APIs, while also offering other high-level functionalities. We envision that in the future, more languages will be supported and the support will be done through the effort from the wider community, not just NEAR alone. </details> --- ## Contract primitives Contract primitives such as FT, NFT, and DAOs are fundamental building blocks that can be combined to create awesome user experiences such as reward tokens, decision-making tools, and marketplaces. :::tip Check our section on [primitives](../5.primitives/what-is.md) to learn more about them :::
--- description: This is a guide to DAO Governance with Astro on NEAR. title: DAO Governance --- # DAO Governance :::info on this page * This guide provides information on the different features available to DAOs built with Astro on NEAR, such as custom tokens, NFTs, and bounties. * To create a voting token, a DAO can either create a new token, adopt a pre-existing Token Farm token, or adopt the NEAR native token. * Bounties are an important part of DAO governance on Astro. DAOs can post bounties for tasks and other pieces of work, and contributors can claim and complete bounties for rewards. ::: Before we discuss DAO governance, it might be beneficial if you either join a DAO, or [launch one](./how-to-launch-a-dao.md). This guide covers the different features available to DAOs built with Astro on NEAR, including voting, custom tokens, NFTs, and other exciting features. ## Voting Tokens (Creation) On the overview of your page you can begin the process of creating a voting token by hitting ‘Create a token for voting’. 1. On the ‘Enable voting by token’ page, hit ‘start’ * **Note:** Once a DAO adopts a token for voting, that token cannot be changed 2. Select an option from the three displayed: 1. Create a new token * A new token will be created on the NEAR blockchain for voting purposes 2. Adopt a Token Farm token * Utilize a pre-existing token - anyone who owns this token can stake it and use it to vote within the DAO 3. Adopt the NEAR native token * Anyone who holds NEAR will be able to vote within the DAO ![Astro DAO](@site/static/img/astrodao4.png) ### Creating a New Token If you’re creating a new token for governance within your DAO then you’ll need to fill out the details: 1. Select ‘Create a new token’ 2. Enter the details of your voting token: 1. Token name 2. Token symbol * This is the token ticker, e.g. NEAR = NEAR Token 3. Total supply of the token 4. Upload an image for your token icon 5. Enter the account for where the tokens will be sent to * This will typically be your DAO account 3. Hit ‘Next’ and confirm the details and you’re all set The DAO can then distribute voting tokens to members accordingly after the creation of the token. ![Astro DAO](@site/static/img/astrodao5.png) ### Adopting a Token Farm Token 1. Select ‘Adopt a Token Farm token’ 2. Select the token from the drop-down list 3. Hit ‘Next’ and confirm the details 4. Select ‘Propose’ on the final screen Note: Once you’ve selected a token for governance, this cannot be changed&#x20; ![Astro DAO](@site/static/img/astrodao6.png) ### Adopting the NEAR Native Token 1. Hit ‘Adopt the NEAR native token’ 2. Select ‘Propose’ Anyone with NEAR will be able to vote for proposals within this DAO. ![Astro DAO](@site/static/img/astrodao7.png) ## Tasks Astro is endowed with considerable flexibility within the interface itself. DAOs can create bounties, host polls, and interact with the NEAR ecosystem directly through function calls under the ‘Plugins’ section ### Bounties DAOs are able to post bounties which are, in essence, projects, tasks, and other pieces of work the DAO wants to complete. Each bounty will come with a specified reward which, upon successful completion of the bounty, will be received by the claimant.&#x20; Bounties can range in complexity and length from meme/content creation to the refactoring of code repositories. ![Astro DAO](@site/static/img/astrodao8.png) ### Creating a Bounty DAOs looking to post bounties to the wider NEAR Community can do so in a few clicks: 1. In the Bounties section of Astro hit ‘Create new bounty’ 2. Select the token type which the reward will consist of and the amount 3. Enter the details of the bounty 4. Add an external URL link&#x20; * This can be a link to the NEAR Governance Forum or somewhere which delivers more details on the bounty 5. Select the number of times the bounty can be claimed 6. Enter the amount of time from claiming the bounty to completion 7. Hit ‘Propose’ ![Astro DAO](@site/static/img/astrodao9.png) ### Claiming a Bounty Completing bounties can be a rewarding endeavor that contributes to the growth of the NEAR Ecosystem and the growth of DAOs. If you’re a contributor, artist, or meme-master then there may well be a bounty out there for you to hunt.&#x20; When you’ve found a bounty you’d like to take onboard you can claim it and get started right away: 1. Identify the Bounty you’d like to take on board in the Bounties section of the DAOs Astro page 2. Hit ‘Claim’ 3. Make sure you’ve understood the requirements of the bounty and if you’re happy to take on the task to earn the reward hit ‘Claim’ and pay the bond * **Note:** If you fail to complete the bounty or your submission is rejected then you will lose your bond and it will be sent to the DAOs treasury 4. Good luck, and happy bounty hunting! ![Astro DAO](@site/static/img/astrodao10.png) You can un**-**claim a bounty within 2 days of claiming it in order to retrieve your bond. This is done through the same Bounties interface of Astro. Once your bounty is complete head back to the bounty which you claimed in Astro and hit ‘Complete bounty’. Fill in the details, including your payment address and the completed bounty, and hit ‘Propose’. This will then be sent to the DAO for review. If the bounty has been satisfied, the DAO will distribute funds to your specified payout address. ### Polls Polls are a simple way to gauge the opinions of the members of your DAO. You can ask any question and invite members to vote with a simply yes or no. Creating a poll is easy: ![Astro DAO](@site/static/img/astrodao11.png) 1. Head to the Polls section of Astro in your DAO 2. Click ‘Create new poll’ 3. Enter the question or statement to vote on 4. Add an external URL if applicable 5. Hit ‘Propose’ ![Astro DAO](@site/static/img/astrodao12.png) All done. Your poll is live! To participate in a poll simply select the poll and hit the green thumbs up or red thumbs down depending on which way you want to vote. ### Plugins The plugins section allows for NEAR function calls which enable your DAO to interact with applications in the NEAR ecosystem. This functionality is only restricted by the breadth of function calls on NEAR. Essentially, the DAO can interact with any other dApp just as a user would. ![Astro DAO](@site/static/img/astrodao13.png) ![Astro DAO](@site/static/img/astrodao14.png) ## Treasury DAOs built on Astro can retain a treasury of multiple assets, rather than being restricted to just NEAR. The treasury is divided into fungible tokens (tokens) and NFTs. From the Treasury section of Astro, users can send tokens to create a new payment proposal and find more details on a particular token in the treasury. The treasury balance is displayed in USD. ![Astro DAO](@site/static/img/astrodao15.png) ### Tokens Here the balance of all fungible tokens is displayed. DAOs can ‘hold’ any NEP141 asset within the treasury. ### NFTs Non fungible tokens are displayed in a gallery style and can be sent out in a similar manner to sending fungible tokens. ![Astro DAO](@site/static/img/astrodao16.png) ### Sending Tokens Tokens can be sent by a DAO to those who may have requested funding or a grant.&#x20; 1. In the ‘Tokens’ section of Astro hit ‘Send tokens’ 2. Fill out the details 1. The type of token, and number of tokens, to be sent 2. The address they’ll be sent to 3. Details of the payout 4. External URL if applicable 3. Hit ‘Propose’ This will create a proposal within Astro for governance participants to vote upon. If accepted, the funds will be sent to the specified payout address. ![Astro DAO](@site/static/img/astrodao17.png) ### Requesting Payouts If you’re external to the DAO and wish to request funding you can do so: Head to the DAO page on Astro 1. Hit ‘Create proposal’ 2. Select ‘Request a payout' 3. Fill out the details&#x20; 1. The type of token, and number of tokens, to be sent 2. The address they’ll be sent to 3. Details of the payout 4. External URL if applicable 4. Hit ‘Propose’ Governance participants will be invited to vote on the payout request. If approved, funds will be sent to the specified payout address. The bond will be returned to the proposer unless the proposal is marked as spam. ## Groups Within Astro, members of DAOs can be bundled into groups. With groups, DAOs have more flexibility in regards to governance due to the ability to restrict the voting on certain proposal types to members of specific groups. Additionally, groups serve as a way to clearly identify the roles of members within a DAO. ![Astro DAO](@site/static/img/astrodao18.png) ### How to Create a Group 1. Under the ‘Groups’ section of Astro hit ‘Add group’ 2. Enter the details for your proposed group: 1. Enter the group name 2. Add at least one member using their NEAR Account 3. Enter the details of the group 4. Add an external URL link if applicable 3. Hit ‘Propose’ After the proposal is accepted the group will be created and members can be added and removed at the will of the DAO. ![Astro DAO](@site/static/img/astrodao19.png) ### Adding Group Members 1. Under the ‘Groups’ section of Astro select the Group you want to add a member to and hit ‘Add member to this group’ 2. Enter the details 1. Enter the group you wish to add members to 2. Enter their NEAR account 3. Add details to the proposal 4. Include an external URL link if applicable 3. Hit ‘Propose’ If and when it’s approved by the DAO that member will be added to the specified group. ![Astro DAO](@site/static/img/astrodao20.png) ### Removing Group Members 1. Under the ‘Groups’ section of Astro select the Group you want to remove a member from 2. Hit the ‘-’ icon by the person logo in the top right of the user profile 3. Enter the details 1. Enter the group you wish to remove a member from 2. Enter their NEAR account 3. Add details to the proposal 4. Include an external URL link if applicable 4. Hit ‘Propose’ If and when it’s approved by the DAO that member will be removed from the specified group. ![Astro DAO](@site/static/img/astrodao21.png) ## Governance The governance process sits at the core of a DAO and is exemplified within Astro. With a variety of governance methods, DAOs are empowered to leverage their community and members to achieve their goals in a transparent manner. ### DAO Settings The setting section of your DAO in Astro includes details on: ![Astro DAO](@site/static/img/astrodao22.png) * Name & Purpose of the DAO * Links * Bonds & Deadlines * Flag Each of these are set during the DAO creation process but, through governance, can be amended through the DAO Settings section. ### Voting policy Here, Astro users can amend the voting policies for all aspects of the DAO. Proposals can be restricted to ensure that only members of the DAO who are in a certain group have voting rights.&#x20; ![Astro DAO](@site/static/img/astrodao23.png) DAOs can amend * Who can vote on proposals * The bond required to submit proposals * The threshold required for proposals to pass Now that you know what you can _DAO_, go ahead and explore!
Infura Brings its Leading ETH Dev Platform to NEAR Protocol COMMUNITY May 25, 2022 ConsenSys, the Ethereum incubator and enterprise company, has announced a partnership between the NEAR Protocol and Infura, the leading Ethereum development platform. This agreement paves the way for over 430,000 Infura developers to access a non-Ethereum Virtual Machine (EVM) compatible that is super simple to use, incredibly secure and infinitely scalable for the very first time. Integrating Infura and bringing Ethereum developers into the NEAR ecosystem is a significant step in fulfilling NEAR’s mission of creating an inclusive, self-sustainable, fully decentralized ecosystem with billions of users. It also illustrates the importance of the role that a multi-chain future will play in fulfilling that vision. Here’s everything you need to know about Infura’s partnership and integration with NEAR, and why developers expanding beyond non-EVM compatible chains will benefit everyone. Driving climate neutrality and scalability The Infura and NEAR integration has been in private beta for two months. Expanding beyond EVM compatible chains also marks a strategic shift by Infura, as it seeks to become a key connector in tomorrow’s multi-chain world. By integrating with NEAR, Infura also makes strides towards better sustainability and scalability for developers. The integration of Infura with NEAR will provide developers with one of the best options in terms of sustainability. The NEAR network and ecosystem are carbon-neutral with a minimal environmental footprint. Last year, South Pole, a leading climate advocay group,awarded NEAR the Climate Neutral Product Label. As for scalability, NEAR’s sharded blockchain enables a substantial increase in overall capacity. Infura developers will now have access to a network that can process at a rate of 1,000 transactions per second. And once NEAR’s Nightshade sharding is fully implemented, network scalability will be theoretically limitless, processing millions of transactions per second. Enhancing the developer experience Infura developers will now have access to the full development experience on NEAR, as well as the tools and resources at their disposal. This includes the ability to build decentralized applications using common programming languages such as Rust, AssemblyScript, and WebAssembly (WASM), and NEAR’s class-leading education platform. NEAR will also provide developers with a superior suite of learning resources including educational video series, as well as guided courses and workshops. While Infura developers are already using and accessing other networks like Ethereum, Polygon, and IPFS, they’ll find all the tools and resources needed to successfully build on NEAR. The ability to utilize Ethereum assets on NEAR, and vice versa, is another core benefit to developers of the integration. With NEAR’s Rainbow Bridge, assets can be seamlessly moved cross-chain in a fraud-proof manner with optimal security. Rainbow Bridge is a permissionless protocol that removes the necessity of trusting a single party to complete transactions. Infura developers can access the NEAR network today. The integration will accelerate the global adoption of Infura’s development tool suite, in addition to bringing more development talent and brainpower into the NEAR ecosystem.
Our Last Update | December 13th, 2019 COMMUNITY December 13, 2019 Friday the 13th, our last community update… Until next year! This is going to be our last community update in 2019. Our next update, on Friday the 27th, is going to be an end of the year special. Mark the date in your calendar! Now that we got that out, here is what we have been up to over the past weeks. We are heavily working on NEAR-specific content. Episode four and five of our ‘Lunch & Learn’ Series are out. For those of you, who are new to the episodes, it is basically a whiteboard series by Near on NEAR, explaining all aspects of the protocol. The fourth episode covers block finality in Nightshade, and in the fifth Evgeny takes a deep dive into runtime. If you have any comments, questions, or would like to request a topic, please get in touch on Discord. Becoming stable — Stake Wars has been up and running for almost a month now. Let’s give a huge shout out to everyone, who has been sticking around and filed issues on GitHub. Since our testnet being more stable, we are changing the structure of the program. We will be rewarding running nodes and test scenarios. Follow the validator and stake-wars-announcement channel on Discord as well as the GitHub repository for further updates. 31st episode of NEARProtocol’s Whiteboardseries is out! Watch it here. COMMUNITY UPDATE Similar to our engineering approach, we like to iterate on existing community programs, once we feel the need to change the scope, to make those more effective. We are currently working on two community programs that build on our learning and feedback from previous community efforts. More information is going to be announced soon! UPCOMING EVENTS 2020 is right around the corner and we are getting ready for the new year. I can only tell you this much, we are going to be back in Asia at the beginning of 2020. If you are in the Bay Area, come and say hi at our office, we love to chat about user experience. In the meantime, our “Blockchain Hack Night”, a bi-weekly meetup for developers and blockchain enthusiasts in the Bay Area, is taking a little winter break. We will be back on the 15th of January. Jan, one of our beta program participants, has been hosting several meetups in Prague. Check-out this photo from yesterday’s meetup. Jan’s meetup WRITING AND CONTENT Check-out the latest Chorus One Podcast episode that Felix recorded with Illia on NEAR staking economics. The 31st episode of our whiteboard series is out! Join Kevin Davis from Kava Labs and Illia for a deep dive on cross-chain DeFi, stablecoins, and Kava’s tech. Do you want to learn more about NEAR? Then head over to our “Lunch and Learn” Series on YouTube. We have just published the fifth episode, in which Evgeny explains runtime. Let’s celebrate the last days of 2019! Photo by NordWood Themes ENGINEERING UPDATES 132 PRs across 24 repos by 26 authors. Featured repos: nearcore, nearlib, near-fiddle-api, near-shell, near-explorer, near-bridge and near-wallet; Implementation of the fork choice rule in nearcore Network graph cache in nearcore Progressive slashing for double signs (as opposed to 100% slashing) in nearcore Adding staking for fishermen (to prevent challenges spam) in nearcore Light clients support in nearcore Computing light client blocks RPC endpoint that serves light clients Published v0.4.8 of nearcore Fix memory leaks in both ShardsManager and network routing table. Use stake as weight in finality gadget Store hash instead of actual values in trie nodes. V0.16.0 release of near-shell, including Allow easier formatting input for attonear Use NEAR as default unit Min node version requirement Search by block height in near-explorer Implement API for signing individual transaction in near-wallet Published v0.17.3 of nearlib Added documentation explaining receipt matching in nomicon Lastly, check out the ongoing discussions for the design of cross-shard composability in NEP (here and here) HOW YOU CAN GET INVOLVED Join us: there are new jobs we’re hiring across the board! If you want to work with one of the most talented teams in the world right now to solve incredibly hard problems, check out our careers page for openings. And tell your friends! Learn more about NEAR in The Beginner’s Guide to NEAR Protocol. 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. https://upscri.be/633436/
# Components Here is the high-level diagram of various runtime components, including some blockchain layer components. <img src="/images/runtime_architecture.svg" />
# Royalties and Payouts ## [NEP-199](https://github.com/near/NEPs/blob/master/neps/nep-0199.md) Version `2.0.0`. This standard assumes the NFT contract has implemented [NEP-171](https://github.com/near/NEPs/blob/master/specs/Standards/Tokens/NonFungibleToken/Core.md) (Core) and [NEP-178](https://github.com/near/NEPs/blob/master/specs/Standards/Tokens/NonFungibleToken/ApprovalManagement.md) (Approval Management). ## Summary An interface allowing non-fungible token contracts to request that financial contracts pay-out multiple receivers, enabling flexible royalty implementations. ## Motivation Currently, NFTs on NEAR support the field `owner_id`, but lack flexibility for ownership and payout mechanics with more complexity, including but not limited to royalties. Financial contracts, such as marketplaces, auction houses, and NFT loan contracts would benefit from a standard interface on NFT producer contracts for querying whom to pay out, and how much to pay. Therefore, the core goal of this standard is to define a set of methods for financial contracts to call, without specifying how NFT contracts define the divide of payout mechanics, and a standard `Payout` response structure. ## Specification This Payout extension standard adds two methods to NFT contracts: - a view method: `nft_payout`, accepting a `token_id` and some `balance`, returning the `Payout` mapping for the given token. - a call method: `nft_transfer_payout`, accepting all the arguments of`nft_transfer`, plus a field for some `Balance` that calculates the `Payout`, calls `nft_transfer`, and returns the `Payout` mapping. Financial contracts MUST validate several invariants on the returned `Payout`: 1. The returned `Payout` MUST be no longer than the given maximum length (`max_len_payout` parameter) if provided. Payouts of excessive length can become prohibitively gas-expensive. Financial contracts can specify the maximum length of payout the contract is willing to respect with the `max_len_payout` field on `nft_transfer_payout`. 2. The balances MUST add up to less than or equal to the `balance` argument in `nft_transfer_payout`. If the balance adds up to less than the `balance` argument, the financial contract MAY claim the remainder for itself. 3. The sum of the balances MUST NOT overflow. This is technically identical to 2, but financial contracts should be expected to handle this possibility. Financial contracts MAY specify their own maximum length payout to respect. At minimum, financial contracts MUST NOT set their maximum length below 10. If the Payout contains any addresses that do not exist, the financial contract MAY keep those wasted payout funds. Financial contracts MAY take a cut of the NFT sale price as commission, subtracting their cut from the total token sale price, and calling `nft_transfer_payout` with the remainder. ## Example Flow ``` ┌─────────────────────────────────────────────────┐ │Token Owner approves marketplace for token_id "0"│ ├─────────────────────────────────────────────────┘ │ nft_approve("0",market.near,<SaleArgs>) ▼ ┌───────────────────────────────────────────────┐ │Marketplace sells token to user.near for 10N │ ├───────────────────────────────────────────────┘ │ nft_transfer_payout(user.near,"0",0,"10000000",5) ▼ ┌───────────────────────────────────────────────┐ │NFT contract returns Payout data │ ├───────────────────────────────────────────────┘ │ Payout(<who_gets_paid_and_how_much) ▼ ┌───────────────────────────────────────────────┐ │Market validates and pays out addresses │ └───────────────────────────────────────────────┘ ``` ## Reference Implementation ```rust /// A mapping of NEAR accounts to the amount each should be paid out, in /// the event of a token-sale. The payout mapping MUST be shorter than the /// maximum length specified by the financial contract obtaining this /// payout data. Any mapping of length 10 or less MUST be accepted by /// financial contracts, so 10 is a safe upper limit. #[derive(Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct Payout { pub payout: HashMap<AccountId, U128>, } pub trait Payouts { /// Given a `token_id` and NEAR-denominated balance, return the `Payout`. /// struct for the given token. Panic if the length of the payout exceeds /// `max_len_payout.` fn nft_payout(&self, token_id: String, balance: U128, max_len_payout: Option<u32>) -> Payout; /// Given a `token_id` and NEAR-denominated balance, transfer the token /// and return the `Payout` struct for the given token. Panic if the /// length of the payout exceeds `max_len_payout.` #[payable] fn nft_transfer_payout( &mut self, receiver_id: AccountId, token_id: String, approval_id: Option<u64>, memo: Option<String>, balance: U128, max_len_payout: Option<u32>, ) -> Payout { assert_one_yocto(); let payout = self.nft_payout(token_id, balance); self.nft_transfer(receiver_id, token_id, approval_id, memo); payout } } ``` ## Fallback on error In the case where either the `max_len_payout` causes a panic, or a malformed `Payout` is returned, the caller contract should transfer all funds to the original token owner selling the token. ## Potential pitfalls The payout must include all accounts that should receive funds. Thus it is a mistake to assume that the original token owner will receive funds if they are not included in the payout. NFT and financial contracts vary in implementation. This means that some extra CPU cycles may occur in one NFT contract and not another. Furthermore, a financial contract may accept fungible tokens, native NEAR, or another entity as payment. Transferring native NEAR tokens is less expensive in gas than sending fungible tokens. For these reasons, the maximum length of payouts may vary according to the customization of the smart contracts. ## Drawbacks There is an introduction of trust that the contract calling `nft_transfer_payout` will indeed pay out to all intended parties. However, since the calling contract will typically be something like a marketplace used by end users, malicious actors might be found out more easily and might have less incentive. There is an assumption that NFT contracts will understand the limits of gas and not allow for a number of payouts that cannot be achieved. ## Future possibilities In the future, the NFT contract itself may be able to place an NFT transfer is a state that is "pending transfer" until all payouts have been awarded. This would keep all the information inside the NFT and remove trust. ## Errata - Version `2.1.0` adds a memo parameter to `nft_transfer_payout`, which previously forced implementers of `2.0.0` to pass `None` to the inner `nft_transfer`. Also refactors `max_len_payout` to be an option type. - Version `2.0.0` contains the intended `approval_id` of `u64` instead of the stringified `U64` version. This was an oversight, but since the standard was live for a few months before noticing, the team thought it best to bump the major version. ## Copyright [copyright]: #copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
--- description: A guide to using the Rainbow Bridge. title: Rainbow Bridge sidebar_position: 7 --- --- If you have existing assets on Ethereum, it's possible to transfer them to NEAR and vice-versa. The Rainbow Bridge allows you to move ERC-20 assets between Ethereum, Aurora and NEAR. The bridge was built by Aurora, the Ethereum-compatible scaling solution built on NEAR. To use the Rainbow Bridge, you will need to create a [NEAR wallet](overview/tokenomics/creating-a-near-wallet.md), and you will need to install MetaMask. ## How Much Does it Cost? Transfers between NEAR and Aurora happen instantaneously and require a single transaction. Similarly, transfers from Ethereum to NEAR or Aurora only require a single transaction, they take approximately 10 minutes and the cost will be estimated by MetaMask. Transfers to Ethereum, from NEAR or Aurora require two transactions. These transactions are the kickoff, from the network you start with and the finalization Ethereum. The finalization can take up to 16 hours, and the cost is determined by the Ethereum gas price which makes them hard to predict. Once a transaction begins, it cannot be cancelled, but you don't have to start the finalization transaction immediately. If the gas prices are too high, you can wait until they drop to a manageable price before beginning the finalization transaction. ## Using The Rainbow Bridge Start by connecting MetaMask, and your NEAR wallet so that you can make transfers between the NEAR network and other networks. In the example below we'll transfer NEAR to Aurora. ![Connect your wallets](@site/static/img/rainbowbridge1.png) Next you need to choose the token you're transferring, and the amount you'll transfer. In the example below we're transferring 1 NEAR to Aurora. ![Enter your transfer details](@site/static/img/rainbowbridge2.png) Now, you need to confirm your transaction. ![Confirm transfer](@site/static/img/rainbowbridge3.png) Finally, if the transfer details are accurate and you're satisfied with the fee, click the "Approve" button. ![Approve transfer](@site/static/img/rainbowbridge4.png) **Note:** Depending on the direction of your bridge transactions, you may be requested to confirm additional transactions in MetaMask and/or NEAR Wallet.
--- id: economics title: Web 3.0 Economics sidebar_label: Economics --- With technological decentralization also came economical decentralization. It stands on 3 pillars - Non-Fungible tokens (NFTs), Fungible tokens (FTs) and Decentralized Finance (DeFi). ## Non-Fungible Tokens At the heart of the new Web 3 economy lies [Non-Fungible token](https://en.wikipedia.org/wiki/Non-fungible_token) (NFT). In a nutshell, it’s a way to represent digital ownership in a decentralized way. From a technical perspective, it’s just a piece of data on a blockchain. The simplest case of such data is just a `(token_id, account_id)` tuple, where `token_id` uniquely identifies an asset, and `account_id` identifies an owner. A smart contract that owns this data defines a set of allowed operations - like creation of a new token (minting) or transfer of a token to another account. An exact set of allowed operations is defined in an NFT standard. Different blockchains have different standards, NEAR NFT Standard is available [here](https://nomicon.io/Standards/NonFungibleToken/). Because NFTs are tied to a specific contract, they mostly make sense only in scope of this contract, and subsequently they are tied to a specific dApp. It’s possible to implement transfer of NFTs between contracts, but there’s no standard way to do this. What digital asset is hiding behind a `token_id` is up to the smart contract to decide. There are few common ways how to handle this: - Store an asset itself in a smart contract alongside the ownership information. This is the most straightforward way, but often is not feasible since storage cost is quite high and many types of digital assets, especially media, are quite big. <div align="center"> <img src="/docs/assets/web3/web3-20.png" alt="image" width="400" /> </div> - Store token data off-chain. Such an approach solves storage cost problems, but requires some level of trust to guarantee that data in the off-chain storage won’t be changed or removed. ![image](/docs/assets/web3/web3-21.png) - Store asset’s metadata and hash on chain, and an asset itself on some off-chain storage. Storing an asset’s hash on a chain guarantees data integrity and immutability. On-chain metadata usually includes basic token information, like title, description and media url. It’s required to quickly identify an asset without downloading it from the storage. This is the most popular approach to handle NFT’s since it combines the best of 2 previous approaches - token is immutable and storage cost is cheap (exact cost depends on the storage solution, but it usually several orders of magnitude cheaper than an on-chain storage) ![image](/docs/assets/web3/web3-22.png) Choosing the right off-chain storage also can be a challenge, in general they can be divided into 2 buckets: - Centralized storages - traditional Web 2 storage solutions, like relational databases or blob storages. While suitable for some applications, this means NFTs can be destroyed if a central server goes offline, so they aren’t the most popular in the Web 3 world. - Decentralized storages. As we already mentioned, BitTorrent protocol is one of the first examples of such decentralized storage solutions, but in recent years more advanced solutions have appeared - like [IPFS](https://ipfs.io/), [FileCoin](https://filecoin.io/) and [Arweawe](https://www.arweave.org/). Such solutions are a preferred method to store digital assets, since they are cheap and decentralized, so no-one can destroy or alter NFT assets. In addition to the NFT standard, NEAR also provides [its implementation](https://docs.rs/near-contract-standards/latest/near_contract_standards/non_fungible_token/index.html), which can be used by Smart Contract developers to implement NFTs in their smart contract. Implementation itself doesn’t dictate assets storage model, so it’s up to a developer to decide how and where it will be stored. ## Fungible Tokens NFTs changed digital assets ownership model, but by itself they are not enough to build a full digital economy. In the simplest model, NFTs can be sold and bought using main blockchain currency (e.g. NEAR tokens), but this is quite limiting since circulation and price of such tokens is dictated by the blockchain itself. What if, instead of relying on blockchain currency, applications could create their own? For exactly this reason, Fungible Tokens (FT) have been created. Similarly to NFTs, fungible tokens are also just a piece of data stored in a smart contract, but instead of storing unique token ids, an amount of tokens held by an account is stored. <div align="center"> <img src="/docs/assets/web3/web3-23.png" alt="image" width="400" /> </div> Smart Contracts can define allowed operations - like transfer or payment using this token. [NEAR defines a standard](https://nomicon.io/Standards/FungibleToken/Core) for fungible tokens and provides a [default implementation](https://docs.rs/near-contract-standards/latest/near_contract_standards/fungible_token/index.html). Since an application is fully in control over emission and circulation of such tokens, a full fledged application economy can be created. For example, users can earn FTs for performing actions, and spend them to buy or mint new NFTs. Another exciting option is creation of [Decentralized Autonomous Organizations](https://near.org/use-cases/dao/) (DAOs), in which FTs can be used as a membership (or governance) tool. In such scenarios, tokens are awarded to members and can be used to vote on decisions or participate in community events. But we can push our tokens even further, by tying them to other cryptocurrencies and giving them a real-life monetary value. That’s where [Decentralized Finance](https://www.investopedia.com/decentralized-finance-defi-5113835) (DeFi), and especially [Decentralized Exchanges](https://en.wikipedia.org/wiki/Decentralized_exchange) (DEX) come into play. We won’t go into details here, but at the core a [liquidity pool](https://academy.binance.com/en/articles/what-are-liquidity-pools-in-defi) for a Fungible Token can be created on DEX, which allows trades of this token for other tokens or [stablecoins](https://en.wikipedia.org/wiki/Stablecoin). This opens the door for a new gaming model - [Play-to-Earn](https://en.wikipedia.org/wiki/Blockchain_game), where players can earn real-life money just by playing a game.
--- id: kurtosis-localnet title: Creating a Local Development Environment sidebar_label: Local Development description: Using Kurtosis NEAR Package to develop locally --- > [Kurtosis](https://www.kurtosis.com/) has created an easy way to spin up a local NEAR testing environment using a [Docker container](https://www.docker.com/). This Kurtosis NEAR Package contains the following components: - [Indexer for Explorer](https://github.com/near/near-indexer-for-explorer) - [NEAR Explorer](https://github.com/near/near-explorer) - [NEAR Wallet](https://github.com/near/near-wallet) - Local RPC Endpoint [Visit here](https://www.loom.com/share/8a1b8e2138334a81a380f5d523fba27e) to see a short demo of the package in action. --- ## Prerequisites {#prerequisites} - [Docker](https://docs.docker.com/get-docker/) - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install) - [NEAR-CLI](/tools/near-cli#setup) - [Kurtosis CLI](https://docs.kurtosis.com/install) - Start Kurtosis engine after installation using: `kurtosis engine start` --- ## Setup ### Launch Kurtosis NEAR Package {#launching-cluster} Launch your Kurtosis NEAR Package in four easy steps! 1. Launch [Docker](https://docs.docker.com/get-docker/) 2. Copy the [Kurtosis NEAR Package launch script](https://github.com/kurtosis-tech/near-package/blob/master/launch-local-near-cluster.sh) by running the following: ```bash curl -o ~/launch-local-near-cluster.sh https://raw.githubusercontent.com/kurtosis-tech/near-package/master/launch-local-near-cluster.sh -L ``` 3. Grant write permission to the script file you just downloaded: ```bash chmod u+x ~/launch-local-near-cluster.sh ``` 4. Launch the Kurtosis NEAR Package: If you're running the NEAR-in-Kurtosis cluster on your local machine: ```bash ~/launch-local-near-cluster.sh ``` If you're running your NEAR-in-Kurtosis cluster on a machine you intend to access remotely, replace `1.2.3.4` with the IP address of the machine you're running the cluster on: ```bash ~/launch-local-near-cluster.sh '{"backend_ip_address":"1.2.3.4"}' ``` <details> <summary>Example response: </summary> ```bash Created directory '/Users/zerix/.neartosis' for storing all NEAR-in-Kurtosis output INFO[2022-12-06T12:59:04+05:30] Creating a new enclave for Starlark to run inside... INFO[2022-12-06T12:59:14+05:30] Enclave 'near' created successfully INFO[2022-12-06T12:59:14+05:30] Kurtosis CLI is running in a non interactive terminal. Everything will work but progress information and the progress bar will not be displayed. > print "Starting the near-package with input struct(backend_ip_address = \"127.0.0.1\")" Starting the near-package with input struct(backend_ip_address = "127.0.0.1") > print "Launching contract helper postgresql" Launching contract helper postgresql > print "Adding contract helper Posgresql DB running on port '5432'" Adding contract helper Posgresql DB running on port '5432' > add_service service_id="contract-helper-db" Service 'contract-helper-db' added with service GUID 'contract-helper-db-1670311755' > exec service_id="contract-helper-db" command=["sleep", "10"] Command returned with exit code '0' with no output > exec service_id="contract-helper-db" command=["psql", "-U", "near", "-c", "\\l"] Command returned with exit code '0' and the following output: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+-------+----------+------------+------------+------------------- near | near | UTF8 | en_US.utf8 | en_US.utf8 | postgres | near | UTF8 | en_US.utf8 | en_US.utf8 | template0 | near | UTF8 | en_US.utf8 | en_US.utf8 | =c/near + | | | | | near=CTc/near template1 | near | UTF8 | en_US.utf8 | en_US.utf8 | =c/near + | | | | | near=CTc/near (4 rows) > exec service_id="contract-helper-db" command=["psql", "-U", "near", "-c", "create database indexer with owner=near"] Command returned with exit code '0' and the following output: 'CREATE DATABASE' > exec service_id="contract-helper-db" command=["psql", "-U", "near", "-c", "create database analytics with owner=near"] Command returned with exit code '0' and the following output: 'CREATE DATABASE' > exec service_id="contract-helper-db" command=["psql", "-U", "near", "-c", "create database telemetry with owner=near"] Command returned with exit code '0' and the following output: 'CREATE DATABASE' > print "Contract helper postgresql db info struct(analytics_db = \"analytics\", db_user_password = \"near\", db_username = \"near\", indexer_db = \"indexer\", private_url = struct(ip_address = \"contract-helper-db\", path = \"\", port_number = 5432, protocol = \"postgres\"), telemetry_db = \"telemetry\")" Contract helper postgresql db info struct(analytics_db = "analytics", db_user_password = "near", db_username = "near", indexer_db = "indexer", private_url = struct(ip_address = "contract-helper-db", path = "", port_number = 5432, protocol = "postgres"), telemetry_db = "telemetry") > print "Launching contract helper dynamo db" Launching contract helper dynamo db > print "Adding contract helper DynamoDB running on default port '8000'" Adding contract helper DynamoDB running on default port '8000' > add_service service_id="contract-helper-dynamo-db" Service 'contract-helper-dynamo-db' added with service GUID 'contract-helper-dynamo-db-1670311770' > print "Contract helper dynamodb info struct(private_url = struct(ip_address = \"contract-helper-dynamo-db\", path = \"\", port_number = 8000, protocol = \"TCP\"))" Contract helper dynamodb info struct(private_url = struct(ip_address = "contract-helper-dynamo-db", path = "", port_number = 8000, protocol = "TCP")) > print "Launching indexer" Launching indexer > print "Adding indexer service..." Adding indexer service... > upload_files src="github.com/kurtosis-tech/near-package/static_files/near-configs/localnet" artifact_id="8f5279c5-d012-4543-88e7-e9829b6d6040" Files uploaded with artifact ID '8f5279c5-d012-4543-88e7-e9829b6d6040' > add_service service_id="indexer-node" Service 'indexer-node' added with service GUID 'indexer-node-1670311774' > exec service_id="indexer-node" command=["sleep", "10"] Command returned with exit code '0' with no output > exec service_id="indexer-node" command=["cat", "/root/.near/validator_key.json"] Command returned with exit code '0' and the following output: { "account_id": "test.near", "public_key": "ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW", "secret_key": "ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW" } > print "Indexer launched with struct(private_rpc_url = struct(ip_address = \"indexer-node\", path = \"\", port_number = 3030, protocol = \"http\"), public_rpc_url = struct(ip_address = \"127.0.0.1\", path = \"\", port_number = 8332, protocol = \"http\"), validator_key = {\"account_id\": \"test.near\", \"public_key\": \"ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW\", \"secret_key\": \"ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW\"})" Indexer launched with struct(private_rpc_url = struct(ip_address = "indexer-node", path = "", port_number = 3030, protocol = "http"), public_rpc_url = struct(ip_address = "127.0.0.1", path = "", port_number = 8332, protocol = "http"), validator_key = {"account_id": "test.near", "public_key": "ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW", "secret_key": "ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW"}) > print "Launching contract helper" Launching contract helper > print "Adding contract helper service running on port '3000'" Adding contract helper service running on port '3000' > add_service service_id="contract-helper-service" Service 'contract-helper-service' added with service GUID 'contract-helper-service-1670311796' > print "Contract helper launchded with struct(private_url = struct(ip_address = \"contract-helper-service\", path = \"\", port_number = 3000, protocol = \"http\"), public_url = struct(ip_address = \"127.0.0.1\", path = \"\", port_number = 8330, protocol = \"http\"))" Contract helper launchded with struct(private_url = struct(ip_address = "contract-helper-service", path = "", port_number = 3000, protocol = "http"), public_url = struct(ip_address = "127.0.0.1", path = "", port_number = 8330, protocol = "http")) > print "Launching explorer backend" Launching explorer backend > print "Adding explorer backend service" Adding explorer backend service > add_service service_id="explorer-backend" Service 'explorer-backend' added with service GUID 'explorer-backend-1670311799' > print "Explorer backend launchded with struct(private_url = struct(ip_address = \"explorer-backend\", path = \"\", port_number = 8080, protocol = \"http\"), public_url = struct(ip_address = \"127.0.0.1\", path = \"\", port_number = 18080, protocol = \"http\"))" Explorer backend launchded with struct(private_url = struct(ip_address = "explorer-backend", path = "", port_number = 8080, protocol = "http"), public_url = struct(ip_address = "127.0.0.1", path = "", port_number = 18080, protocol = "http")) > print "Launching explorer frontend" Launching explorer frontend > print "Adding explorer frontend service running on port '3000'" Adding explorer frontend service running on port '3000' > add_service service_id="explorer-frontend" Service 'explorer-frontend' added with service GUID 'explorer-frontend-1670311803' > print "Explorer frontend launchded with struct(public_url = struct(ip_address = \"127.0.0.1\", path = \"\", port_number = 8331, protocol = \"http\"))" Explorer frontend launchded with struct(public_url = struct(ip_address = "127.0.0.1", path = "", port_number = 8331, protocol = "http")) > print "Launching wallet" Launching wallet > print "Adding wallet service running on port '3004" Adding wallet service running on port '3004 > print "Replacing variable 'NODE_URL' to 'http://127.0.0.1:8332' using regexp: '([,{])NODE_URL:[^,]*([,}])'" Replacing variable 'NODE_URL' to 'http://127.0.0.1:8332' using regexp: '([,{])NODE_URL:[^,]*([,}])' > print "Replacing variable 'ACCOUNT_HELPER_URL' to 'http://127.0.0.1:8330' using regexp: '([,{])ACCOUNT_HELPER_URL:[^,]*([,}])'" Replacing variable 'ACCOUNT_HELPER_URL' to 'http://127.0.0.1:8330' using regexp: '([,{])ACCOUNT_HELPER_URL:[^,]*([,}])' > print "Replacing variable 'EXPLORER_URL' to 'http://127.0.0.1:8331' using regexp: '([,{])EXPLORER_URL:[^,]*([,}])'" Replacing variable 'EXPLORER_URL' to 'http://127.0.0.1:8331' using regexp: '([,{])EXPLORER_URL:[^,]*([,}])' > print "Replacing variable 'NETWORK_ID' to 'localnet' using regexp: '([,{])NETWORK_ID:[^,]*([,}])'" Replacing variable 'NETWORK_ID' to 'localnet' using regexp: '([,{])NETWORK_ID:[^,]*([,}])' > print "Replacing variable 'ACCOUNT_ID_SUFFIX' to 'test.near' using regexp: '([,{])ACCOUNT_ID_SUFFIX:[^,]*([,}])'" Replacing variable 'ACCOUNT_ID_SUFFIX' to 'test.near' using regexp: '([,{])ACCOUNT_ID_SUFFIX:[^,]*([,}])' > print "Replacing variable 'ACCESS_KEY_FUNDING_AMOUNT' to '3000000000000000000000000' using regexp: '([,{])ACCESS_KEY_FUNDING_AMOUNT:[^,]*([,}])'" Replacing variable 'ACCESS_KEY_FUNDING_AMOUNT' to '3000000000000000000000000' using regexp: '([,{])ACCESS_KEY_FUNDING_AMOUNT:[^,]*([,}])' > add_service service_id="wallet" Service 'wallet' added with service GUID 'wallet-1670311807' > print "Explorer wallet struct(public_url = struct(ip_address = \"127.0.0.1\", path = \"\", port_number = 8334, protocol = \"http\"))" Explorer wallet struct(public_url = struct(ip_address = "127.0.0.1", path = "", port_number = 8334, protocol = "http")) Starlark code successfully run. Output was: { "contract_helper_service_url": "http://127.0.0.1:8330", "explorer_url": "http://127.0.0.1:8331", "near_node_rpc_url": "http://127.0.0.1:8332", "network_name": "localnet", "root_validator_key": { "account_id": "test.near", "public_key": "ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW", "secret_key": "ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW" }, "wallet_url": "http://127.0.0.1:8334" } INFO[2022-12-06T13:00:10+05:30] ============================================= INFO[2022-12-06T13:00:10+05:30] || Created enclave: near || INFO[2022-12-06T13:00:10+05:30] ============================================= ============================================================ SUCCESS ================================================================================ ACTION Paste the following in your terminal to declare the following variables so you can use them: export NEAR_ENV="local" export NEAR_CLI_LOCALNET_NETWORK_ID="localnet" export NEAR_NODE_URL="http://127.0.0.1:8332" export NEAR_CLI_LOCALNET_KEY_PATH="/Users/zerix/.neartosis/2022-12-06T12.59.04/validator-key.json" export NEAR_WALLET_URL="http://127.0.0.1:8334" export NEAR_HELPER_URL="http://127.0.0.1:8330" export NEAR_HELPER_ACCOUNT="test.near \"ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW\"}) ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW"}) test.near" export NEAR_EXPLORER_URL="http://127.0.0.1:8331" ACTION Paste the following into your terminal now to use the 'local_near' command as a replacement for the NEAR CLI for connecting to your local cluster (e.g. 'local_near login'): alias local_near='NEAR_ENV="local" NEAR_CLI_LOCALNET_NETWORK_ID="localnet" NEAR_NODE_URL="http://127.0.0.1:8332" NEAR_CLI_LOCALNET_KEY_PATH="/Users/zerix/.neartosis/2022-12-06T12.59.04/validator-key.json" NEAR_WALLET_URL="http://127.0.0.1:8334" NEAR_HELPER_URL="http://127.0.0.1:8330" NEAR_HELPER_ACCOUNT="test.near \"ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW\"}) ed25519:2ykcMLiM7vCmsSECcgfmUzihBtNdBv7v2CxNi94sNt4R8ar4xsrMMYvtsSNGQDfSRhNWXEnZvgx2wzS9ViBiS9jW"}) test.near" NEAR_EXPLORER_URL="http://127.0.0.1:8331" near' ACTION If you want the 'local_near' command available in all your new terminal windows, add the above alias into your .bash_profile/.bashrc/.zshrc file and open a new terminal window. ACTION To stop your cluster, run the following: kurtosis enclave stop near ACTION To remove your cluster, run: kurtosis clean -a ============================================================ SUCCESS ================================================================================ ``` :::tip The URLs and validator key value above will be the same for each run of Kurtosis, so you can safely use these values in your config files. ::: :::tip If you're running Kurtosis on a remote machine, you'll also need to: - Replace the `127.0.0.1` IP addresses in the environment variables with the IP address of your remote machine - Copy the validator key from where it lives on the machine running Kurtosis (in `NEAR_CLI_LOCALNET_KEY_PATH`) to somewhere on your local machine - Adjust the value of the `NEAR_CLI_LOCALNET_KEY_PATH` on your local machine to match the location you stored the key at ::: </details> If you ever forget the above URLs, you can inspect the cluster: ``` kurtosis enclave inspect near ``` ### Setup Environment Variables After deploying your Kurtosis NEAR Package, you will need to setup some environment variables to make life a lot easier. Notice the **ACTION** sections in your terminal log from the package deployment. You will be using these exact values to setup these variables. 1. Follow the first ACTION item from the deployment log by copying all of the export commands and running them in your terminal. **Example exports: (DO NOT COPY ~ yours will be slightly different)** ```bash export NEAR_ENV="local" export NEAR_CLI_LOCALNET_NETWORK_ID="localnet" export NEAR_NODE_URL="http://127.0.0.1:8332" export NEAR_CLI_LOCALNET_KEY_PATH="/Users/zerix/.neartosis/2022-06-03T18.04.32/validator-key.json" export NEAR_WALLET_URL="http://127.0.0.1:8334" export NEAR_HELPER_URL="http://127.0.0.1:8330" export NEAR_HELPER_ACCOUNT="test.near" export NEAR_EXPLORER_URL="http://127.0.0.1:8331" ``` 2. Proceed to the second ACTION item which asks you to create an alias for `local_near`. This is what we will use when running [`near-cli`](/tools/near-cli) commands with our test environment. **Example alias: (DO NOT COPY ~ yours will be slightly different)** ```bash alias local_near='NEAR_ENV="local" NEAR_CLI_LOCALNET_NETWORK_ID="localnet" NEAR_NODE_URL="http://127.0.0.1:8332" NEAR_CLI_LOCALNET_KEY_PATH="/Users/zerix/.neartosis/2022-06-03T18.04.32/validator-key.json" NEAR_WALLET_URL="http://127.0.0.1:8334" NEAR_HELPER_URL="http://127.0.0.1:8330" NEAR_HELPER_ACCOUNT="test.near" NEAR_EXPLORER_URL="http://127.0.0.1:8331" near' ``` Now replacing `near` with `local_near` when running [`near-cli`](/tools/near-cli) commands will perform these actions in your local test environment. ### Testing Ensure that your alias is working correctly by checking the state of the root account `test.near`. Run the following in your terminal: ```bash local_near state test.near ``` This should return something similar to the following output: ```bash Loaded master account test.near key from /Users/zerix/.neartosis/2022-06-03T18.04.32/validator-key.json with public key = ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW Account test.near { amount: '1000000000000000000000000000000000', block_hash: 'G8jx4pYgqFSFSCDyM9MvVYj3HAdgRuxhkAHGweNhUNrY', block_height: 224, code_hash: '11111111111111111111111111111111', locked: '50000000000000000000000000000000', storage_paid_at: 0, storage_usage: 182, formattedAmount: '1,000,000,000' } ``` **Congratulations! Setup is complete and you are ready to start exploring your local NEAR blockchain!** 🎉 :::tip The Kurtosis Team has created a great [video presentation](https://www.loom.com/share/8a1b8e2138334a81a380f5d523fba27e) that covers the above steps as well as demoing the functionality of this local network setup. ::: --- ## Using Wallet and Explorer ### Local NEAR Wallet Now that you have [everything setup](#setup), create an account using your local NEAR Wallet at 127.0.0.1:8334. ![Local wallet landing page](/docs/assets/kurtosis/local-wallet-landing-page.png) The account creation is exactly the same as on mainnet or testnet but **only the passphrase recovery mode** will work here. Also note that the root account is `test.near` instead of `testnet` or `mainnet`. This means that all the accounts you create will be [subaccounts](/concepts/protocol/account-model#subaccounts) of `test.near`. (ex. `benji.test.near`) :::tip Because the Wallet will start on the same host and port, and the Wallet stores your account information in your browser's local storage, if you've created an account with a previous Kurtosis network then the Wallet will be storing the old account's information (which won't work with your new network). If this is the case for you, you'll need to clear the Wallet's storage by visiting [your Chrome's local storage](chrome://settings/siteData?searchSubpage=127.0.0.1), removing the `127.0.0.1` entry, and refreshing the Wallet. ::: Now that you've created an account, try interacting with it using the local CLI. In order to use this account you will need to "login" with it via CLI which will save a full access key locally for that account. [`near login`](/tools/near-cli#near-login) is the command to perform this action but as you are on `localnet` you will need to replace `near` with `local_near`. ```bash local_near login ``` This launches the local wallet site and will ask for confirmation for this action. Once you authorize you should see confirmation in your terminal similar to this: ```bash Logged in as [ kevin.test.near ] with public key [ ed25519:8EaALn... ] successfully ``` - Export your account ID to an environment variable by running the following: (replacing YOUR_ACCOUNT_ID) ```bash export ACCOUNT_ID=YOUR_ACCOUNT_ID ``` - Now create a test transaction by sending 1 $NEAR to the root account `test.near`: ```bash local_near send $ACCOUNT_ID test.near 1 ``` <details> <summary>Example response: </summary> ```bash Sending 1 NEAR to test.near from kevin.test.near Loaded master account test.near key from /Users/zerix/.neartosis/2022-06-03T18.04.32/validator-key.json with public key = ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW Transaction Id 3e3H5zqj9noKGYTCMqeZ5pb4NWK7tQsjYKak6ybtpgvD To see the transaction in the transaction explorer, please open this url in your browser http://127.0.0.1:8331/transactions/3e3H5zqj9noKGYTCMqeZ5pb4NWK7tQsjYKak6ybtpgvD ``` </details> ### Local NEAR Explorer Again, now that you have [everything setup](#setup) you can view the transaction details of the command you just performed at the end of [the last section](#local-near-wallet). Notice that the last line of the terminal log displays a link to the transaction details in your local NEAR Explorer. ```bash Sending 1 NEAR to test.near from kevin.test.near Loaded master account test.near key from /Users/zerix/.neartosis/2022-06-03T18.04.32/validator-key.json with public key = ed25519:3Kuyi2DUXdoHgoaNEvCxa1m6G8xqc6Xs7WGajaqLhNmW Transaction Id 3e3H5zqj9noKGYTCMqeZ5pb4NWK7tQsjYKak6ybtpgvD To see the transaction in the transaction explorer, please open this url in your browser http://127.0.0.1:8331/transactions/3e3H5zqj9noKGYTCMqeZ5pb4NWK7tQsjYKak6ybtpgvD ``` - Click on this link or copy/paste it into your browser: ![Local explorer sending 1 NEAR](/docs/assets/kurtosis/local-explorer-send-funds.png) Here everything behaves exactly like the `testnet` or `mainnet` NEAR Explorer except it is retrieving data from your local NEAR blockchain! - If you ever need to open your local NEAR Explorer, you can always visit 127.0.0.1:8331 or run: ```bash echo $NEAR_EXPLORER_URL ``` **Example Response:** ```bash http://127.0.0.1:8331 ``` ![Localnet explorer](/docs/assets/kurtosis/localnet-explorer.png) --- ## Deploy a Smart Contract With everything setup and your `test.near` account created, it's time to deploy a smart contract on `localnet`. For this example you will deploy an NFT use a pre-compiled WASM smart contract from [this NFT example](https://github.com/near-examples/nft-tutorial.git). - Download the smart contract: ``` curl -o ~/main.wasm https://github.com/near-examples/nft-tutorial/raw/main/out/main.wasm -L ``` - Deploy the smart contract: ``` local_near deploy --wasmFile ~/main.wasm --accountId $ACCOUNT_ID ``` <details> <summary>Example response: </summary> ``` Loaded master account test.near key from /Users/benjaminkurrek/.neartosis/2021-12-02T13.37.41/validator-key.json with public key = ed25519:AnLHi4ZAxfxFAQSXniycyZS6dpBqxhmVZH3zBCZbqAS6 Starting deployment. Account id: goteam.test.near, node: http://127.0.0.1:62285, helper: http://127.0.0.1:62286, file: /Users/benjaminkurrek/main.wasm Transaction Id 7atHm2piVehEitYeMF2FxWuRJVd6ZdRQEo3K83P98GuR To see the transaction in the transaction explorer, please open this url in your browser http://127.0.0.1:62290/transactions/7atHm2piVehEitYeMF2FxWuRJVd6ZdRQEo3K83P98GuR Done deploying to goteam.test.near ``` </details> - Click on the clink to the Explorer and verify that the contract was deployed: ![Local explorer contract deployed](/docs/assets/kurtosis/local-explorer-contract-deployed.png) Now, let's interact with the deployed contract. - First, initialize the contract by running the following command: ```bash local_near call $ACCOUNT_ID new_default_meta '{"owner_id": "'$ACCOUNT_ID'"}' --accountId $ACCOUNT_ID ``` This will initialize the contract with some default metadata and set our account ID as the owner of the contract. - Now mint your first NFT! ```bash local_near call $ACCOUNT_ID nft_mint '{"token_id": "team_token", "metadata": { "title": "Go Team!", "description": "Go Team!", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif", "copies": 1}, "receiver_id": "'$ACCOUNT_ID'"}' --accountId $ACCOUNT_ID --amount 0.1 ``` Once the NFT has been minted, you can view the token on the local wallet's collectibles tab. If you already had the wallet site open, simply refresh. Otherwise open your local NEAR Wallet instance and view your collectible. ![Local wallet collectibles tab](/docs/assets/kurtosis/local-wallet-collectibles-tab.png) We won't spoil what the NFT is, but once you switch over to the collectibles tab your beautiful token should be there! --- ## Connecting a dApp to `localnet` The ability to develop decentralized applications locally is a dream come true for dApp developers and the Kurtosis NEAR Package really simplifies this process. Here you'll integrate `localnet` into one of the examples at [near.dev](http://near.dev). ### Clone Example dApp - Clone the [NEAR Guestbook](https://github.com/near-examples/guest-book-examples) repository: ```bash git clone https://github.com/near-examples/guest-book-examples.git ``` ### Configure Network - Open the `src/config.js` file inside the guestbook repo and scroll down to the `local` config: ```javascript case 'local': return { networkId: 'local', nodeUrl: 'http://localhost:3030', keyPath: `${process.env.HOME}/.near/validator_key.json`, walletUrl: 'http://localhost:4000/wallet', contractName: CONTRACT_NAME }; ``` Here you will need to update all of the values **except** the `contractName`. Copy the following into your `local` case. This will automatically assign the config to your environment variables if you've specified them. This way, you don't need to change anything when running new enclaves. ```javascript case 'local': return { networkId: process.env.NEAR_CLI_LOCALNET_NETWORK_ID || 'local', nodeUrl: process.env.NEAR_NODE_URL || 'http://localhost:3030', keyPath: process.env.NEAR_CLI_LOCALNET_KEY_PATH || `${process.env.HOME}/.near/validator_key.json`, walletUrl: process.env.NEAR_WALLET_URL || 'http://localhost:4000/wallet', contractName: CONTRACT_NAME, }; ``` The last thing you will need to do is set your `NODE_ENV` in your terminal to `local` so your dApp will use the values we configured above. - Run: ```bash export NODE_ENV=local ``` **Your dApp is now fully configured to use `localnet`!** 🎉 ### Create Contract Account As mentioned earlier, you do not need to change the `contractName` in the `config.js` file you updated earlier. This is an environment variable you will configure now. Let's quickly create a subaccount from [the account you created earlier](#local-near-wallet) to deploy the guest-book contract to. - Using the `local_near CLI`, run the following command: ```bash local_near create-account guest-book.$ACCOUNT_ID --masterAccount $ACCOUNT_ID --initialBalance 5 ``` **Example Response:** ```bash Loaded master account test.near key from /Users/benjaminkurrek/.neartosis/2021-12-02T13.37.41/validator-key.json with public key = ed25519:AnLHi4ZAxfxFAQSXniycyZS6dpBqxhmVZH3zBCZbqAS6 Saving key to 'undefined/localnet/guest-book.goteam.test.near.json' Account guest-book.goteam.test.near for network "localnet" was created. ``` - Export the `CONTRACT_NAME` environment variable as the account you just created: ```bash export CONTRACT_NAME=guest-book.$ACCOUNT_ID ``` ### Deploy Contract to `localnet` With the network setup and contract account created you are now ready to launch your dApp! - Run the following command in the root directory of the guest book repo: ```bash yarn && yarn start ``` **Example Response:** ![Local dApp build](/docs/assets/kurtosis/local-dapp-build.png) - Open the dApp by clicking on the server address in the terminal: ```bash Server running at http://localhost:1234 ✨ Built in 1.20s. ``` You should see the Guest Book landing page: ![Local Guest Book Landing Page](/docs/assets/kurtosis/local-guest-book-landing.png) :::tip If you run into any problems signing into try clearing your browser's local storage. If you've used the guest-book before your browser might think you're still logged in with your `testnet` account and it will throw an error saying it can't find that account on `localnet`. ::: Once you've logged in, you can sign a message with an optional donation. ![Local Guest Book Signed Message](/docs/assets/kurtosis/local-guest-book-signed-message.png) - Sign the Guest Book which will create a transaction on `localnet`. - Once complete, open your local NEAR explorer and you can view the transaction you just created! ![Local Explorer Signed Transaction](/docs/assets/kurtosis/local-explorer-signed-transaction.png) **Congratulations! You've successfully deployed and interacted with a dApp on a local NEAR blockchain!** 🎉 --- ## Managing NEAR Pacakages The Kurtosis NEAR Pacakages you create will continue to run on your local machine for as long as your Docker engine is running. This package runs inside of a Kurtosis "enclave" which is an environment isolated from both your computer and other enclaves. In practice, this means that you can have multiple independent local NEAR clusters running on your machine simply by rerunning the script we executed from the [setup instructions](#setup). ### View Package Status - To see the status of your existing enclaves, run: ```bash kurtosis enclave ls ``` ### View Package Details - To see detailed information about an enclave, copy an enclave ID and run: ```bash kurtosis enclave inspect near ``` ### Terminate Package - To shut down your NEAR Package and free up resources on your machine, run the following: ```bash kurtosis enclave stop near ``` :::note You will not be able to restart the cluster! If this is something you need, please [file an issue here](https://github.com/kurtosis-tech/kurtosis-cli-release-artifacts) so we can prioritize it. ::: ### Delete Package - Stopping an enclave leaves its resources intact so that you can examine them if need be. To destroy a stopped enclave and free its resources, run: ``` kurtosis clean ``` ### Delete All Package If you would like to destroy _all_ enclaves, regardless of if they're running, pass the `-a` flag to `clean` like so: ``` kurtosis clean -a ``` This can be a handy way to clear all your Kurtosis data.
--- id: upgrade-contract title: Upgrading the Contract sidebar_label: Upgrade a Contract --- import {Github} from "@site/src/components/codetabs" In this tutorial, you'll build off the work you previously did to implement the [minting functionality](/tutorials/nfts/js/minting) on a skeleton smart contract. You got to the point where NFTs could be minted, however, the wallet had no way of displaying the tokens since your contract didn't implement the method that the wallet was trying to call. ## Introduction Today you'll learn about deploying patch fixes to smart contracts and you'll use that knowledge to implement the `nft_tokens_for_owner` function on the contract you deployed in the previous tutorial. ## Upgrading contracts overview {#upgrading-contracts} Upgrading contracts, when done right, can be an immensely powerful tool. If done wrong, it can lead to a lot of headaches. It's important to distinguish between the code and state of a smart contract. When a contract is deployed on top of an existing contract, the only thing that changes is the code. The state will remain the same and that's where a lot of developer's issues come to fruition. The NEAR Runtime will read the serialized state from disk and it will attempt to load it using the current contract code. When your code changes, it might not be able to figure out how to do this. You need to strategically upgrade your contracts and make sure that the runtime will be able to read your current state with the new contract code. For more information about upgrading contracts and some best practices, see the NEAR SDK's [upgrading contracts](/sdk/rust/building/prototyping) write-up. ## Modifications to our contract {#modifications-to-contract} In order for the wallet to properly display your NFTs, you need to implement the `nft_tokens_for_owner` method. This will allow anyone to query for a paginated list of NFTs owned by a given account ID. To accomplish this, let's break it down into some smaller subtasks. First, you need to get access to a list of all token IDs owned by a user. This information can be found in the `tokensPerOwner` data structure. Now that you have a set of token IDs, you need to convert them into `JsonToken` objects as that's what you'll be returning from the function. Luckily, you wrote a function `nft_token` which takes a token ID and returns a `JsonToken` in the `nft_core.ts` file. As you can guess, in order to get a list of `JsonToken` objects, you would need to iterate through the token IDs owned by the user and then convert each token ID into a `JsonToken` and store that in a list. As for the pagination, you can use some basic JavaScript to get that done. Let's move over to the `enumeration.ts` file and implement that logic: <Github language="js" start="47" end="82" url="https://github.com/near-examples/nft-tutorial-js/blob/2.minting/src/nft-contract/enumeration.ts" /> ## Redeploying the contract {#redeploying-contract} Now that you've implemented the necessary logic for `nft_tokens_for_owner`, it's time to build and re-deploy the contract to your account. Using the build script, deploy the contract as you did in the previous tutorial: ```bash yarn build && near deploy --wasmFile build/nft.wasm --accountId $NFT_CONTRACT_ID ``` This should output a warning saying that the account has a deployed contract and will ask if you'd like to proceed. Simply type `y` and hit enter. ```bash This account already has a deployed contract [ AKJK7sCysrWrFZ976YVBnm6yzmJuKLzdAyssfzK9yLsa ]. Do you want to proceed? (y/n) ``` Once the contract has been redeployed, let's test and see if the state migrated correctly by running a simple view function: ```bash near view $NFT_CONTRACT_ID nft_metadata ``` This should return an output similar to the following: ```bash { spec: 'nft-1.0.0', name: 'NFT Tutorial Contract', symbol: 'GOTEAM' } ``` **Go team!** At this point, you can now test and see if the new function you wrote works correctly. Let's query for the list of tokens that you own: ```bash near view $NFT_CONTRACT_ID nft_tokens_for_owner '{"account_id": "'$NFT_CONTRACT_ID'", "limit": 5}' ``` <details> <summary>Example response: </summary> <p> ```bash [ { token_id: 'token-1', owner_id: 'goteam.examples.testnet', metadata: { title: 'My Non Fungible Team Token', description: 'The Team Most Certainly Goes :)', media: 'https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif' } } ] ``` </p> </details> ## Viewing NFTs in the wallet {#viewing-nfts-in-wallet} Now that your contract implements the necessary functions that the wallet uses to display NFTs, you should be able to see your tokens on display in the [collectibles tab](https://testnet.mynearwallet.com//?tab=collectibles). ![filled-nft-in-wallet](/docs/assets/nfts/filled-nft-in-wallet.png) ## Conclusion In this tutorial, you learned about the basics of [upgrading contracts](#upgrading-contracts). Then, you implemented the necessary [modifications to your smart contract](#modifications-to-contract) and [redeployed it](#redeploying-contract). Finally you navigated to the wallet collectibles tab and [viewed your NFTs](#viewing-nfts-in-wallet). In the [next tutorial](/tutorials/nfts/js/enumeration), you'll implement the remaining functions needed to complete the [enumeration](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration) standard. :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `3.0.0` - NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0` :::
--- id: circulating-supply title: Creating a Circulating Supply sidebar_label: Circulating Supply --- import {Github} from "@site/src/components/codetabs" In the previous tutorial, you looked at what a fungible token was and how you could define one in your smart contract. In this tutorial, you'll learn how to create a circulating supply belonging to the contract owner and view all the tokens, with their metadata, in the NEAR wallet. To get started, either work off the code you wrote in the previous tutorial or switch to the `2.define-a-token` folder in our repo. If you haven't cloned the repository, refer to the [Contract Architecture](1-skeleton.md) to start. If you wish to see the finished code for this tutorial, you can find it in the `3.initial-supply` folder. ## Introduction Every fungible token contract on NEAR has what's known as a circulating supply. This is the number of tokens that exist on the contract and are actively available to trade. When creating your contract, there are many different ways you could implement this to start. A few examples could be: - Specify a starting total supply and distribute it based on a set of parameters (Benji gets 20%, Josh gets 2.5%, and the rest goes to Mike). - Have a first come first serve pool where everybody claims up to X amount of tokens. - Create tokens on demand resulting in a steady increase of the circulating supply overtime up to a specified cap. The simplest approach, however, is to specify a total supply when initializing the contract. The entire circulating supply is then created and sent to the owner of the contract. The owner would then be able to transfer or sell the tokens as they wish. Once the initial supply is created, no more FTs could be minted. This means that the circulating supply will always be equal to the total supply. ## Modifications to contract In order to implement this logic, you'll need to keep track of two things in your smart contract: - A mapping of an account to the number of tokens they own. - The total supply of tokens. The mapping is so that you can easily check or modify the tokens owned by any given account at anytime within your contract. You'll also need to keep track of the total supply since it's required by the standard that you have a function to query for the supply of tokens on the contract. ### Setting the supply Head over to the `src/lib.rs` file and add the following code to the `Contract` struct. <Github language="rust" start="21" end="32" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/lib.rs" /> You'll now want to add the functionality for depositing the tokens into the owner's account. Do this by creating a helper function that takes an amount and an account ID and performs the deposit logic for you. First create a new file `src/internal.rs` such that your file structure now looks as follows. ``` src ├── ft_core.rs ├── internal.rs ├── lib.rs ├── metadata.rs └── storage.rs ``` In the `internal.rs` file, add the following code to create a function called `internal_deposit` which takes an `AccountId` and a `Balance` and adds the amount to the account's current supply of FTs. <Github language="rust" start="1" end="18" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/internal.rs" /> Now that the functionality for depositing FTs is in place, switch back to the `src/lib.rs` file and add the `internal` module: <Github language="rust" start="8" end="10" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/lib.rs" /> In addition, add the following code to the `new` initialization function. ```rust #[init] pub fn new( owner_id: AccountId, total_supply: U128, metadata: FungibleTokenMetadata, ) -> Self { // Create a variable of type Self with all the fields initialized. let mut this = Self { // Set the total supply total_supply: total_supply.0, // Storage keys are simply the prefixes used for the collections. This helps avoid data collision accounts: LookupMap::new(StorageKey::Accounts.try_to_vec().unwrap()), metadata: LazyOption::new( StorageKey::Metadata.try_to_vec().unwrap(), Some(&metadata), ), }; // Set the owner's balance to the total supply. this.internal_deposit(&owner_id, total_supply.into()); // Return the Contract object this } ``` This will initialize the total supply to what you passed in and will call the `internal_deposit` function to add the total supply to the owner's account. ### Getting the supply Now that you've created a way to set the total supply, you'll also want a way to query for it as well as the balance for a specific user. The [standard](https://nomicon.io/Standards/Tokens/FungibleToken/Core) dictates that you should have two methods on your smart contract for doing these operations: - **`ft_total_supply`** - **`ft_balance_of`** Head on over to the `src/ft_core.rs` file and add the following code to these functions. <Github language="rust" start="83" end="91" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/ft_core.rs" /> At this point, you have everything you need to create an initial supply of tokens and query for the balance of a given account. There is, however, a problem that we need to solve. How will the wallet know that the total supply was created and is owned by the contract owner? How would it even know that our contract is a fungible token contract? If you were to deploy the contract and run through the setup process, you would be able to query for the information from the contract but you wouldn't see any FTs in the owner's NEAR wallet. ## Events Have you ever wondered how the wallet knows which FTs you own and how it can display them in the [balances tab](https://testnet.mynearwallet.com/)? Originally, an [indexer](/tools/indexer-for-explorer) was used and it listened for any functions starting with `ft_` on your account. These contracts were then flagged on your account as likely FT contracts. When you navigated to your balances tab, the wallet would then query all those contracts for the number of FTs you owned using the `ft_balance_of` function you just wrote. ### The problem {#the-problem} This method of flagging contracts was not reliable as each FT-driven application might have its own way of minting or transferring FTs. In addition, it's common for apps to transfer or mint many tokens at a time using batch functions. ### The solution {#the-solution} A standard was introduced so that smart contracts could emit an event anytime FTs were transferred, minted, or burnt. This event was in the form of a log. No matter how a contract implemented the functionality, an indexer could now listen for those standardized logs. As per the standard, you need to implement a logging functionality that gets fired when FTs are transferred or minted. In this case, the contract doesn't support burning so you don't need to worry about that for now. It's important to note the standard dictates that the log should begin with `"EVENT_JSON:"`. The structure of your log should, however, always contain the 3 following things: - **standard**: the current name of the standard (e.g. nep141) - **version**: the version of the standard you're using (e.g. 1.0.0) - **event**: a list of events you're emitting. The event interface differs based on whether you're recording transfers or mints. The interface for both events is outlined below. **Transfer events**: - **old_owner_id**: the old owner of the FTs. - **new_owner_id**: the new owner that the FTs are being transferred to. - **amount**: the number of tokens transferred. - *Optional* - **memo**: an optional message to include with the event. **Minting events**: - **owner_id**: the owner that the FTs are being minted to. - **amount**: the amount of FTs being minted. - *Optional* - **memo**: an optional message to include with the event. ### Examples {#examples} In order to solidify your understanding of the standard, let's walk through two scenarios and see what the logs should look like. #### Scenario A - simple mint In this scenario, the Benji mints 50 FTs to himself and doesn't include a message. The log should look as follows. ```json EVENT_JSON:{ "standard": "nep141", "version": "1.0.0", "event": "ft_mint", "data": [ {"owner_id": "benji.testnet", "amount": "50"} ] } ``` #### Scenario B - batch transfer In this scenario, Benji wants to perform a batch transfer. He will send FTs to Jada, Mike, Josh, and Maria. The log is as follows. ```json EVENT_JSON:{ "standard": "nep141", "version": "1.0.0", "event": "ft_transfer", "data": [ {"old_owner_id": "benji.near", "new_owner_id": "josh.near", "amount": "1", "memo": "go team"}, {"old_owner_id": "benji.near", "new_owner_id": "mike.near", "amount": "9000"}, {"old_owner_id": "benji.near", "new_owner_id": "jada.near", "amount": "500"}, {"old_owner_id": "benji.near", "new_owner_id": "maria.near", "amount": "500"} ] } ``` ## Modifications to the contract {#modifications-to-the-contract} At this point, you should have a good understanding of what the end goal should be so let's get to work! Open the `src` directory and create a new file called `events.rs`. This is where your log structs will live. ### Creating the events file {#events-rs} Copy the following into your file. This will outline the structs for your `EventLog`, `FtMintLog`, and `FtTransferLog`. In addition, we've added a way for `EVENT_JSON:` to be prefixed whenever you log the `EventLog`. <Github language="rust" start="1" end="121" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/events.rs" /> ### Adding modules and constants {#lib-rs} Now that you've created a new file, you need to add the module to the `lib.rs` file. <Github language="rust" start="1" end="13" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/lib.rs" /> ### Logging the total supply minted Now that all the tools are set in place, you can implement the actual logging functionality. Since the contract will only be minting tokens at the very start when it's initialized, it's trivial where you should place the log. Open the `src/lib.rs` file and navigate to the bottom of the `new` initialization function. This is where you'll construct the log for minting. <Github language="rust" start="63" end="97" url="https://github.com/near-examples/ft-tutorial/blob/main/3.initial-supply/src/lib.rs" /> With that finished, you've successfully implemented the backbone of the events standard and it's time to start testing. ## Deploying the contract {#redeploying-contract} Since the current contract you have is already initialized, let's create a sub-account and deploy to that instead. ### Creating a sub-account Run the following command to create a sub-account `events` of your main account with an initial balance of 25 NEAR which will be transferred from the original to your new account. ```bash near create-account events.$FT_CONTRACT_ID --masterAccount $FT_CONTRACT_ID --initialBalance 25 ``` Next, you'll want to export an environment variable for ease of development: ```bash export EVENTS_FT_CONTRACT_ID=events.$FT_CONTRACT_ID ``` Using the build script, build the deploy the contract as you did in the previous tutorials: ```bash cd 2.define-a-token && ./build.sh && cd .. && near deploy $EVENTS_FT_CONTRACT_ID out/contract.wasm ``` ### Initialization {#initialization} Now that the contract is deployed, it's time to initialize it and mint the total supply. Let's create an initial supply of 1000 `gtNEAR`. Since it has 24 decimal places, you should put `1000` followed by 24 zeros in the total supply field. ```bash near call $EVENTS_FT_CONTRACT_ID new_default_meta '{"owner_id": "'$EVENTS_FT_CONTRACT_ID'", "total_supply": "1000000000000000000000000000"}' --accountId $EVENTS_FT_CONTRACT_ID ``` You can check to see if everything went through properly by looking at the output in your CLI: ```bash Scheduling a call: events.goteam.testnet.new_default_meta({"owner_id": "events.goteam.testnet", "total_supply": "1000000000000000000000000000"}) Doing account.functionCall() Receipt: BmD2hQJCUEMmvaUd45qrt7S55cewUXQSTPWT21Um3gXd Log [events.goteam.testnet]: EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_mint","data":[{"owner_id":"events.goteam.testnet","amount":"1000000000000000000000000000","memo":"Initial token supply is minted"}]} Transaction Id BrEBqE9S3tTBcgDUU6ZyszjAbaR4wkPyEN1viYKaXpgh To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/BrEBqE9S3tTBcgDUU6ZyszjAbaR4wkPyEN1viYKaXpgh '' ``` You can see that the event was properly logged! ### Querying Supply Information {#testing} You can now test if your view functions work properly. First, try to query for the total supply. ```bash near view $EVENTS_FT_CONTRACT_ID ft_total_supply ``` This should return an output similar to the following: ```bash '1000000000000000000000000000' ``` Hurray! Now you can check if the balance of the owner account works properly. If you call the following function, it should return the same number as the total supply. ```bash near view $EVENTS_FT_CONTRACT_ID ft_balance_of '{"account_id": "'$EVENTS_FT_CONTRACT_ID'"}' ``` Returns: ```bash '1000000000000000000000000000' ``` If you query for the balance of some other account, it should return `0`. ```bash near view $EVENTS_FT_CONTRACT_ID ft_balance_of '{"account_id": "benjiman.testnet"}' ``` ## Viewing FTs in the wallet {#viewing-fts-in-wallet} Now that your contract implements the necessary functions that the wallet uses to pickup your contract and display the FTs, you should be able to see your tokens on display in the [balances tab](https://testnet.mynearwallet.com/). <img width="65%" src="/docs/assets/fts/filled-fts-in-wallet.png" /> 🎉🎉🎉 **This is awesome! Go team!** 🎉🎉🎉 You can now see your very first fungible tokens in the wallet! ## Conclusion Today you went through and created the logic for minting a total supply. You then implemented some of the core standard logic and the [events standard](https://nomicon.io/Standards/Tokens/FungibleToken/Event). You created events for [minting](#modifications-to-the-contract) FTs on initialization. You then deployed and [tested](#testing) your changes and saw your very first FTs in the wallet! In the next tutorial, you'll look at the basics of registering accounts so that they can transfer and receive FTs.
NEAR Protocol Awarded the Climate Neutral Product Label NEAR FOUNDATION April 16, 2021 Post by Yessin Schiegg Builders on NEAR, join us and offset your carbon footprint! How can a decentralized blockchain that uses energy be climate neutral? – It can, by a commitment to measure, reduce, and offset its carbon footprint with green projects. NEAR Protocol has been awarded the Climate Neutral Product Label from South Pole. We, as human beings, are inherently a threat to our planet’s climate by emitting carbon dioxide (CO2) and other greenhouse gases. However, by making the right choices, we can create systems that reduce and even remove emissions and preserve a healthy environment. A tribe that plants more trees than it chops down may claim climate neutrality, even though its members are making fires. To sustain a healthy climate, we need to reach a net-zero level of emissions which involves reducing emissions as much as possible and then removing the remaining emissions either through nature-based solutions or technological solutions that draw CO2 out of the air. Otherwise, the level of greenhouse gases in the world’s atmosphere continues to increase, leading to global warming. Technical carbon-capturing solutions are still rare and expensive. Currently, nature offers the only reasonably cost-effective carbon-capturing mechanism. Chlorophyll is the molecule that is vital for photosynthesis and renders our world green. It allows plants to absorb energy from light by capturing CO2 and emitting oxygen into the atmosphere. Planting trees is a great solution, but it is wiser and less expensive to reduce carbon emission in the first place. Significant areas to start reducing carbon emissions are the systems that we control ourselves. If we cannot reduce our own carbon footprints, we can reduce the carbon footprint in other systems. For example, an airline can’t eliminate its carbon footprint with today’s technologies. Therefore, the airline could reduce the CO2 production by replacing the combustion engine-powered shuttle systems of its airports with green alternatives powered by renewable energy. If it becomes prohibitively expensive to reduce the carbon emissions in a particular system, resources can be transferred to another system to pay for the necessary reduction. This is essentially how carbon offsetting functions. Saving the climate is not a matter of faith, as many believe in error. It’s a matter of science and commitment. Science helps us set the necessary targets, which we reach by measuring, reducing, removing, and offsetting carbon emissions. Measuring a company’s carbon footprint is not easy and never perfect. It’s nevertheless a great start to begin to understand the impact of your company on nature. The commitment to improve our situation then helps deploy the resources required to bring an emissions balance to our planet. For a decentralized protocol like NEAR, it does not matter that not every participant is carbon neutral, but the network should be carbon neutral as a whole. NEAR Foundation engaged South Pole, the leading low-carbon project developer, and climate solutions provider, to measure NEAR Protocol’s carbon footprint and meet its climate neutrality commitment. By offsetting the first year’s emissions by supporting tree-planting projects and seeking to reduce avoidable emissions until the second accounting year, NEAR achieved South Pole’s Carbon Neutral Product Label 2021. The three green projects supported by NEAR are Kariba Forest Protection, Vegachi Forest Restoration, and Afognak Forest Carbon, as listed here. South Pole assessed NEAR Protocol’s carbon footprint by considering the emissions of NEAR Foundation, the Members of NEAR’s Core Collective, the NEAR Validators, and the use phase of the Protocol (NEAR users initiating transactions). Following the Greenhouse Gas Protocol Standard, the scope of the footprint accounting encompassed both direct and indirect emissions associated with the NEAR Protocol: everything from electricity use, heating, and cooling, to purchased goods and services such as hardware and cloud services, to generated waste as well as travel, commuting and teleworking activities. Data that was not centrally available was surveyed, and South Pole critically reviewed the feedback and data before NEAR’s carbon footprint was calculated from these inputs. A surprise was that business travel and commuting by the Core Collective Members accounted for most of NEAR Protocol’s carbon emissions. Simultaneously, the use phase, namely the online activity around transaction initiation, constitutes only a tiny fraction of the footprint. The emissions from validator activity play a significant role for NEAR’s indirect emissions relative to other categories. However, this needs to be understood in the light of an overall small footprint due to the advantages of a proof-of-stake protocol instead of proof-of-work. While NEAR’s footprint can be expected to increase with future scaling, both validator activity and use phase can be expected to stay by far below the enormous climate footprint of proof-of-work networks. This finding, therefore, supports the notion that proof-of-stake offers a more climate-friendly alternative to proof-of-work. The quantification of NEAR’s first footprint was done to the best available methodological knowledge. Due to the early stage of performing this for proof-of-stake blockchains, some future changes can be anticipated, and to be on the safe side, NEAR decided to compensate a bit more than was calculated by South Pole. By pioneering climate-friendly solutions, NEAR Protocol attracts like-minded people who are seeking to commit to improving the climate too. While doing your transactions on the NEAR Protocol is offsetting CO2 already. But we are looking at innovative ways to take it a step further so that every project building on NEAR can easily measure and offset its carbon footprint! Plenty of ideas are emerging, and separate projects are currently being formalized. One of them could be very positive for the climate: With the upcoming release of the NFT platform Mintbase on NEAR, crypto artists will create NFT art pieces that thematize South Pole projects. The artists will then auction the NFTs off, and a large part of the proceeds will go directly to the CO2 compensation projects in developing countries. These projects are results-based, so a project only gets paid for its emission reduction once measured and verified by an independent 3rd party auditor. If you would like to build on NEAR Protocol while offsetting your CO2 footprint, participate as an artist in the NFT project, or have an idea for any climate-friendly initiative, please reach us at [email protected]. We look forward to discussing with you how blockchain technology can help improve the world.
NEAR and Dropt to Revolutionize Loyalty and Engagement NEAR FOUNDATION January 19, 2023 NEAR Foundation is excited to announce a new partnership with Dropt, focused on embedding Web3 technologies into customer loyalty and engagement programs. With ownership and interoperability being critical components in the next generation of the customer experience, Dropt chose to build on NEAR. Its compelling tech stack and powerful tooling offer Dropt the ideal foundation for delivering these features at scale and redefining “frictionless onboarding”. With 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. Customers simply use apps and sites just as they do today, but with new NFT-powered features. NEAR and Dropt believe this is the key to mass adoption. Users are not interested in what is happening in the background—they simply want a fun experience that is engaging and rewarding. For one of its first integrations, Dropt will be partnering with a NBA championship team, led by one of the most dominant players in the world. Blockchain mechanics shift the paradigm for customer engagement By introducing NFTs to the customer journey, brands immediately integrate an incentive structure into the customer experience that elevates participation and engagement like never before. Branded marketplaces, where customers can interact with tokens, give users the ability to monetize their engagement with a brand.”With Dropt, NFTs can feature different kinds of perks and benefits. In this way, customers are better aligned with the brand’s and naturally become true evangelists. A changing landscape In an era where customer expectations are evolving and acquisition costs are rising, Dropt’s highly curated experiences enable brands to exceed these expectations. Let’s face it, loyalty is stale. Consumer expectations are shifting—people want to align themselves with brands that connect with authenticity and make consumers feel like part of a community. Dropt transforms the loyalty experience into a deeper, more community-based level of engagement, enabling brands to better connect with their communities. This not only modernizes how brands engage in this digital era, but also creates new acquisition channels. To capitalize on this opportunity, NEAR Foundation and Dropt believe user experience is vital. It’s unrealistic to expect customers to change their behavior, which is why Dropt and NEAR are working alongside cutting-edge authentication and gamification partners to build a web that’s both familiar and brings the best of what Web3 has to offer. Dropt is confident that in partnering with the Foundation, mass adoption is NEAR.
--- title: Contributing to NEAR sidebar_label: 'Contributing To NEAR' sidebar_position: 1 --- # Contributing to NEAR :::info on this page * NEAR welcomes contributions from interested individuals * There are numerous open issues across repositories, and bounties are regularly posted * For developers, there is a Developer Contributions walkthrough that explains the contribution flow * The contributor program is available for those who want to get formally involved with continuous contributions * Contributors in the program get early access to new bounties, exclusive support, and feedback, and can earn tokens for their contributions * There are several developer channels available to ask questions NEAR's GitHub repositories are available for exploration ::: ## Overview Welcome! If you are in this repository, you are probably interested in contributing to NEAR's development. We have tons of open issues across repositories and regularly post [bounties](https://github.com/near/bounties). To learn more about the contribution flow for developers, please head over to the [Developer Contributions walkthrough](development/how-to-contribute.md). ## Contributor Program {#contributor-program} If you like contributing to NEAR and would like to get formally involved with continuous contributions, the [contributor program](https://pages.near.org/ecosystem/community/) is the right place for you. As part of the NEAR contributor program - You are the first to hear about new bounties - You are invited to our bi-weekly engineering calls with contributors - You receive exclusive support and feedback and you have the option to earn tokens for your contributions. <!-- ## Example Contributions {#example-contributions} --> #### Testing {#testing} If you are interested in testing our documentation, guides and developer tools, head over to the following pages. We would love to jump on a call and get to know your insights, or you can submit directly issues in the respective repositories on GitHub. For more information on where and how to file issues, please head over to our [developer contribution section.](development/how-to-contribute.md) - [Developer tools](https://docs.near.org/develop/welcome) - [Local development](https://near-nodes.io/validator/running-a-node) - [Introduction to near-api-js](https://docs.near.org/develop/integrate/frontend) #### Development {#development} - We are always looking for more example applications. If you are interested in building a dApp, we would love to help you along the way and see the final result. - Create a walk-through example of how to use the [NEAR-explorer](https://docs.near.org/tools/indexer-for-explorer) or highlight different aspects of the [NEAR CLI](https://docs.near.org/tools/near-cli). An example walkthrough of the wallet can be found on the [Creating a NEAR Wallet](overview/tokenomics/creating-a-near-wallet.md) page. Please submit your example to the [docs repository](https://github.com/near/docs). #### You can always ask questions on either of our developer channels {#you-can-always-ask-questions-on-either-of-our-developer-channels} - [StackOverflow](https://stackoverflow.com/search?q=nearprotocol) - [Telegram Developer group](https://t.me/neardev) - [Discord](http://near.chat/) Checkout our [GitHub repositories](https://github.com/near). :::note Got a question? **[Ask it on StackOverflow!](https://stackoverflow.com/questions/tagged/nearprotocol)** :::
An Industry Set For Change: A Future Outlook on Blockchain Adoption, Usability, and Scalability in Modern Times COMMUNITY January 15, 2019 What is Programmable Money? Our current system of monetary exchange has evolved over time to accommodate new marketplace demands and technological advancements, giving financial inclusion to even the most remote villages on earth. Predating the era of tangible fiat currencies, the idea of an ecosystem reliant upon bartering was most commonly used to facilitate trade between two or more parties that were in the same geographical area, where the price of the goods or services being traded can be negotiated in person. It wasn’t until the advent of minted coins, most commonly attributed to Lydian societies (now modern-day Turkey) where an exchange of goods can be quantified based on a widely recognized set of standards. This store of value enabled ancient societies to expand well beyond their territorial boundaries and engage in trade with empires across the globe. New forms of monetary transmission have allowed civilizations to become more interdependent and the reliance on cross border trade has fueled societies to grow, people to live outside of major metropolitan areas, and cultures to assimilate with one another. Our modern-day system of exchange, while technologically more advanced, is no different in principle than how ancient societies functioned. A good or service is placed in the marketplace and a price is set, for which a buyer can either accept, reject, or counter the offer. If the two parties agree on a mutually satisfactory price, the transaction is complete. This form of trade is conditional upon sellers providing quality goods and buyers using authentic forms of payment. However, the risk of bad actors using deceit and engaging in fraudulent behavior cannot be fully controlled in open marketplace transactions whereby those looking to deceive can offer counterfeit goods in return for authentic currencies. Modern trading platforms such as eBay and Amazon have security measures in place to facilitate transactions where payment of goods are not released to the seller until confirmation of goods in transit, partially combating fraudulent behavior, however, what happens if the goods in transit are fraudulent themselves? A bad review can be left for the seller, which can result in the reporting and shutdown of a seller account, but that only solves part of the problem and the buyer is often times left at a loss. With recent advancement in marketplace architecture, the concept of programmable money has allowed transactions to not only be quantifiable (as in the case of eBay and Amazon) but also verifiable and secure. Goods and payment terms can be locked up in escrow where neither party is given access their piece of the transaction until authenticity is provided (through notary services or trusted 3rd parties) and goods have changed hands. A common example can be seen in the sale of a car. Jack is looking to buy a car from Bob, however, Jack wants to make sure the car passes the proper emissions tests, does not have structural damage, and is delivered to an address provided. Jack puts in escrow the amount that has been negotiated with Bob for the car and upon a mechanic signing off on all relevant tests and a shipping agent delivering the car to the proper address, the payment terms are then released to the seller. Programmable money, or the act of creating exchange based transaction conditions, gives the payer and payee greater parameters when engaging in trade and conditions such as time, value, and expertise can be predefined as a result of a valid trade and stored through electronic measures. In theory, creating a system of predefined marketplace conditions where both the buyer and seller have transactional guarantees makes sense, but the logistical inefficiencies of implementing such a system have barred mass adoption to date. The DAO is a good example of what can happen when the direct access to funds transfer is controlled only by using the software. Through exploitation of weak security code, hackers were able to ciphon off about 80 million dollars in Ethereum’s native currency, Ether, due to the lack of features that frameworks supporting critical systems would ordinarily have. It is possible that inefficient or missing documentation was the result of the hack, where if properly provided developers could have spotted the critical flaws in advance, but when software is only the control agent for funds transfer, security is most critical. Technology development around programmable money has come a long way since the DAO hack of 2016 and major financial institutions such as IBM have started to make substantial investments into distributed ledger technology. In fact, IBM’s recent release of their programmable money whitepaper and platform World Wire, notes that 91% of banks surveyed in the report are making some kind of investment into blockchain technology as a facilitation medium for deposit transfers, however, the entire monetary transmission supply chain won’t be completely decentralized. It is argued that while there is substantial efficiencies that can be gained by using programmable money, critical functions such as ID management, monitoring transactions for fraud, and preventing/reporting money laundering activities will still be manual checks using trusted 3rd party agents. Scaling Programmable Money It seems as if this industry is heading towards using a blend of software and trusted 3rd parties to facilitate trade, however mass adoption of programmable money will only come from scalable protocol layers that allow for decentralized consumer applications to gain popularity. A great medium article by Newtown Partners (with contributions from Civic) discusses Decentralized Applications, commonly known as DApps, and their value chain. Application layers enable a relationship with the end user (ie consumer-facing services and interactions), application protocols facilitate the internal token economy, and base/processing protocols dictate governance of the organization and facilitate the underlying network. For consumer-facing solutions to work, all parts of the DApp value chain must work harmoniously so that value is captured across multiple layers. It is discussed that for mass DApp adoption, user aggregation of application layers is the only way to scale DApps and bring value to the underlying protocol. In some centralized manner, all the current infrastructure needed to build a DApp has already been created, thus, capturing a majority user base is the only way to effectively scale blockchain products. A DApp needs to be able to bootstrap and generate genuine user level interest before value can be attributable to the underlying protocol. But before a DApp can be built, it must work using already existing infrastructure (such as AWS), work with an established blockchain protocol layer (such as Bitcoin, Ethereum, Stellar, etc.) that can support its functional needs, or concurrently build with a new protocol layer. Interestingly enough, the rise of protocol layers followed by mass adoptable consumer applications is not a new trend and in fact, occurred back in the early 90’s. When Tim Berners-Lee sought to build an application protocol layer for distributable and collaborative hypermedia information systems, the result was HTTP, or what has become the genesis of document and information sharing. Berners-Lee created a system where users can click and link resources for public access, consumption, and publication over the internet. He built the first web server, which leads to the rise of the web browser accessing, reading, and displaying the shareable content. Companies such as Netscape/Mosaic, Opera, and browsers, such as Lynx and Internet Explorer, were among the first to capitalize on this trend and soon after, consumer application development started to occur using HTTP to share content and web browsers to display content. Today, virtually all consumer applications use some form of HTTP (such as Amazon, Facebook, LinkedIn, etc.) with many organizations taking advantage of the numerous other protocol layers out there. With the blockchain industry still in its infancy, we are seeing many of the same trends as the early 90’s to build protocol layers that can eventually support mass adoptable consumer applications. Problems with Blockchain Adoption The blockchain developer ecosystem is growing: from October 2017 to October 2018, solidity package downloads tripled, the number of new decentralized applications released per week doubled, and OpenZeppelin (popular framework for smart contract development) downloads almost grew tenfold (source). Developers building on platforms are motivated to build on a blockchain as long as the platform allows them to acquire users, scale across the users and monetize their applications. When it comes to end-user acquisition adoption and the ability of current blockchains to scale applications across the larger user base, the existing solutions fall short of their promises. Usability What’s the problem with user acquisition? The user coming from web 2.0 to blockchain faces a lot of challenges with basic concepts of this new paradigm. The biggest problem or friction is that you have to pay for every transaction, even if the transaction is not monetary. This means that in order to create their first transaction, the users have to go through multiple steps, involving installing software, creating an account and funding the account. In order to fund the account, the user would need to convert his fiat (USD) into cryptocurrency using some exchange. This usually involves some identification and sharing of personalized information with a centralized entity — which ruins the purpose of a decentralized environment. This clearly slows down adoption, since most people are not willing to share personalized information in the blockchain space, whereas sharing of personal information for mobile application usage is common practice. At NEAR Protocol, we use a different transaction model: instead of paying per transaction, we use a rate limiter. Essentially, the user can send some amount of the transaction based on a per unit of time while the rate limiter is backed by bandwidth staking. Bandwidth stake doesn’t have to come from the user and other accounts or contracts can stake on behalf of the user. This allows new users to create transactions without having any money in their account. This means that a person who just opened the app for the first time can start using it almost immediately. How does this work? When the user first visits the website, we either use their existing identity (similar to Metamask) or create an ephemeral account for them as a temporary identity. This ephemeral account can be used and later converted to a real account. The keys can be stored in local storage and the application can temporarily stake on behalf of this new account after some verification to prevent Sybil attack (for example: checking a phone number or some other form of login). After some time, the application’s stake is returned back to its account and can be reused again. In other words, NEAR solves the issue of the user having to fund an account before using the application. Needless to say, it’s a major point of friction today: in popular decentralized applications, the dropoff rates for sign-ups go up to 97–99%. In other words, there is interest and demand, but users today can’t use apps due to monetary reasons. While it’s now possible for a user to conduct their very first transaction in a decentralized application without any monetary support, we now look at potential security issues a user may face to keep their new account secure. In most blockchain protocols, a users identity is linked to the user’s public key or at least a unique private key. This means if the private key is exposed, you have to re-create your account with a new private key and move everything to a new account (which might not even be possible due to fact that state data could be stored in other applications). Additionally, the private key cannot be trusted to be stored with other parties since the malicious third party can duplicate the key and get possession of user’s funds. At NEAR Protocol, the user and contract identity is not a computer generated public key. Instead, it’s an alphanumeric string (some additional characters) such as a domain name, phone number, email or just a name. This makes it easy for people to read and remember account IDs. This allows an account to have a variable number of public keys associated with it and transferring accounts by swapping public key. This can be used in at onboarding phase, an application can create an account on your behalf and then transfer ownership to the user when requested. A user would need to only provide the public key and receive full ownership of such an account. Importantly, this account can now be used with other applications. Another use case is allowing each device to have their own key pair. Then when new device is added, the current device can just authorize new public key and add it to the account. This way, private key doesn’t need to transfer between devices or even be seen by the user. In essence, NEAR Protocol allows developers to onboard new users without any additional software (using the concept of ephemeral accounts and bandwidth staking), while also allowing more advanced end users to use the application in a fully decentralized manner. Scalability What is the problem with the current base protocol scalability? From NEAR Protocol’s sharding blog post: “It is well-known that Ethereum, the most used general purpose blockchain at the time of this writing, can only process less than 20 transactions per second on the main chain. This limitation, coupled with the popularity of the network, leads to high gas prices (the cost of executing a transaction on the network) and long confirmation times; despite the fact that at the time of this writing a new block is produced approximately every 10–20 seconds while the average time it actually takes for a transaction to be added to the blockchain is 1.2 minutes, according to ETH Gas Station. Low throughput, high prices, and high latency all make Ethereum not suitable to run services that need to scale with adoption.” Why are current solutions so slow? It’s because each node does all of the work for the system: processing transactions, relaying the validated transactions and completed blocks to other nodes, and storing states and histories of the system on each node individually. Sharding in NEAR Protocol Sharding of blockchain (which includes sharding of state and processing) solves these limitations because nodes in each shard are building their own blockchain that contains transactions that affect only the local part of the global state that is assigned to that shard. Therefore, the validators in the shard only need to store their local part of the global state and only execute, and as such only relay, transactions that affect their part of the state. This partition linearly reduces the requirement on all compute power, storage, and network bandwidth. For an in-depth discussion on blockchain sharding, check out our other blog here. Needless to mention, sharding introduces some additional complexities and therefore new problems, with many of them being unsolved as of now. We’ve covered such problems in this blog post. However, an important additional benefit is that higher throughput will decrease each transaction cost which will make it cheaper for everyone to use blockchain. Industry Set For Change With scalable application and base protocol layers in the works, there has been a rise of consumer-facing applications that are trying to capture aggregate value with users to solve real-world use cases within the financial sector. Developing fractionalized lending platforms (ie asset tokenization platforms) where users can own shares of historically illiquid assets has grown in popularity over the last couple of years. While not directly related to the blockchain space, companies such as Realty Shares, Fund Rise, Lending Home, and Cadre are among the numerous companies that are taking a distributed approach to investing. From the consumer side, capital can be invested into a variety of real estate deals with no more than a small minimum buy-in while all back-office tasks (legal, underwriting, etc.) are taken care of. Furthering the push to capture consumer-based market share, there has also been a rise of mobile-first financial planning and investment platforms seeking to provide users access to stocks (and cryptocurrencies) with the push of a button and with no transaction fees. Robinhood is among the leaders seeking to provide value to the average investor with more than 4 million user account registrations and a valuation of $5.6 billion. Traditional investment platforms are paving the way for consumer-facing blockchain products to grow and it’s only a matter of time before using programmable money to guide the purchase and sale of fractionalized partnership, real estate, or alternative investment interests can come to fruition. While companies such as Harbor and Trust Token are making waves to further these goals, it seems as though the days of requiring large minimum buy-ins, having access to deal flow, or locking up capital may be a thing of the past as protocol/application layers are working together to garner user adoption and appeal to the average consumer. Conclusion As of the time of this writing, nobody knows what the initial blockchain use cases with mass adoption will look like. Since monetary transactions are baked into the chain, the first applications will likely involve financial transaction services, however, the potential for adoption within other vertices are still being explored. Blockchain developments reliant upon security and trust have created the idea of fungible tokens, leading to native use cases such as CryptoKitties. But once the technology is far enough along to facilitate more cost-effective transactions, we might see completely new applications being adopted. In this blog post, we’ve covered the history of monetary systems as well as how programmable money has allowed transactions to not only be quantifiable (as in the case of traditional tech marketplaces, like eBay or Amazon), but also verifiable and secure. We then looked at how adoption might come from better approaches to the current usability and scalability models that can help blockchain technology pave the way for an industry set for change. With the right public and private capital support, tokenized investment funds can replace traditional investment platforms that may help consumer-facing blockchain products to grow in the financial services sector. We see it as only a matter of time before using programmable money will guide the purchase and sale of fractionalized partnership, real estate, or alternative investment interests that can be readily available for consumer use. Outro NEAR Protocol builds a sharded general purpose blockchain with a huge emphasis on usability. If you like our write-ups, follow us on Twitter to learn when we post new content: Twitter If you want to be more involved, join our Discord channel where we discuss all technical and non-technical aspects of NEAR Protocol, such as consensus, economics, and governance: Discord Lastly, please subscribe to our newsletter. We send bi-weekly updates, and this is the best channel to learn about our progress towards the launch of NEAR Protocol. https://upscri.be/633436/ Thanks to Evgeny Kuzyakov (Linkedin & Medium), Mitch Somach (LinkedIn & Medium) & Random Bares for providing a bulk of the thought leadership on this blog post.
--- sidebar_position: 2 --- # Contract Mutability Contract state mutability is handled automatically based on how [`self`](https://doc.rust-lang.org/std/keyword.self.html) is used in the function parameters. Depending on which is used, the [`#[near_bindgen]`](../contract-structure/near-bindgen.md) macro will generate the respective code to load/deserialize state for any function which uses `self` and serialize/store state only for when `&mut self` is used. The following semantics are consistent for all [public methods](public-methods.md). ## Read-Only Functions To access state immutably, where the existing state is not overwritten at the end of the transaction, you can use `&self` or `self` as a parameter. Both of these will generate the same code to load and deserialize the state into the structure and call the function, but the difference is that `&self` will just pass a reference to this variable into the function where `self` will move the variable into the function. For more information about `&self` versus `self` see [this section in the Rust book](https://doc.rust-lang.org/stable/book/ch05-03-method-syntax.html?highlight=capture%20self#defining-methods). Here are some examples of using each: ```rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, Default)] pub struct MyContractStructure { integer: u64, message: String, } #[near_bindgen] impl MyContractStructure { pub fn get_values(self) -> (u64, String) { (self.integer, self.message) } pub fn log_state_string(&self) { near_sdk::env::log(self.message.as_bytes()); } } ``` There is no simple guideline that works for every case, but here are some core reasons on when to use each: ### self (owned value) Moving the owned value into the function can be useful if `self` itself or its fields are moved within the function, as it will remove the need to `Clone`/`Copy` the data. Example: ```rust /// View method. More efficient, but can't be reused internally, because it consumes self. pub fn get_owner_id(self) -> AccountId { self.owner_id } ``` ### &self (immutable reference) This should be used when the contract state is only read or the function is re-used by other methods which do not have [ownership](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) of the variable. This can also be useful if the struct uses a lot of memory, to avoid moving a large amount of data into the function scope rather than just referencing it. Example: ```rust /// View method. Requires cloning the account id. pub fn get_owner_id(&self) -> AccountId { self.owner_id.clone() } ``` ### Returning derived data Some less common cases may intend to use read-only methods to return objects that are derived from modified objects stored in state. Below is a demonstration of this concept: ```rust /// View method that "modifies" state, for code structure or computational /// efficiency reasons. Changes state in-memory, but does NOT save the new /// state. If called internally by a change method, WILL result in updated /// contract state. pub fn update_stats(&self, account_id: AccountId, score: U64) -> Account { let account = self.accounts.get(&account_id).unwrap_or_else(|| env::panic_str("ERR_ACCT_NOT_FOUND")); account.total += score; account } ``` ## Mutable Functions Mutable functions allow for loading the existing state, modifying it, then rewriting the modified state at the end of the function call. This should be used for any transaction which modifies the contract state. Note that the serialized contract data is stored in persistent storage under the key `STATE`. An example of a mutable function is as follows: ```rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, Default)] pub struct MyContractStructure { integer: u64, } #[near_bindgen] impl MyContractStructure { pub fn modify_value(&mut self, new_value: u64) { self.integer = new_value; } pub fn increment_value(&mut self) { self.integer += 1; } } ``` ## Pure Functions These functions do not use `self` at all, and will not read or write the contract state from storage. Using public pure functions will be very rare but can be useful if returning data embedded in the contract code or executing some static shared logic that doesn't depend on state. Some examples of pure functions are as follows: ```rust const SOME_VALUE: u64 = 8; #[near_bindgen] impl MyContractStructure { pub fn log_message(/* Parameters here */) { near_sdk::log!("inside log message"); } pub fn log_u64(value: u64) { near_sdk::log!("{}", value); } pub fn return_static_u64() -> u64 { SOME_VALUE } } ```
--- id: transaction-anatomy title: Anatomy of a Transaction --- A transaction is a request from a user to the network to perform a set of actions. To create a transaction, the user must specify the following fields: - `Signer`: the account that signs the transaction - `Actions`: the set of actions to be performed (see bellow) - `Receiver`: the account on which to perform the actions In addition, a transaction has the following fields to ensure its integrity and validity: - `PublicKey`: the public key used to sign the Transaction (so the network can verify the signature) - `Nonce`: a number that is incremented for each transaction sent by the `Signer` - `BlockHash`: the hash of a recent block, to limit the time-validity of the transaction Users create transactions and sign them with their private keys. Then, the **transaction and its signature** are broadcasted together to the network, where they are validated and processed. :::tip Each transaction has exactly one `Signer` and `Receiver`, but can have multiple `Actions` ::: --- ## Actions Each transaction can have **one or multiple** `Actions`, which are the actual operations to be performed on the `Receiver` account. There are 9 types of actions that can be performed: 1. `FunctionCall`: to invoke a function on a contract (optionally attaching NEAR to the call) 2. `Transfer`: to transfer tokens to another accounts 3. `DeployContract`: to deploy a contract in the account 4. `CreateAccount`: to create a new sub-account (e.g. `ana.near` can create `sub.ana.near`) 5. `DeleteAccount`: to delete the account (transferring the remaining balance to a beneficiary) 6. `AddKey`: to add a new key to the account (either `FullAccess` or `FunctionCall` access) 7. `DeleteKey`: to delete an existing key from the account 8. `DelegateActions`: to create a meta-transaction 9. `Stake`: special action to express interest in becoming a network validator For example, `bob.near` can bundle the following actions in a single transaction: - Create the account `contract.bob.near` - Transfer 5 NEAR to `contract.bob.near` - Deploy a contract in `contract.bob.near` - Call the function `init` in `contract.bob.near` The `Actions` are executed in the **order they are specified in the transaction**. If any of the **actions fails**, the transaction is discarded and none of the actions take effect. :::warning One Receiver Notice that all actions are performed on the same account. It is **not possible** to perform actions on multiple accounts in a single transaction, because transactions can have **only one receiver** :::
--- id: oracles title: Price Oracles --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Oracles are smart contracts that enable you to query the current price of an asset. Since smart contracts cannot connect to internet and pull information, Oracles rely on having someone constantly updating their prices. Because of that, be mindful when using an oracle that there might be a delay between the market's latest information and the Oracles data. Oracle contract's are not standardized. We will here list different providers and how to use their Oracle as they are built. --- ## Price Oracles - Account: **priceoracle.near** | **priceoracle.testnet** - Creator: [NearDefi](https://github.com/NearDeFi) - Smart contract: https://github.com/NearDeFi/price-oracle - Bot to fill contract: https://github.com/NearDeFi/near-price-oracle-bot --- ## Query Assets <Tabs> <TabItem value="🖥️ CLI" label="🖥️ CLI"> ```bash near view priceoracle.near get_assets ``` </TabItem> </Tabs> <details> <summary>Example response</summary> ```json [ [ 'wrap.near', { reports: [ { oracle_id: 'thorinoracle.near', timestamp: '1669795900809627816', price: { multiplier: '17030', decimals: 28 } }, { oracle_id: 'npo-aurora.near', timestamp: '1706631791706032710', price: { multiplier: '30641', decimals: 28 } }, { oracle_id: 'gloriafoster.near', timestamp: '1706631808550973590', price: { multiplier: '30666', decimals: 28 } }, ... ``` </details> --- ## Get Assets Price <Tabs> <TabItem value="🖥️ CLI" label="🖥️ CLI"> ```bash near view priceoracle.near get_price_data ``` </TabItem> </Tabs> <details> <summary>Example response</summary> ```json { timestamp: '1706631861981947371', recency_duration_sec: 90, prices: [ { asset_id: 'wrap.near', price: { multiplier: '30702', decimals: 28 } }, { asset_id: 'aurora', price: { multiplier: '235662', decimals: 20 } }, { asset_id: 'meta-pool.near', price: { multiplier: '38770', decimals: 28 } }, { asset_id: 'linear-protocol.near', price: { multiplier: '36432', decimals: 28 } }, ``` </details> :::tip Divide the returned `multiplier` by `10000` to obtain the price in USD. :::
--- title: Treasury Playbook description: Current treasury best practices for venture-backed startups --- # Treasury Playbook _This document is intended to be a living playbook for current treasury best practices for venture-backed startups. It draws from [FirstMark’s](https://firstmarkcap.com/) collective experience through multiple cycles, as well as our [CFO Guild](https://www.guilds.cc/), an invite-only community that brings together 400+ CFOs from the venture-backed ecosystem._ _The guidelines presented herein are intended exactly as that; guidelines. We encourage all companies to work in close concert with their Board and Legal counsel to develop the right treasury approach for your business. Comments? Please reach out to [dan@firstmarkcap.com](mailto:dan@firstmarkcap.com)._ ## TREASURY FOR STARTUPS {#treasury-for-startups} For early-stage companies (or those with roughly 1-2 years of cash runway), some basic guiding principles for treasury are as follows: * **Operating cash**: maintain 90 days of operating cash in multiple banks including a [money center bank](#bookmark=id.10fyjc4dzy20) at all times; this is capital used for payroll, vendors, etc. * **Near-term cash:** additional near-term operating cash (~1 year) held across one and ideally two incremental banking relationships, at least one of which should be with a second money center bank. This cash should be held in liquid accounts: (interest-bearing) savings/checking, money market, or insured cash sweep (ICS) accounts. * **Additional cash:** any cash in excess of the above (i.e., cash not needed in the next ~12+ months) can be invested for yield. In a company’s early stages, this will be in similar safe and yield-bearing accounts (money market, ICS, or treasuries). Investments are typically executed through these same money center banks or asset managers like Fidelity, Morgan Stanley, and Schwab. _Note: it is important that you have the most direct access to investments possible; [see below for more](#bookmark=id.1k55o36ic5xt)._ Of course, a company should calibrate its treasury approach based on both its total cash position and staffing. For Seed-stage companies, doing much beyond the first two steps above is unnecessary and a poor use of founders’ time. Early stage companies can execute all three principles with 1-2 money center bank relationships, coupled with services offered through the likes of [Mercury Treasury](https://mercury.com/treasury); these trade potential yield for “one-click” services that federate deposits across multiple insured and interest-bearing accounts. Note that the selection of your primary relationships may be influenced by your credit relationships; i.e., many lenders require companies to meet deposit requirements as a term of their credit lines. ``` Making it Concrete: A Real-World Example Let's use the example of a Series A startup that has $10M of cash, with $500K of net operating expenses each month: Operating cash: $1.5M in a JPMorgan Chase checking account Near-term cash: $4.5M across two incremental accounts, Wells Fargo and First Republic Invested cash: $4.0M directly invested in laddered treasuries through Fidelity ``` ## Definitions for those New to Treasury _Money Center Bank_: these are banks that access capital primarily through money markets instead of deposits. The four highest-profile of these are JP Morgan Chase, Bank of America, Wells Fargo, and Citibank. _Insured Cash Sweep_: product that federates deposits across multiple FDIC-insured bank accounts, in order to both insure your deposits while also giving you the opportunity to earn yield. Note that the pros of ICS products are to fully insure your deposit; while the risk is that, should an operating issue affect your primary bank, you may struggle to access the federated cash when you need it the most. [See below for additional detail](#bookmark=id.1k55o36ic5xt). ## FINANCIAL RISK MANAGEMENT FOR STARTUPS {#financial-risk-management-for-startups} Fundamentally, financial risk management for startups is as simple as asking “what if” questions about your business: “what happens if I lose access to my primary bank?”, “what happens if our payment processor goes down?”, and so on. In this vein, one of the top lessons of the 2023 SVB crisis was for companies to **understand where your assets are custodied.** In the context of treasury, a _custodian_ refers to an entity that officially holds a company’s cash or securities for safekeeping. Why does this matter? Because in 2023, many companies discovered that although their capital was invested directly in safe assets, like treasuries, those assets were held by a third-party entity _that companies did not have direct access to_. In practice, this meant that companies could not liquidate or transfer those assets without the explicit approval of SVB–making them useless in the midst of a potential cash crunch. While some were able to resolve issues with calls up and down the custodial chain, this is _not_ where to spend time in a crisis. #### To get ahead of this, leaders should: * **Have co-custody and/or relationships throughout the custody chain.** If your assets are custodied by a third party, make sure you have co-custody (i.e., can access, liquidate, and transfer assets without your investment advisor), or at a minimum, have active contacts at those entities. * **Think through timing implications**. Remember that many aspects of money management require time and processes that are out of your control. For example, the sale of assets may take 24 hours to settle; payroll may debited 48 hours in advance of employees’ getting paid; etc. Understand and plan ahead for the interplay of these timing constraints. * **Know the type(s) of risk you’re taking.** In the 2023 SVB crisis, startups experienced the consequences of exposure to Bank Risk; if you were invested in an ICS, you were (generally speaking) fine. In 2008, we saw Market Risk, as even “safe” money market fund traded down. Be thoughtful about where your money is stored, the type(s) of risk you’re taking, and how you’re mitigating that risk. The second major takeaway of the 2023 SVB crisis is to **plan ahead for the loss of critical financial infrastructure**. Depending on the maturity of your company, it’s irrational to think that you can or should have a full backup for every contingency. Even so, leaders should absolutely consider what it means to lose a critical piece of infrastructure. What will be the impact on your business, your customers, and your employees? How difficult or time-consuming will it be to replace that infrastructure? This helps you make an _active_ decision about whether to build hard or soft contingency plans. Finally, a handful of other tactics beneficial to leaders during times of turmoil and uncertainty: * **Cultivate multiple debt relationships.** While this adds friction, it also adds resilience * **Keep wire templates & controls up to date**. This is not something to revisit mid-crisis * **Pre-fund payroll.** Consider funding slightly ahead of payroll timelines to give you space. ## TREASURY AT SCALE {#treasury-at-scale} Companies that have raised significant capital (typically, those with more than two years of available cash) may seek additional investment options beyond basic treasuries or interest-bearing bank accounts. Note two important principles: first, no startup has ever “won” because of its treasury practices; the attention of founders and CFOs alike is best directed at the fundamentals of the business. Second, in a certain sense, a more refined investment strategy doesn’t make sense until the incremental yield generated by that strategy more than pays for itself, and therefore justifies the full-time attention of a Finance team member. Typically, the maturity of the treasury function follows this trajectory: * **Formal, Board-approved investment policy**: as a company matures, you will need to have a formal, Board-approved investment policy that explicitly states where excess cash is invested; what investment decisions can be made by company executives; and what investment decisions need Board approval. This will typically occur around the time you hire your [first CFO](https://firstmark.medium.com/your-first-cfo-a-playbook-for-success-in-year-one-9749b1719d7b). * **Non-sweep & treasury investments**: at larger scale, generating additional yield beyond that available through interest-bearing accounts, money market accounts, or treasuries becomes material. These investments typically involve a mix of the same assets already discussed in addition, e.g., corporate or municipal bonds; institutional asset managers like those at the money center banks (as well as Morgan Stanley, Fidelity et al) have experience developing investment portfolios to balance risk against additional yield. As a company matures to and beyond the public markets, the treasury function becomes far more sophisticated, with one or more team members dedicated to the practice. The playbook for that evolution is outside of the scope of this document. ## SVB DEBT LINES & ADDITIONAL CONSIDERATIONS {#svb-debt-lines-&-additional-considerations} One of the most important medium-term issues that many companies will face: _what happens to venture debt lines that companies have established with SVB? _The short answer is that, as of right now, we don’t know. But to prepare for all scenarios, companies are encouraged to: * **Be vigilant & deliberate about debt covenants**: as of now, it is unclear what entity will ultimately own your venture debt line. Therefore, it is important to be mindful and deliberate about covenants, since _the next holder of the debt may be looking for any reason to call back capital._ For example, companies that urgently moved cash in the midst of the SVB crisis may have arguably violated their covenants; and some of those companies are relying on a 10-day "cure period" explicitly written into the agreement. _In any case, your imperative is to understand the ins and outs of your specific agreement. _ * **Plan on a _net_ cash basis:** given near-term uncertainty, it is not prudent for companies to plan as if your venture debt line will be fully available. Therefore, all companies should plan on a net cash basis; i.e., if you hold $20M in cash and have drawn $5M of venture debt, plan your business as if you only have $15M of cash. * **Adopt lessons learned in future debt (re)financings**. What startups experience during the 2023 SVB crisis should inform new or refinanced venture loans. The simplest example: pushing for lower deposit requirements to continue to enable your banking diversification. _As of this writing, SVB is open for business–and wants your business–so now may present a window for amending your loan agreement._ Looking ahead, our intention is to make this a living, breathing guide of best practices–both evergreen best practices for a startup’s approach to treasury, as well as important lessons learned from 2023. ## BANKS & RELATIONSHIPS {#banks-&-relationships} _Note: If you reach out directly, please mention your affiliation to FirstMark as an investor or member of our Guilds community. If you have additional banks or contacts to recommend, please contact [dan@firstmarkcap.com](mailto:dan@firstmarkcap.com)._ <table className="treasuryPlaybookTable"> <tr> <td> <h3><strong>MONEY-CENTER BANK CONTACTS</strong></h3> <h4>Bank of America</h4> <p>Shawn M. Hoyer</p> <p><a href="mailto:shawn.m.hoyer@bofa.com">shawn.m.hoyer@bofa.com</a></p> <p>Rahul Baig</p> <p>MD | Venture Capital Coverage</p> <p>347.753.2692</p> <h4>Wells Fargo</h4> <p>MD | Venture Capital Coverage</p> <p><a href="mailto:rahul.baig@wellsfargo.com">rahul.baig@wellsfargo.com</a></p> <h4>JPMorgan Chase</h4> <p>See footnote<sup><a href="#notes">1</a></sup> for details</p> <p>Business Banking</p> <p><a href="https://www.jpmorgan.com/commercial-banking">jpmorgan.com/commercial-banking</a></p> <h3><strong>NON-MONEY CENTER BANKS</strong></h3> <h4>BNY Mellon | <a href="https://www.bnymellon.com/">bnymellon.com</a></h4> <h4>Brex | <a href="https://www.brex.com/product/business-account">brex.com</a></h4> <p>Shai Goldman</p> <p><a href="mailto:sgoldman@brex.com">sgoldman@brex.com</a></p> <h4>BridgeBank | <a href="https://www.westernalliancebancorporation.com/bridge-bank/">bridgebank.com</a></h4> <p>Greg Dietrick</p> <p>Sr Dr | Venture Capital</p> <p><a href="mailto:greg.dietrick@bridgebank.com">greg.dietrick@bridgebank.com</a></p> <h4>Capital One | <a href="http://capitalone.com">capitalone.com</a></h4> </td> <td> <h4>Charles Schwab | <a href="https://www.schwab.com/bank">schwab.com</a></h4> <h4>City National Bank | <a href="https://www.cnb.com/">cnb.com</a></h4> <p>Bill Sweeney</p> <p><a href="mailto:bill.sweeney@cnb.com">bill.sweeney@cnb.com</a></p> <h4>Comerica | <a href="https://www.comerica.com/business.html">comerica.com</a></h4> <p>Kevin Urban</p> <p><a href="mailto:kturban@comerica.com">kturban@comerica.com</a></p> <p>SVP & Market Manager</p> <h4>Fifth Third Bank | <a href="https://www.53.com/content/fifth-third/en.html">53.com</a></h4> <h4>First Republic | <a href="https://www.firstrepublic.com/">firstrepublic.com</a></h4> <p>Gary D. Farro</p> <p><a href="mailto:gfarro@firstrepublic.com">gfarro@firstrepublic.com</a></p> <p>Executive Managing Director</p> <h4>HSBC | <a href="https://www.hsbc.com/who-we-are/businesses-and-customers/commercial-banking">hsbc.com</a></h4> <p>Meghan Curtin</p> <p><a href="mailto:meghan.m.curtin@us.hsbc.com">meghan.m.curtin@us.hsbc.com</a></p> <p>Head of HSBC Ventures</p> <h4>Mercury | <a href="https://mercury.com/">mercury.com</a></h4> <p>Nick Dellis</p> <p><a href="mailto:nick.dellis@mercury.com">nick.dellis@mercury.com</a></p> <p>VP Revenue</p> <h4>Stifel | <a href="https://bankwithstifel.com/">bankwithstifel.com</a></h4> <p>Brad Ellis</p> <p><a href="mailto:bellis@stifelbank.com">bellis@stifelbank.com</a></p> <p>MD | VC Banking & Lending</p> <h4>US Bank | <a href="http://usbank.com">usbank.com</a></h4> </td> </tr> </table> ## SAMPLE INVESTMENT POLICY {#sample-investment-policy} **_Important: closely consult with your Board and counsel before adopting a formal investment policy._** ### PURPOSE The purpose of this policy is to establish a clear understanding between (the “Company”) and investment manager(s) regarding investment objectives and policies. ### OBJECTIVES The Company's primary objectives when investing excess cash are, in order of importance: * Preservation of principal * Maintenance of liquidity that is sufficient to meet cash flow requirements * Maximize total return - capture market rate of return consistent with the parameters of this policy and market conditions ### ROLES AND RESPONSIBILITIES This policy is approved by the Company’s Board of Directors. The Company will review the investment policy on an as needed basis, ideally at least annually. Any significant changes to the investment policy, as determined by the CEO and/or CFO, are required to be approved by the Company's Board of Directors. The Company's Chief Executive Officer (CEO) or Chief Financial Officer (CFO) or any individual designated by them ("the Company") will review the Company's cash flow requirements and determine the amount of liquidity required for working capital. Funds not required for working capital can be invested in a managed portfolio of fixed income securities within the guidelines set forth below. The Company may employ the services of a Registered Investment Advisor (RIA), a broker dealer and/or Commercial Bank, to handle a portion or all of the investment activities of the Company consistent with the guidelines set forth in the investment policy. The CFO will review current investments for compliance with this policy and monitor whether the Company meets the definition of an “investment company” under the Investment Company Act of 1940. If any investments are out of compliance with this policy, or the Company meets the definition of an investment company, the CFO, working with the CEO, will identify ways to remedy the problem, by liquidating any investments or through other means. The CFO will report on at least an annual basis to the Company’s Audit Committee on the condition of the Company’s investment portfolio. ### INVESTMENT GUIDELINES #### 1. Approved Instruments The funds will be invested only in fixed income instruments denominated and payable in U.S. dollars. The following investments are considered appropriate: * Money market funds registered according to SEC Rule 2a-7 of the Investment Company Act of 1940; fund size must be at least $5 billion * U.S Treasury Securities, specifically U.S. Treasury Bills, U.S. Treasury Notes, and U.S Treasury Bonds * U.S. Government Agencies, specifically Federal Home Loan Bank, Fannie Mae, Freddie Mac, and/or Federal Farm Credit Bank * FDIC-Guaranteed Certificates of Deposit (CD's) and Time Deposits #### 2. Prohibited Investments All investments that are not listed as Approved Instruments in section 1. above are prohibited. The following investments are specifically prohibited (not a complete listing): * Collateralized debt obligations, collateralized loan obligations * Structured investment vehicles * Auction rate securities * Extendable commercial paper #### 3. Credit Quality At the time of purchase, investments which bear a _short-term_ credit rating must have a minimum rating and be explicitly rated by _two of_ the following rating services: A2 by Standard & Poor's, P2 by Moody's and/or F-2 by Fitch. At the time of purchase, investments which bear a _long-term_ credit rating must have a minimum rating and be explicitly rated by _one_ of the following rating services: A by Standard & Poor's, A3 by Moody's and/or A- by Fitch. Asset-backed securities with a long-term credit rating must be rated AAA or equivalent by at least one NRSRO. Asset-backed securities with a short-term credit rating must be rated A-1+ or equivalent by at least one NRSRO. Overnight money market mutual funds must be AAA rated by at least _one_ of the three ratings agencies mentioned above If securities are downgraded by one of the above rating agencies, the investment manager will be required to send notification of the downgrade to the Company and recommended action within two business days of the downgrade event. If a security's rating drops below the minimum ratings above, the investment manager will recommend the action to be taken in the downgrade notice, and may hold the security, unless specifically instructed to be sold by the Company. Repurchase agreements will be at least 102 percent collateralized with securities issued by the U.S. government or its agencies. #### 4. Diversification Securities of a single issuer valued at cost at the time of purchase should not exceed [5] percent of the market value of the portfolio or [$X] million, whichever is greater. For purposes of this diversification restriction, securities of a parent company, subsidiaries, entities acquired or merged will be combined. Securities issued by the U.S. Treasury and U.S. government agencies and overnight money market funds are specifically exempted from these restrictions. #### 5. Marketability/Liquidity/Trading For accounting purposes, all investments will be designated as "Available for Sale" as defined by FASB Accounting Codification ASC320, "Investments - Debt and Equity Securities." Thus, investments may be sold prior to maturity to preserve capital or to provide required liquidity or for other reasons determined by the Registered Investment Advisor. In addition, trading of securities is permitted by outside investment managers to realize capital gains or losses within the context of maximizing after-tax total return. \ #### 6. Maturity/Portfolio Duration At the time of purchase, the final maturity of each security within the portfolio shall not exceed [24] months. The weighted average maturity of the portfolio will be no greater than [12] months. In the case of asset-backed securities, the average life of the security shall be used to determine the maximum maturity threshold and the weighted average maturity of the portfolio. With respect to any eligible instrument that has an interest rate that is reset periodically, the reset date shall be used to determine the maximum maturity limit. The reset date should also be used for the weighted average maturity calculation. \ #### 7. Performance Measurement The investment manager should meet with the Company quarterly and will be available for regular contact. Investment performance for the portfolio will be measured against the agreed upon benchmark. #### 8. Transparency and Verification Assets are to be held in a segregated third-party custodial account with separate custody agreement executed between the custodian and the Company. The SSAE 16 report of the custodian will be provided annually. #### 9. Fiduciary Discretion The Chief Financial Officer or other individual appointed by the Board and his/her authorized employees are responsible for securing and managing investments and cash for operations. These individuals have full discretion to invest any excess capital subject to strict adherence to these guidelines. These guidelines are to be reviewed periodically with the Chief Financial Officer or Chief Executive Officer and revisions made consistent with objectives set forth herein. ## Notes <p> <sup style={{color: "blue"}}>[^1]</sup> Contact <a href="mailto:paula.s.root@jpmorgan.com">paula.s.root@jpmorgan.com</a> and <strong>include the following info</strong>: Current banking partner, Company legal name, Company address, Contact name, Contact phone, Contact email, Website </p>
A Deep Dive into DAOs: Life Changing DAOs COMMUNITY March 25, 2022 In 2016, a few members of the Ethereum community came together to create a platform that would allow individuals to pitch project ideas. Community members would vote on these ideas using tokens they bought in exchange for sending Ether to a unique wallet address. This was how the first DAO, or decentralized autonomous organization, was created. Since then the pace and development of the Web3 tool has exploded. Today, communities across the globe are using DAOs to help gather, organize, and distribute funds to causes that matter. On NEAR, there are dozens of DAOs working and collaborating in an open and transparent way. This feature explores how DAOs are being used to change lives in different and radically new ways. Unchain Fund – Raising Funds for Humanitarian Causes Rev Miller, Co-founder of Atlantis World, a Web3 social metaverse, was on holiday in Dubai when news about the Ukraine war broke out. “I couldn’t just stand still,” he says. “I wanted to create a fundraiser or volunteer or just do something.” Miller immediately reached out to people and communities he knew in the crypto space to start some sort of initiative that could help Ukrainians impacted by the war. Miller joined forces with several others who also wanted to get involved. “I don’t trust non-profits in general because a lot of them lack transparency,” he says. “I’ve been in the blockchain space for years so I was like, hey, what if we created this initiative within the intersection of Web3, where you can have your funds publicly shown and are operated and run by trusted people.” Unchain Fund now has about 50 core members and hundreds of volunteers globally and across Ukraine. To date, the organization has raised $7 million, of which it has distributed $2 million to people on the ground. Miller says the team is currently working on its distribution model to prevent scams. The DAO partnered with a Ukrainian bank to issue an online card that distributes funds directly to individuals. They can use the cards to buy food and pay for other services. Unchain Fund is permissionless, meaning anyone can become a contributor. However, there are different layers of contribution. Volunteers, for instance, have limits on how much funding they can receive to help people on the ground. Additionally, individuals seeking help must fill out a detailed application that asks for contact information, proof of identification, an address where they can be reached, and more. Miller says this was a necessary step to take because Unchain Fund receives 1,000 applications a day on average and that number is only rising. He also emphasizes that the DAO certainly has some centralized aspects. “There are some things we just can’t wait a week to make a decision on through governance because people are dying. At the end of the day, there are some things that are unfortunately still based on human trust,” Miller says. “DAOs and Web3 are definitely the way to become resistant to events like these, but due to Web3 tooling, we are able to coordinate global power and resources for a public good that needs to be addressed here and now.” Marma J Dao – Empowering Grassroot Communities When Chloe Lewis started Marma J DAO in the spring of last year, her goal was to come up with a way to more efficiently and transparently manage crypto assets as a community. The DAO, named after Lewis’ grandmother, is a part of the Marma J Foundation, an organization that aims to leverage Web3 technology for social good. The DAO’s most recent initiative, #maksimourhero, raised funds for Maksim, a ten-year-old diagnosed with medulloblastoma, a cancer that begins in the brain or spinal cord. Marma J Foundation raised funds to help Maksim’s family with his relocation, lodging, and medical treatments. The DAO invited artists to create Valentine’s cards which would then be minted and sold through a simple sale. The initiative was quite successful, according to Lewis. Dozens of NFTs were created and minted by Marma J DAO, with 90% of the proceeds going to Maksim, with the rest earmarked for the DAO. “It was great to see so many people in the ecosystem learning how to use custom function calls on their DAO to mint NFTs,” Lewis says. Marma J DAO has led many other initiatives focused on not only social good but also Web3 education, including teaching users how to leverage tools in the NEAR ecosystem and how to mint an NFT through a DAO. Marma J DAO generally funds initiatives to support members of the Marma J community using its treasury of native tokens. Currently, the DAO is comprised of nine unique addresses that form its council, as well as 47 members. The DAO’s council members vote on proposals with the goal of “spreading love and positivity in the open web ecosystem,” according to its website. The collective uses Marma J DAO to hold and distribute NEAR assets to and from Marma J community members. The Marma J Foundation uses DAO-launching platform Astro to manage the DAO—its membership, decision-making, and funding are coordinated publicly on the NEAR blockchain. “We realized that if we had our foundational assets in a proof-of-stake network where we were supporting the NEAR ecosystem just from staking our NEAR tokens, which we could then use to convert into goods and services to spread to the community, that could be a more viable path moving forward,” Lewis said in a video breakdown of the Marma J Foundation. “The largest difference between DAOs and a company is that the DAO has no legally binding obligations, just smart contracts to control logic,” Lewis says. Aurora DAO – Helping Protocols Give Control to their Communities Imagine a board of directors making decisions in a company, except that instead of doing so behind closed doors and allocating all power to a select few, the board is fed information from the rest of the company and uses this data to make company-wide choices. The Aurora DAO functions as this exact sort of decentralized board of directors, created as a way to govern the Aurora protocol, an Ethereum Virtual Machine (EVM) smart contract platform that creates a bridge between Ethereum and NEAR. Holders of Aurora DAO are able to vote on high-level matters concerning the Aurora protocol, as well as other administrative and operational decisions. Aurora DAO organizer Aliaksei Papou explained that Aurora’s EVM was developed to be entirely permissionless, and its governance through the DAO was devised with this goal in mind. Aurora DAO approved the creation of a “community treasury” with a significant portion of the Aurora token supply, which will be used to fund projects being built on Aurora. “It makes perfect sense to offload the decision-making in this respect to the members of the community since they are the primary users of those projects, and are the ones who are most interested in a healthy ecosystem growth,” Papou says. “Meanwhile, more complex or technical matters, like protocol upgrades, will be the prerogative of the DAO Council, as the Council is represented by experts in such specific aspects.” Papou says the DAO was formed by well-known representatives of the crypto space. To ensure wide representation, the council consists of principal Aurora investors who have more experience in investment matters, Aurora ecosystem partners who have more experience in technical projects, and members of Aurora Labs itself. “With further decentralization of the governance, many important decisions will be delegated to the community,” Papou said. “So the DAO will perform the role of the board of directors, similarly to traditional companies, while they will be elected by the community as well.” Aurora DAO uses the SputnikDAO framework for operations. The DAO currently has 13 councils, each of whom votes on different proposals including council management, DAO smart contract upgrades, contract calls, and payouts. “Simply put, it’s decentralization,” Papou said. “Trusted people with various competencies, who do not necessarily know each other, make decisions about the protocol.” Developer DAO – Helping People Learn Together Developer DAO is a community of like-minded individuals committed to participating, learning, and contributing to the future of Web3. The DAO aims to accelerate the education and impact of new builders in the Web3 space. To join, individuals must hold a D4R NFT that can now only be bought on the secondary market or won in contests and giveaways (the original NFT mint has ended). Developer DAO also offers a scholarship program for free entry that’s available to anyone who wants to join. The DAO today has nearly 6,000 individual NFT holders. Developer DAO started as an experiment in September 2021 by Nader Dabit, who live-coded and launched the DAO on his YouTube channel. From there, the DAO grew organically. Individuals, who joined after seeing Dabit promote it on Twitter, began organizing the Discord and developing the DAO’s mission. “I initially started it in the hope of having a community of developers to learn and build together with,” Dabit says. “After joining Friends With Benefits, I really loved the community but wanted to have more engineers to hang out with and talk to. We’re about seven months in and we’re still figuring things out, but we’ve accomplished a lot already and have a lot of exciting things that we’re working on right now.” For core member Will Kempster, one of the best things about being a part of a DAO is how everything is community-driven. “No one person is in control. You’re free to drop in and out when it suits you and people are generally free to do what they want so long as it is in line with our mission, values, and goals,” Kempster says. “The biggest issue is probably coordination, organizing about 6,000 people in a DAO via Discord that was created without any prior planning is an interesting challenge but we’re starting to get a good handle on things!” For moderator Narbeh Shahnazarian, DAOs are similar to startups in that one can be wearing multiple hats and be leading multiple efforts simultaneously. “The great thing about Developer DAO is you can literally go and get started in any which way you want and are empowered to come up with and lead new initiatives,” he says. “The DAO does have areas for improvement but things will most definitely improve over time as we learn from our experiences and apply those to future endeavors.” “I like to refer to the current iteration of Developer DAO as ‘beautiful chaos,” he adds. Komorebi Collective – Elevating New Voices in Crypto Community Komorebi Collective is a DAO formed by women in the blockchain space to support crypto companies founded by female and non-binary individuals. The DAO was formed by Manasi Vora, Medha Kothari, and Kinjal Shah, and currently has 35 members, some of whom are from crypto organizations Women in Blockchain and she256 (founded by Vora and Kothari respectively). Komorebi is a Japanese expression that describes sunlight filtering through trees. These rays of light, according to Vora, illuminate the forest undergrowth that is otherwise difficult to see. “Komorebi Collective aims to illuminate and elevate a group of otherwise underestimated visionary founders building in crypto,” Vora says. Komorebi invests in teams and products created by female and non-binary founders, which the DAO wants to see flourish in the Web3 space. “DAOs have a lot of potential to bring communities together and channel capital towards identified missions, but they require a good amount of coordination across members and need processes in place for it to be efficient,” Vora says. “It might not be the best tool for everything crypto. It’s like the early days of blockchain where you need to ask: does this need a DAO?” Komorebi Collective is almost 70% deployed and has invested in several companies so far, including Apricot Finance and FormFunction. The collective is slated to raise its second round of funding in the next few weeks. SailGP DAO – Reimagining Team Sport Management on NEAR A ground-breaking multi-year partnership between NEAR and SailGP, one of the world’s fastest-growing sailing events, will explore the sale of a new team to a DAO launched on the NEAR Protocol. This will make the SailGP DAO a first-of-its-kind community engagement and activation platform for professional sports. The SailGP team DAO will be a community project—a major break from traditional sports team ownership structures. DAO members will, through proposals, have a say athlete selection, team management, commercialization options, as well as overall team strategy and operations. “Our mission is to enable community-driven innovation to benefit people around the world, and this partnership is a fantastic example of exactly that,” said Marieke Flament, CEO of the NEAR Foundation, the non-for profit entity that oversees the NEAR blockchain’s development. SailGP and the NEAR community will collaborate on several new projects—each designed to inspire Web3 developers on the NEAR protocol. As partners, SailGP and NEAR will also work on integrated technology and research and development projects for offerings like events ticketing, NFT and gaming, and mobile app integration. On-site experiences and activations at global SailGP events will help traditional industries transition to Web3 through NEAR’s simple, secure, and scalable blockchain platform. NEAR will also leverage SailGP’s global technology platform to build real-world intellectual property and Web3 applications that will cover fan engagement, data delivery and management, league management, and more. This new DAO team could join the SailGP starting line-up for Season 4 in 2023. “We welcome NEAR to the SailGP family and we are looking forward to them participating in the most exciting racing on-water, featuring the world’s best sailors,” SailGP Founder Larry Ellison said. “This deal presents an exciting opportunity to change how fans can directly influence and participate in the sports they love,” added Mark Shapiro, President of Endeavor, part of IMG and a strategic investor in SailGP. “We are proud to have brokered this ground-breaking partnership which is the culmination of what happens when sport, technology and entertainment collide.” The DAO revolution DAOs are transforming the way individuals join forces to work towards a common goal, whether it is social, cultural, technological, or financial. Unchain Fund, Aurora DAO, Marma J DAO, Developer DAO, and Komorebi Collective are just a few examples of DAOs using transparency and decentralized collaboration to work towards changing society as we know it. These are still early days for DAOs on NEAR and other blockchains—much remains to be done to optimize the DAO ecosystem for mass Web3 adoption. Launchpads like Sputnik, AstroDAO, NearPad, and other services being built by developers will all be critical in unleashing the next wave of DAO innovation. To fully tap the power of DAOs, things like tooling, standards, and management will also need to be refined and built up, so that other autonomous organizations and Web3 services can efficiently interact with DAOs, creating more integrations with the physical world.
--- sidebar_position: 4 --- # Further Reading
- Proposal Name: Execution Outcome - Start Date: 2019-09-23 - NEP PR: [nearprotocol/neps#0017](https://github.com/nearprotocol/neps/pull/17) - Issue(s): https://github.com/nearprotocol/nearcore/issues/1307 # Summary [summary]: #summary Refactor current TransactionResult/TransactionLog/FinalTransactionResult to improve naming, deduplicate results and provide results resolution by the front-end for async-calls. # Motivation [motivation]: #motivation Right now the contract calls 2 promises and doesn't return a value, the front-end will return one of the promises results as an execution result. It's because we return the last result from final transaction result. With the current API, it's impossible to know what is the actual result of the contract execution. # Guide-level explanation [guide-level-explanation]: #guide-level-explanation Here is the proposed Rust structures. Highlights: - Rename `TransactionResult` to `ExecutionOutcome` since it's used for transactions and receipts - Rename `TransactionStatus` and merge it with result into `ExecutionResult`. - In case of success `ExecutionStatus` can either be a value of a receipt_id. This helps to resolve the actual returned value by the transaction from async calls, e.g. `A->B->A->C` should return result from `C`. Also in distinguish result in case of forks, e.g. `A` calls `B` and calls `C`, but returns a result from `B`. Currently there is no way to know. - Rename `TransactionLog` to `ExecutionOutcomeWithId` which is `ExecutionOutcome` with receipt_id or transaction hash. Probably needs a better name. - Rename `FinalTransactionResult` to `FinalExecutionOutcome`. - Update `FinalTransactionStatus` to `FinalExecutionStatus`. - Provide final resolved returned result directly, so the front-end doesn't need to traverse the receipt tree. We may also expose the error directly in the execution result. - Split into final outcome into transaction and receipts. ### NEW - The `FinalExecutionStatus` contains the early result even if some dependent receipts are not yet executed. Most function call transactions contain 2 receipts. The 1st receipt is execution, the 2nd is the refund. Before this change, the transaction was not resolved until the 2nd receipt was executed. After this change, the `FinalExecutionOutcome` will have `FinalTransactionStatus::SuccessValue("")` after the execution of the 1st receipt, while the 2nd receipt execution outcome status is still `Pending`. This helps to get the transaction result on the front-end faster without waiting for all refunds. ```rust pub struct ExecutionOutcome { /// Execution status. Contains the result in case of successful execution. pub status: ExecutionStatus, /// Logs from this transaction or receipt. pub logs: Vec<LogEntry>, /// Receipt IDs generated by this transaction or receipt. pub receipt_ids: Vec<CryptoHash>, /// The amount of the gas burnt by the given transaction or receipt. pub gas_burnt: Gas, } /// The status of execution for a transaction or a receipt. pub enum ExecutionStatus { /// The execution is pending. Pending, /// The execution has failed. Failure, /// The final action succeeded and returned some value or an empty vec. SuccessValue(Vec<u8>), /// The final action of the receipt returned a promise or the signed transaction was converted /// to a receipt. Contains the receipt_id of the generated receipt. SuccessReceiptId(CryptoHash), } // TODO: Need a better name pub struct ExecutionOutcomeWithId { /// The transaction hash or the receipt ID. pub id: CryptoHash, pub outcome: ExecutionOutcome, } #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub enum FinalExecutionStatus { /// The execution has not yet started. NotStarted, /// The execution has started and still going. Started, /// The execution has failed. Failure, /// The execution has succeeded and returned some value or an empty vec in base64. SuccessValue(String), } pub struct FinalExecutionOutcome { /// Execution status. Contains the result in case of successful execution. pub status: FinalExecutionStatus, /// The execution outcome of the signed transaction. pub transaction: ExecutionOutcomeWithId, /// The execution outcome of receipts. pub receipts: Vec<ExecutionOutcomeWithId>, } ```
--- id: guest-book title: Guest Book --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" Our Guest Book example is a simple app composed by two main components: 1. A smart contract that stores messages from users, allowing to attach money to them. 2. A simple web-based frontend that displays the last 10 messages posted. ![img](/docs/assets/examples/guest-book.png) --- ## Obtaining the Guest book Example You have two options to start the Guest book Example. 1. You can use the app through `GitHub Codespaces`, which will open a web-based interactive environment. 2. Clone the repository locally and use it from your computer. | Codespaces | Clone locally | | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | | [![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/near-examples/guest-book-examples) | 🌐 `https://github.com/near-examples/guest-book-examples` | --- ## Structure of the Example The example is divided in two main components: 1. The smart contract, available in two flavors: Rust and JavaScript 2. The frontend, that interacts with an already deployed contract. <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash ┌── sandbox-ts # sandbox testing │ ├── src │ │ └── main.ava.ts │ ├── ava.config.cjs │ └── package.json ├── src # contract's code │ ├── contract.ts │ └── model.ts ├── package.json # package manager ├── README.md └── tsconfig.json # test script ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash ┌── tests # workspaces testing │ ├── workspaces.rs ├── src # contract's code │ └── lib.rs ├── Cargo.toml # package manager ├── README.md └── rust-toolchain.toml ``` </TabItem> </Tabs> --- ## Frontend The guest book example includes a frontend that interacts with an already deployed smart contract, allowing user to sign a message. <hr class="subsection" /> ### Running the Frontend To start the frontend you will need to install the dependencies and start the server. ```bash cd frontend yarn yarn start ``` Go ahead and login with your NEAR account. If you don't have one, you will be able to create one in the moment. Once logged in, you will be able to sign a message in the guest book. You can further send some money alongside your message. If you attach more than 0.01Ⓝ then your message will be marked as "premium". <hr class="subsection" /> ### Understanding the Frontend The frontend is composed by a single HTML file (`/index.html`) and uses REACT. Check `/App.js` and `/index.js` to understand how components are displayed in the screen. You will notice in `/src/App.jsx` the following code: <CodeTabs> <Language value="js" language="js"> <Github fname="App.jsx" url="https://github.com/near-examples/guest-book-examples/blob/main/frontend/src/App.jsx"/> </Language> </CodeTabs> It setups the necessary variables and starts the app. --- ## Smart Contract The contract presents 3 methods: `add_message`, `get_message` and `total_messages`. <CodeTabs> <Language value="js" language="ts"> <Github fname="contract.ts" url="https://github.com/near-examples/guest-book-examples/blob/main/contract-ts/src/contract.ts" start="4" end="27" /> </Language> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/guest-book-examples/blob/main/contract-rs/src/lib.rs" start="31" end="64" /> </Language> </CodeTabs> <hr class="subsection" /> ### Testing the Contract The contract readily includes a set of unit and sandbox testing to validate its functionality. To execute the tests, run the following commands: <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash cd contract-ts yarn yarn test ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash cd contract-rs cargo test ``` </TabItem> </Tabs> :::tip The `integration tests` use a sandbox to create NEAR users and simulate interactions with the contract. ::: <hr class="subsection" /> ### Deploying the Contract to the NEAR network In order to deploy the contract you will need to create a NEAR account. <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash # Optional - create an account near create-account <accountId> --useFaucet # Deploy the contract cd contract-ts yarn build near deploy <accountId> ./build/guestbook.wasm ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash # Optional - create an account near create-account <accountId> --useFaucet # Deploy the contract cd contract-rs cargo near build near deploy <accountId> ./target/wasm32-unknown-unknown/release/guestbook.wasm ``` </TabItem> </Tabs> :::tip To interact with your contract from the [frontend](#frontend), simply replace the variable `CONTRACT_NAME` in the `index.js` file. ::: <hr class="subsection" /> ### CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands ```bash # Get messages with optional arguments for pagination near view guestbook.near-examples.testnet get_messages --args='{"from_index": "0","limit": "10"}' # Get total number of messages near view guestbook.near-examples.testnet total_messages # Add a message # Replace <accountId> with your account ID # Required a text # Optional deposit to make the message premium near call guestbook.near-examples.testnet add_message '{"text":"Hello Near"}' --accountId <accountId> --deposit 0.1 ``` :::tip If you're using your own account, replace `guestbook.near-examples.testnet` with your `accountId`. ::: --- ## Moving Forward A nice way to learn is by trying to expand a contract. You can modify the guestbook example to incorporate a feature where users can give likes to messages. Additionally, implement a method to toggle the like. :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-cli: `4.0.13` - node: `18.19.1` - rustc: `1.77.0` :::
NEAR Protocol Roadmap 2023-4: The Next 2 Years of NEAR COMMUNITY November 9, 2022 This post, written by Pagoda’s Head of Protocol Bowen Wang, originally appeared on the Web3 startup platform and main contributor to the core Protocol Pagoda’s blog. NEAR has evolved tremendously in the two years since the mainnet launch in October 2020. More than 20 protocol upgrades were done live, most recently the launch of Sharding Phase 1. As we look ahead to the next two phases of sharding and beyond, it’s time for an updated protocol roadmap. This post will outline the next two years of evolving the NEAR Protocol and the technical priorities we believe will benefit builders and users the most. The roadmap is meant to be a living document and anyone is welcome to make suggestions or proposals on how the protocol should evolve. The roadmap has two major components: Experience and Core. The Experience section encompasses user and/or developer experience and the protocol features needed to enable those experiences. As an example, an iPhone user can freely start to use applications built on top of NEAR without having to register an account if we have meta transactions and support for Secp256r1 keys. The Core section, on the other hand, covers major efforts to improve the scalability and decentralization of the protocol. Most notably, this features the launch of phase 2 of sharding, which scales the network to 100 shards with no validators tracking all shards. Phase 2 is planned for 2023. The roadmap goes through 2024 with the delivery of phase 3 of sharding, which dynamically adjusts the number of shards based on demand. Head over to the Pagoda blog to read the NEAR Protocol Roadmap 2023-4 with infographics.
--- description: This is a guide to launching DAOs on NEAR with Astro. title: How to Launch a DAO sidebar_position: 1 --- # 🚀 How to Launch a DAO :::info on this page * Astro offers four pre-set DAO types: Foundation, Clubs, Corporation, and Cooperative, which can be customized during the creation process. * To launch a DAO on Astro, users need to customize proposals, structure, and voting power, name the DAO, add links and select a flag, review and launch, and confirm the transaction in their NEAR wallet. * The creation of a DAO on Astro requires a storage fee of 5 NEAR, and users can skip the next part if their DAO isn't utilizing a voting token. ::: ### **Launching a DAO on Astro: DAO Presets** Before we guide you through the process of setting up your DAO, it’s important to understand the four pre-set DAO types that Astro has to offer. Do note that each of these can be fully customized during the creation process: ![Astro DAO](@site/static/img/astrodao1.png) | **PRE-SET DAO TYPES** | **Proposals** | **Structure** | **Voting Power** | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | **Foundation** - Ideal for groups giving donations, a DAO funding community projects, or a general-purpose fund for open-source projects.<br/> | **Open** - Anyone can submit a proposal | **Groups and Committees** - Specific groups can vote on specific proposals| **Democratic** - Every member gets one vote<br/> | | **Clubs** - Although still as flexible as any other DAO on Astro, are designed to cater to a small circle of friends/acquaintances with a common goal, a group of fans for anything and everything, or a social club - anything along those lines.<br/> | **Members only** - Only members or token-holders can submit a proposal<br/> | **Flat - No groups -** all members have equal access | **Democratic** - Every member gets one vote | | **Corporation** - Enable more structure, this type is ideal for business with shareholders, and companies/startups.<br/> | **Members only** - Only members or token-holders can submit a proposal | **Groups and Committees** - Specific groups can vote on specific proposals | **Weighted** - The more tokens you own, the more voting power you get | | **Cooperative** - Aimed towards creative collectives, or businesses with members, rather than shareholders.<br/> | **Members only** - Only members or token-holders can submit a proposal | **Groups and Committees** - Specific groups can vote on specific proposals | **Democratic** - Every member gets one vote | ### **Launching a DAO on Astro: Step-By-Step** If you’re not already logged into your NEAR Wallet, go ahead and do so by clicking ‘log in’ in the top right corner of the Astro homepage. ![Astro DAO](@site/static/img/astrodao2.png) 1. On the landing page of Astro, select the organization you’re starting out of the four presets or hit ‘Create a DAO’ in the top right corner 2. **Customize** each of the settings in regards to proposals, structure, and voting power to your liking 3. **Name your DAO** 1. DAO Address * This is unchangeable and will be the on-chain address of your DAO 2. Display name * How your DAO will be displayed within the Astro application 3. Purpose * Why have you created this DAO? Concentrating on your goals may help 4. **Links** * Here you can enter the links to your website and social media channels, if applicable 5. **Select a flag** * Move the window around to pick the flag of your DAO 6. **Review and launch** * Double check the information you’ve added is up to scratch and hit ‘Launch DAO’ 7. **Confirm the transaction** in your NEAR wallet and pay a small transaction fee ![Astro DAO](@site/static/img/astrodao3.png) _**Voila**_! Your DAO is live and thriving on Astro! **Note:** The creation of a DAO on Astro requires a storage fee of 5 NEAR, this is a fee for deploying the DAO and does not go to the platform. ### Next Steps If your DAO isn’t utilizing a voting token, then you can skip the next part and refer to the details below to flex all the features of your DAO on Astro. ### A Note on DAOs Decentralized autonomous organizations are still in their relative infancy. However, we believe the accessibility granted by Astro will open up the world of DAOs to the masses.&#x20; On that note, build, create, and innovate through your DAO and unlock all of the benefits that a decentralized, open, and transparent system can yield. Happy building! \ Come and join the Astro Community over on Telegram [here](https://t.me/astro\_near)\
--- title: Strategic Category Positioning description: NEAR BOS Strategic Category Positioning sidebar_position: 2 --- # Strategic Positioning for NEAR/BOS at Consensus **There needs to be a place to build open software experiences that enable community, commerce, and communication with progressive decentralization** Today this is not possible in a scalable and accessible way in Web3. You either have to build and distribute your experiences on client-server websites or on centralized app platforms. Why this needs to exist is clear for people who believe in the ownership of their data, assets, money, and decisions. But for those of us that don’t hold these truths to be self-evident there are practical considerations for why you might consider an open web alternative. ## High Level Summary: ### What does the Blockchain Operating System enable? * For the first time, **decentralization powers distribution**. A sea change for Web3. What used to be a tradeoff for the sake of user-owned data, censorship resistance, and a more open web now delivers those same benefits while also bringing instant exposure to the entire Web3 user base of the BOS. * **Enterprises** can easily introduce Web3 to their customers through existing apps and websites via the BOS. * **Individuals **can engage in community commerce and universal social/discovery across novel Web3 experiences by builders and apps from enterprises. * **Builders **– whether developers or startups – achieve broad Web3 distribution and discovery instantly to the NEAR user base, while also gaining access to a super-simple development environment and a range of services just through some simple JavaScript. ### Who are the first builders on BOS and what value does it deliver to them? #### 3 highest level audiences for Consensus: Enterprises, Individuals, Builders * For Enterprises: deliver seamless **Web3 optionality** to existing customer base and web properties with minimal development effort: deepen customer relationships and expand into new business models. * For Individuals: engage in universal social and **community commerce **across the entire open web, greater discoverability, truly peer-to-peer * For Builders: **fastest development environment**. Component ecosystem = easiest development environment for building apps, zero hosting, range of decentralized services and features included, with instant distribution to pool of common users who own their data via universal account ### What does it mean that NEAR is the BOS, what does the NEAR stack look like now? * Blockchain Operating System * Near Discovery (featured gateway: Near.org) * NEAR Social Contract * NEAR Onboarding (Fast Auth) * NEAR Data (Query API) * NEAR Protocol #### Audience Level Positioning: **For Crypto Developers - IaaS.** We are a blockchain-based development platform that offers build, deploy, and serverless backend services for web apps and dynamic websites that want to use crypto-based business models. We make it easy. You don’t need to worry about any maintenance or devops. Decentralization and distribution of apps has traditionally been a hard trade off. Choose a centralized app store to get access to audiences or build your own website and do all distribution from your own efforts. With the BOS, it is possible to expand your reach through decentralization. Building an app on a decentralized frontend is as easy as remixing an existing open source component. Once you build an app on a decentralized frontend, it can exist in your website, your app, on Near.org or any other website with just a few lines of Javascript. * Decentralized frontends for security & resilience * React-based framework for a familiar coding experience * Zero cost, requires no hosting or special development environments * Build once and deploy to anything on the internet * Super easy onboarding and re-engagement frameworks for users * Publishing & co-marketing to sites with millions of visitors * Interconnect with other blockchains **The result.** We make your Web3 gateway more secure, easier to manage, and enable new distribution through decentralization. 1. Level 1: Explore a component on Near.org. Proof - [Burrow](https://alpha.near.org/ciocan.near/widget/burrow) 2. Level 2: Build an app on Near.org 3. Level 3: Embed a decentralized experience in your existing app or site. Proof - Ref 4. Level 4: Upgrade the frontend of your website to be decentralized and resolve identity on near.org. 5. Level 5: Build a fully decentralized gateway with IPFS and ENS/NEAR Domain. Go completely serverless. **For Enterprise Businesses - PaaS:** We are like Salesforce but for the next generation of business models. We are a cloud computing provider for anything crypto. Our cloud is native to the blockchain which allows us to build a platform that is flexible to your business needs and interoperable with your existing investments. * Enables the use of any crypto blockchain, no complex swaps or passing through exchanges * Can be built entirely by JavaScript engineers at a fraction of the development cost * Onboard customers seamlessly in seconds from their phones without apps * Requires no hosting or special development environments **The result.** We make your brand the gateway to crypto and new business models in community, commerce, and customer loyalty. You can build crypto into your existing business and web properties or extend your brand assets into the crypto-based web. You are in the driver seat, not the technology. * Luxury goods: Create community-driven commerce marketplaces that keep more profits in your hands and maintain the authenticity of your brand. * Consumer services: Build closer relationships with your best customers by gamifying their experience with your services and giving them access to special perks and events. Build momentum and re-engagement like you never thought possible. * Sports: Deepen the fan experience through entertainment that embraces both physical and digital events. Collectibles and top moments brought direct to fan ownership. Even enable direct involvement in how the team is run and played. Proof - SailGP **For Individuals - SaaS:** Exploring in the BOS is like super-powered Facebook groups that extend to every app you love to use. A way to connect and organize with people but you own the data/financials and you can customize it like your own website. * Get started and invite in seconds * Works on your phone without downloading new apps * Send or pool money * Thread conversations * Find anything on the network with simple search * Use components to extend your group's reach with a little JavaScript and soon via Chat prompt. * Take your data with you with identity tied to you, not the application. * Free **The result.** We enable you to shape custom experiences and freely collaborate with anyone you choose. For example: * Organize a vacation with shared money and a custom itinerary * Plan your wedding and allow everyone to share moments and contribute to your registry * Create a personalized blog with a place for discussions and donations **Ultimately,** with BOS we are building an open source platform that offers an alternative to Google, Apple, Amazon, Facebook, & Microsoft as a full software services platform where you can choose how decentralized you want to be. Where to build along the path to progressive decentralization comes down to the following questions. 1. Will money be involved through digital goods or subscription services? 2. Is community ownership key to my experience? If the answer is yes to even one of these questions, then the BOS is the right fit to evolve your business or project into the future web. NEAR offers the most flexible and accessible platform across Web2 or Web3, widely expanding your offerings and services at minimal cost to you compared to 15-30% cost of other platform services.
--- id: token-custody title: Token Custody Options sidebar_label: Token Custody sidebar_position: 1 --- --- There are several options available to manage your NEAR and NEAR-based assets. As with all blockchains, to claim or receive tokens you will need to generate a keypair which stores your crypto. You can do this directly by using a hardware wallet and the command line or indirectly by using a commercially available web or mobile wallet. All of these options are described below. 1. Web Wallets 2. Mobile Wallets 3. Custodians 4. CLI **Do not claim NEAR tokens to an exchange address! Claiming tokens to an exchange address might result in the loss of your tokens.** If you have chosen an option which doesn't allow you to check balances or lockup details, you can lookup your account using [this tool](https://near.github.io/account-lookup). This list will be regularly updated as more products and providers offer NEAR support. Feel free to send Pull Request to [token-custody.md](https://github.com/near/wiki/edit/master/wiki/overview/tokenomics/token-custody.md) with new options. ### Security & Recovery For any applications or hardware wallet you use, the root of the security is in the **seed phrase**. No one else in the world should have access to this seed phrase. And if they manage to get access to it - they will be able to control your account and steal your funds. The seed phrase defines the private key managed by the application. This seed phrase can be used to recover access to your account if you lose access to your app / device or there is some software issue \(which happens with all of the software\). You **MUST** back it up \(store it somewhere securely\) and if you lose both seed phrase and the device - there is no way to get access to your account. E.g. Ledger, Trust Wallet, NEAR Wallet all ask to back up seed phrase. If Trust Wallet stops working, you lose your Ledger or NEAR Wallet front-end goes down - you can always use this seed phrase in another solution \(including CLI\) to recover the private key and access your funds. Note, NEAR Wallet has few less secure but more convenient options, which are just convenient ways to back up your seed phrase via email or sms. It's not recommended for large sums of money, as these are not very secure back up places \(your email can be hacked or SIM card can be highjacked and hackers would be able to access your funds\). We recommend to only use them for small amounts of money, similar to your wallet in the pocket. > Ledger uses a single seed phrase for all applications and accounts on it. It is done by combining the seed phrase with an "HD path" - derivation paths. You can read more [in general about HD wallets and derivation](https://medium.com/myetherwallet/hd-wallets-and-derivation-paths-explained-865a643c7bf2) and [Ledger specifics around multiple coins](https://developers.ledger.com/). You just need to secure the seed phrase and know the paths from which accounts were derived. Even if you lose the paths, a simple search can be done to find them as they are usually sequential. ## Web Wallets ### Option 1: NEAR Wallet \(Recommended for general users\) The [My NEAR Web Wallet](https://app.mynearwallet.com/) provides a way to interact with NEAR network from web without needing to install a wallet. Currently, the NEAR Wallet doesn't allow you to create just a public key. Instead, if you have an allocation of NEAR tokens, ask your facilitator \(e.g. CoinList or the NEAR Foundation\) to send you a NEAR Drop and follow [this guide](https://docs.google.com/document/d/13b3K_9f0YZudFrEAmagM4RcesK3DFxPBE5DswJ37Das). NEAR Wallet also supports Ledger hardware devices for improved security. _Note: currently NEAR Wallet only supports single HD path on Ledger, meaning that all accounts will use the same public key._ #### Importing accounts from other wallets NEAR Wallet supports importing existing accounts from other wallets. Currently only for accounts that have non-zero balance. If you just created an account and have 0 balance on it - you must first fund it via transfer from another account / exchange. 1. Open [https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account](https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account) 2. Enter the seed phrase you have from another wallet This will add an account to your NEAR Wallet. **Importing a TrustWallet Account into NEAR Wallet** You can follow these steps to import your Trust Wallet account into My NEAR Wallet: 1. Go to [https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account](https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account) 2. Enter the 12 word seed phrase for your Trust Wallet account, then click "Find My Account" At this point, your account will have been "restored" into the NEAR Wallet. This means you will be able to sign transactions in the NEAR Wallet. What happens in the background is a new key is added to your account, which is stored in the browser. To add Ledger to your account, first install the NEAR Ledger app: 1. Open Ledger Live 2. Connect your Ledger, and update it to the latest firmware 3. On Ledger Live, go to "Settings" and toggle on Developer Mode 4. Search for and install the NEAR app unto your Ledger Then, on the My NEAR Wallet site: 1. Go to [https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account](https://help.mynearwallet.com/en/articles/44-how-to-recover-your-mynearwallet-account) 2. Scroll down until you see "Hardware Devices" on the right side of the screen, and select "Enable" 3. Follow the instructions on-screen You will be given the option to "Remove all other keys". Choosing "yes" means your Ledger will be required to sign all transactions for your account, which is the most secure option. Your Ledger key will be the only key on your account. ### Option 2: MathWallet Chrome Extension [MathWallet Chrome Extension](https://chrome.google.com/webstore/detail/math-wallet/afbcbjpbpfadlkmhmclhkeeodmamcflc) provides MathWallet interface in the Web via a Chrome Extension. 1. Follow URL above 2. Click "Switch Network" to select NEAR 3a. To create a new wallet use "Create Wallet" 3b. Or select "Import Wallet" to import an existing account: enter seed phrase of the account and account id. ## Mobile Wallets ### Option 1: Trust Wallet [Trust Wallet](https://trustwallet.com/) is a very popular, non-custodial, wallet available on iOS and Android. _Note that, as of October 2020, Trust Wallet does not have plans to enable staking/delegation from the wallet. Moreover, tokens claimed via the NEAR Foundation's claim process should not be directed to Trust Wallet, as the respective tokens might not be transferrable anymore. To transfer tokens you will have to recover the Trust Wallet account in NEAR Wallet by using the Trust Wallet's seed phrase._ _**Setup Trust Wallet and generate public key**_ 1. Install Trust Wallet on your phone from App Store or Play Store 2. Create a new wallet \(or use existing if you already have one setup\) 3. Make sure to back up your recovery seed phase as you would usually do. 4. In "Settings" in upper right corner, toggle NEAR. 5. In the main wallet view, click on "NEAR" and then "Receive". 6. You will see QR code and address in the form `NEAR2F4vDeD9Brbo6cgPAPLMzXrZXza3EXfwS7hrK76SpHwBH4sEud` - this is a public key you can use to claim your tokens. _Note: the current version of Trust Wallet in App / Play Stores doesn't show the actual balance on the account. A new version of Trust Wallet will address this._ ### Option 2: MathWallet * [MathWallet](https://mathwallet.org/) is a multi-platform \(mobile/desktop/hardware\) universal crypto wallet that enables token storage of 50+ chains. MathWallet also has a Chrome extension that supports NEAR, see section below. _**Setup Near Account in MathWallet**_ 1. Install MathWallet on your phone from [https://mathwallet.org/](https://mathwallet.org/). 2. Switch to 'Near' chain. 3. Create/import a Near account. 4. You will see your Near address to send/receive tokens. ### Option 3: Moonlet Wallet [Moonlet](https://moonlet.io/) is a non-custodial digital asset wallet that enables users to securely store their crypto assets, spend their tokens, and manage their return from staking. It's a cross-platform crypto wallet, therefore available on AppStore, Google Play and as a Chrome Extension. _**Setup Moonlet Wallet:**_ Either Create a new wallet, Recover an old one or Connect to your Ledger device. Add NEAR tokens to your main account and start staking to your favourite node. _**Support Pages:**_ * Check here for more about Near Staking within Moonlet including information on connecting to a ledger: [https://moonlet.io/near-staking/](https://moonlet.io/near-staking/) ## Custodians \(Recommended for institutional users\) ### Option 1: Finoa _Status: Currently available_ [Finoa](https://finoa.io/) is the first qualified custodian to offer NEAR asset custody. Check with [Finoa](https://finoa.io/contact) to see if you are eligible and [their NEAR guide](https://www.finoa.io/custody/) for more information about their offering. **Delegation and Staking:** In early phases, users will be able to delegate funds to nodes run by Finoa or provided by Staking Facilities, Chorus One, Certus.One, Blockdaemon, Figment, BisonTrails or T-Systems. ### Option 2: Coinbase _Status: Implementation Phase, no estimated date_ **Delegation and Staking:** Clients can delegate to any validator they want. Coinbase is not going to be running it's own validator, just setting up the functionality for clients to custody their funds with them and delegate to whichever validator they'd like whether that be a third party provider or one they'd like to run themselves. ### Option 3: TBD \(more added soon!\) ## CLI \(Recommended for developers and validators\) ### Option 1: Ledger via CLI For users with advanced security requirements and the need for flexibility \(developers and validators\), we highly recommend using our command line interface [\(NEAR-CLI\)](https://docs.near.org/tools/near-cli) with a Ledger hardware device. This [community-authored guide](https://medium.com/@bonsfi/how-to-use-ledger-with-near-cli-648d5d990517) walks through several common commands. #### Installing the NEAR Ledger App You can install the NEAR Ledger app using [Ledger Live](https://www.ledger.com/ledger-live) by: 1\) Open Ledger Live and install any available firmware updates 2\) Go to `Settings` 3\) Under `Experimental Features` ensure `Developer Mode` is switched on 4\) Return to the `Manager` tab and search for NEAR 5\) Follow instructions to install the NEAR app on your device #### Updating the NEAR Ledger App You will need to have the latest Ledger device firmware installed \(which can be done in Ledger Live's "Manager" tab\) and the latest NEAR app. If you previously installed the NEAR app, it may need to be updated. Currently, while the NEAR app is in Development Mode \(while Ledger finishes reviewing it\), this update may only be possible by uninstalling and reinstalling the app from the "Apps Installed" section of the "Manager" tab. Make sure to quit the Ledger Live app when interacting with your ledger from the CLI or you'll get an error like `Error: cannot open device with path IOService ..........` #### To generate public keys via Web App \[ [Here](https://ledger-keygen.neartools.dev) \] is a simple web application that generates multiple keys using your Ledger device. #### To generate public keys via CLI 1. Make sure [you have npm installed](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 2. Make sure you have quit Ledger Live \(or you'll get an `Error: cannot open device with path IOService ..........` error\) 3. Install `near-cli` via `npm install -g near-cli` \(or similar command on Windows\). Note that you shouldn't use `sudo` as it causes problems with Node.js modules that have native C++ addons. If Node modules are installed in a place inaccessible by your OS user, you need to do `chown -R $USER /path/to/destination/` or equivalent on your OS. 4. Log in your Ledger device and open the NEAR app. A message `Peding Ledger review` will appear. To continue, confirm the receiving of the message by the standard means \(press both buttons on Ledger Nano S\). 5. Use the `near generate-key key --useLedgerKey` command to generate the key for your Ledger device. It will output a _public key_ that can be used to claim your NEAR tokens. Note 1: in the case of generating a key using the Ledger device, the 2nd argument is ignored and can thus be anything. Note 2: This command will output the **same key** no matter how many times it is run. 6. If you want to generate more keys, you will need to provide an [HD path](https://ethereum.stackexchange.com/questions/70017/can-someone-explain-the-meaning-of-derivation-path-in-wallet-in-plain-english-s) as a value to the `--useLedgerKey` flag. Each change in the last number will produce a new key and you can use any number, as the following examples show: ```text # Example 1: near generate-key key --useLedgerKey="44'/397'/0'/0'/2'" # Example 2: near generate-key key --useLedgerKey="44'/397'/0'/0'/11'" ``` 7. After confirming the key on your Ledger device \(which should be opened in the NEAR app\), the result in the console will be the following: ```text Using public key: ed25519:D9Brbo6cgPAPLMzXrZXza3EXfwS7hrK76SpHwBH4sEud ``` ...which is the public key you can use to claiming your NEAR tokens. Note: the key includes the `ed25519:` portion, so the full key is `ed25519:D9Brbo6cgPAPLMzXrZXza3EXfwS7hrK76SpHwBH4sEud` in this example. _Best Practice: Keep a log \(e.g. spreadsheet\) of which HD paths map to which keys and what their purpose is so you don't end up accidentally re-using public keys and potentially de-anonymizing yourself_ ### Option 2: Self custody For professionals who have their own setup, you can self custody on an offline device or any other custom method \(CloudHSM, etc\). Generally, any software that can produce a valid `ed25519` key pair can be used to generate the keys. For NEAR consumption they should be encoded in base58 encoding. For example, if you have an offline device - you can install [near-cli](https://github.com/near/near-cli) via `npm install -g near-cli` and generate keys in the following way: ```bash export NEAR_ENV=mainnet near generate-key some-account-name ``` It will output the public key in the format `Using public key: ed25519:D9Brbo6cgPAPLMzXrZXza3EXfwS7hrK76SpHwBH4sEud`, which is the public key which you can then use for claiming your NEAR tokens \(it includes the `ed25519:` portion, so the full key is `ed25519:D9Brbo6cgPAPLMzXrZXza3EXfwS7hrK76SpHwBH4sEud` in this example\). The private key is stored in the plain-text format in `~/.near-credentials/mainnet/some-account-name.json` #### Verifying Control of Your Account If you have received an account \(e.g. via the account claims process\) associated with one of your Ledger keys, you can do a test transaction to verify if you have control over it. First, look up the key using the [Account Lookup tool](https://near.github.io/account-lookup/). Note the associated Account ID \(the main account\) and the Lockup Account ID, where your tokens are stored if you have a lockup. While you may not be able to move tokens in the lockup account \(due to the lockup!\), you can try a test transfer of `0.01 NEAR` to yourself from yourself using the Account ID. In this example, the full HD Path is used. HD Path 1 is the default used by the ledger anyway but you should replace the final number with whichever is associated with your ledger key: ```text near send YOUR_ACCOUNT_NAME YOUR_ACCOUNT_NAME 0.01 --useLedgerKey="44'/397'/0'/0'/1' ``` #### Using seed phrases in CLI Seed phrases can be generated by any tools \(or offline\), including by other wallet like NEAR Wallet or Trust Wallet. Given seed phrase, you can output keys and do any other actions by specifying seed phrase \(and possibly HD derivation via `-seedPath`\) via command line flags: ```text near generate-key --seedPhrase="words of phrase here" ``` For example, to send money using the seed phrase from another wallet, use: ```text near send <your account> <other account> --seedPhrase="words" ``` **Note:** The default network for `near-cli` is `testnet`. If you would like to change this to `mainnet` or `betanet`, please see [`near-cli` network selection](https://docs.near.org/tools/near-cli#network-selection) for instructions. > Got a question? [Ask it on StackOverflow!](https://stackoverflow.com/questions/tagged/nearprotocol)
--- title: 4.5 Future Creator Economy Developments description: The disappearance of NFTs and a new intuition for internet assets. --- # 4.5 Future Creator Economy Developments → The disappearance of NFTs and a new intuition for internet assets. The goal of this module has been to better understand the future of intangible value - also known as non-fungible tokens or NFTs. Despite the progress of the root technology and the infrastructure surrounding and supporting that technology (Oracles, Indexers, Storage Solutions, etc.), the full application layer of Non-Fungible Tokens (NFTs) has been minimally developed beyond the early digital primitives that encompass digital art, profile pictures, and some early forms of music and content. The focus of this lecture is to better understand how NFTs might evolve into the future: ## Digital Intangibles _“There are endless intangibles that can be moved on-chain. The nice thing about intangibles is that they can be natively digital, and you don’t need a bridge to the physical world.”_ Let’s start with the digital intangibles of the future. Digitally, NFT’s will have free reign to expand exponentially for the following reasons: * **Regulation free:** Meaning they are able to live exclusively in cyberspace and are not required to pay homage to any specific jurisdiction. While a specific project or team may need to relocate or deal with a regulatory body, the value contained in itself is not accessible beyond the digital realm - and hence is in position to thrive globally. * **Instantly Owned:** With account abstraction becoming more important, wallets and addresses are increasingly connected to specific account ID’s. When a user purchases their NFT - irrespective of what kind of NFT it is - the user instantly controls the value of the non-fungible asset. From a financial and usability perspective, this is a major upgrade for users familiar with centralized custodians managing both their digital and physical life. * **Representatives of Non-physical Realities:** In being entirely digital, the represented value is much more customizable than only physical realities: Things like time, participation, AI generated art, objects in the Metaverse, objects in Games, assets (and financial products), as well as access to communities, information, and even music - do not require a single atom to move outside of the digital sphere. This means that the velocity of growth is far better positioned to increase relative to physical non-fungibles tokenized on-chain. From a development perspective, it is much more likely that digital-first NFTs will find product market fit, revenue, and active users, before physical NFTs. That being said, there are trillions of dollars in locked value, which physical NFTs are poised to disrupt: ## Physical Intangibles: Assets from that $77 trillion intangible asset sheet _“We will also trade hotel rooms, and weeks in vacation villa, and billboards, and stadium access. These will also be NFTs. They will be centralized - but for these to happen you the regulatory bridges for the transactions to be enforceable off chain. But there the benefit is, that you are going to move things out of massively fragmented databases, into markets. There is even today, even today in 2022, no market for nights in hotels in SF.”_ As Punk explained in the podcast for a16z, it's clear that there is an obscenely large world of physical non-fungible assets, that await tokenization - with a huge opportunity to create innovative business models at the intersection of Web2 and Web3. Take for example, booking of a hotel room and the tokenization of one night in a hotel room at a specific location: While the booking itself was originally open to everyone, there is no current mechanism today to proposition someone with a booking - if you are someone without a booking. Being able to create a market for the booked hotel room creates optionality, from which users (people looking to stay in the hotel at the last minute) now have an option that has hitherto not been possible. Just as Airbnb provided DIY hosting optionality in an industry dominated by hotels, so NFTs have the opportunity to provide individual monetization optionality for the non-fungible choices we make. ## Physical NFT’s Should Be Understood According to the Following Characteristics * **Will Require Regulatory Underwriting in Some Manner:** This is to say, that it is virtually guaranteed that any physical activity will be done by one or more physical entities, such that these entities will need some form of guidance or regulatory clarity on how they are allowed (or not allowed) to interact with the product at hand. This would apply to real-estate, finance, shipping, supply-chain, real-world entertainment, dining and hospitality, and so forth. More than anything the relevant framework (most likely differing from country to country) would need to provide the basis to guarantee that the activity conducted via the NFT is actually executed physically. In short, that there is a social buy in, to the value designated to the NFT. * **Is widely applicable on a global and fractional scale (baskets of items):** The benefit of physical NFT’s is that instead of remaking the wheel or searching for product market fit in the digital realm, there is an entire world of intangible non-fungible assets, that already exist, and can be readily scaled up - globally. Thus, real-estate, clunky and siloed, can eventually become tokenized, fractionalized, and aggregated globally - such that a single house could be represented by an NFT (and recognized as such) from which it could then be fractionalized into 100 pieces, and combined with 1,000 other houses from around the world with the same structure. These baskets can then be bought or sold, used as collateral, or managed from a distance. The _scale_ of the non-fungible market for physical goods is far larger than that of fungible goods like money or gold. _“It is safe to say that the overall addressable market of NFTs are intangible goods and tangible non-fungible goods which can be tokenized - is utterly gigantic.”_ * **Markets for the enablement of price discovery for new social goods. Moving things out of databases and into markets:** This final value proposition is somewhat controversial depending on the nature of the market, how well the market is regulated, and how much the market is manipulated. But the theoretical possibility remains quite evident: With NFT’s representative of the physical world, we can drastically expand the scope of what can be tokenized, and in what situations value can be exchanged. In a similar manner in which the original internet has democratized information and allowed any company to represent themselves on a website, so the token - and specifically non-fungible revolution - will allow any person or company to create a mechanism of value transfer for the non-fungible value in their life. In principle, this can enable the development of new social goods, such as open bidding on the time of day an activity is carried out. To date in crypto, there is very limited product market fit and experimentation with physical NFT’s beyond limited pilots in fashion, ticketing, and art ownership. The coming two decades suggest that while digital NFT’s may be easier to implement, and faster in attracting users - there is undeniable value in expanding non-fungible tokenization, into the world of physical assets. ## NFT’s and Reality: When ‘NFT’ is No Longer Relevant The original presupposition behind the success of an NFT - and all of crypto for that matter - is that the world has moved on-chain, and native - original content, is being minted in a non-fungible manner. That is to say, gone are the days when YouTube controls a monopoly on video creation, and broadcasters own the full rights to any single event - rather, the event itself, the podcast, the original video - is only accessible to the world, from inside of it’s non-fungible wrapper. _“I believe we are well on our way to **NFTs becoming the "port of entry" for every piece of media on the internet**. This includes the 2D audio/visual and text-based work of the web, and the emerging 3D work that will encompass the metaverse of games and virtual worlds tomorrow.” ([Variant Fund](https://variant.fund/ideas))_ While the road to this reality will undoubtedly take time - in a similar way to that it took close to fifteen years for the internet to become a mainstream staple of business, social life, and communication - the culmination point of ‘adoption’ is when the token is no longer even referred to as non-fungible - but simply as the representation of the non-fungible asset or reality that it represents. All of this is to say, that Non-Fungible tokens (NFTs) are here to stay, and as we progress in our understanding of the business models and use-cases of Non-fungible tokens - in both the digital and the physical domain, we will develop improved intuitions of the technology until it ‘disappears’ from public consciousness, and lives as intangible value built into the world.
--- id: migrate-from-near-lake title: Migrate from NEAR Lake framework sidebar_label: Migrate from Lake framework --- :::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). ::: In this article you'll learn how to migrate your [NEAR Lake Framework](../../../1.concepts/3.advanced/near-lake-framework.md) JavaScript indexer to [Near QueryAPI](intro.md), a fully managed solution to build indexer functions, extract on-chain data, store it in a database, and be able to query it using GraphQL endpoints. :::info Supported languages Currently QueryAPI only supports JavaScript, so if your indexer code uses TypeScript, Python, or Rust, you'll have to re-write your indexing logic in JS before you can migrate it. ::: ## Basic migration build/near-data-infrastructure/lake-framework/building-indexers/js-lake-indexer Let's take a [basic JS indexer](../lake-framework/building-indexers/js-lake-indexer.md) built with NEAR Lake Framework as an example. This indexer simply logs the Block height and the number of shards for each indexed block, using an [indexer handler](../lake-framework/building-indexers/js-lake-indexer.md#create-indexer-handler) function `handleStreamerMessage`. Migrating this basic indexer to QueryAPI is simple. You only need to migrate the code from the `handleStreamerMessage` function: ```js async function handleStreamerMessage(streamerMessage: types.StreamerMessage): Promise<void> { console.log(` Block #${streamerMessage.block.header.height} Shards: ${streamerMessage.shards.length} `); } ``` ### Migrating to QueryAPI 1. To start the migration process, [create a new indexer](../query-api/indexers.md#creating-an-indexer) using [QueryAPI](https://near.org/dataplatform.near/widget/QueryApi.App?view=create-new-indexer). You should see a similar interface like this: ![QueryAPI Indexer Dashboard](/docs/assets/QAPIScreen2.png) 2. Since QueryAPI keeps a compatibility layer with Lake Framework, you don't need to change any references to `streamerMessage` in your indexer function. Just change the function definition to: ```js function handleStreamerMessage(streamerMessage) { // ... Lake framework indexer code } ``` 3. Next, add your migrated indexer function to the `getBlock(...)` method, and simply call your function passing `block.streamerMessage` as parameter: ```js async function getBlock(block: Block) { // Add your code here function handleStreamerMessage(streamerMessage) { console.log(` Block #${streamerMessage.block.header.height} Shards: ${streamerMessage.shards.length} `); } handleStreamerMessage(block.streamerMessage); } ``` That's all! The basic Lake Framework JS indexer has been migrated to QueryAPI, and you can test it out by using [Debug Mode](index-function.md#local-debug-mode). If you run the indexer using local debug mode, you should see an output like: ``` Block #106812523 Shards: 4 ``` ### Database storage If you want to take advantage of QueryAPI's database features, you can also store the indexer results in a Postgres DB. 1. First, create the database schema: ```sql CREATE TABLE "basic" ( "block_height" BIGINT NOT NULL, "shards" INTEGER NOT NULL, PRIMARY KEY ("block_height") ); ``` 2. In your indexer JavaScript code, use the [`context.db`](context.md#db) object to store the results: ```js const basicData = { block_height: streamerMessage.block.header.height, shards: streamerMessage.shards.length, }; context.db.Basic.insert(basicData); ``` ## Advanced migration For this example, let's take the TypeScript [NFT indexer](../lake-framework/building-indexers/nft-indexer.md) built with NEAR Lake Framework as reference. This indexer is watching for `nft_mint` [Events](https://nomicon.io/Standards/EventsFormat) and prints some relevant data about minted NFTs. As with the previous example, moving this NFT indexer to QueryAPI requires to migrate the code from the [`handleStreamerMessage`](https://github.com/near-examples/near-lake-nft-indexer/blob/5acd543c54ce8025bdc9a88d111df43d8d4d05b8/index.ts#L32) function. But since it was done in TypeScript, it also needs some additional work as it needs to re-written in JavaScript. ### Migrating to QueryAPI To migrate the code, you can take advantage of the [`near-lake-primitives`](https://near.github.io/near-lake-framework-js/modules/_near_lake_primitives.html) provided by QueryAPI, and simplify the indexer logic. For example: - to get all [`Events`](https://near.github.io/near-lake-framework-js/classes/_near_lake_primitives.events.Event.html) in a `Block`, you can simply call `block.events()`. - you don't need to iterate through shards and execution outcomes, nor manually parse the `EVENT_JSON` logs to detect events (it's handled by QueryAPI) Here's a JavaScript implementation of the NFT indexer using QueryAPI features, that provides the same output as the original indexer: ```js async function getBlock(block: Block) { let output = []; for (let ev of block.events()) { const r = block.actionByReceiptId(ev.relatedReceiptId); const createdOn = new Date(block.streamerMessage.block.header.timestamp / 1000000); try { let event = ev.rawEvent; if (event.standard === "nep171" && event.event === "nft_mint") { let nfts = []; let marketplace = "unknown"; if (r.receiverId.endsWith(".paras.near")) { marketplace = "Paras"; nfts = event.data.map(eventData => ({ owner: eventData.owner_id, links: eventData.token_ids.map( tokenId => `https://paras.id/token/${r.receiverId}::${tokenId.split(":")[0]}/${tokenId}`) }) ); } else if (r.receiverId.match(/\.mintbase\d+\.near$/)) { marketplace = "Mintbase"; nfts = event.data.map(eventData => { const memo = JSON.parse(eventData.memo) return { owner: eventData.owner_id, links: [`https://mintbase.io/thing/${memo["meta_id"]}:${r.receiverId}`] } }); } output.push({ receiptId: ev.relatedReceiptId, marketplace, createdOn, nfts, }); } } catch (e) { console.log(e); } } if (output.length) { console.log(`We caught freshly minted NFTs!`); console.dir(output, { depth: 5 }); } } ``` That's all! The NFT indexer has been migrated to QueryAPI, and you can test it out by using [Debug Mode](index-function.md#local-debug-mode). If you run the indexer using local debug mode, you should see an output like: ``` Block Height #66264722 We caught freshly minted NFTs! [ { "receiptId": "BAVZ92XdbkAPX4DkqW5gjCvrhLX6kGq8nD8HkhQFVt5q", "marketplace": "Mintbase", "createdOn": "2022-05-24T09:36:00.411Z", "nfts": [ { "owner": "chiming.near", "links": [ "https://mintbase.io/thing/HOTcn6LTo3qTq8bUbB7VwA1GfSDYx2fYOqvP0L_N5Es:vnartistsdao.mintbase1.near" ] } ] } ] ``` ### Database storage If you want to take advantage of QueryAPI's database features, you can also store the indexer results in a Postgres DB. 1. First, create the database schema: ```sql CREATE TABLE "nfts" ( "id" SERIAL NOT NULL, "marketplace" TEXT, "block_height" BIGINT, "timestamp" DATETIME, "receipt_id" TEXT, "nft_data" TEXT, PRIMARY KEY ("id", "block_height") ); ``` 2. In your indexer JavaScript code, use the [`context.db`](context.md#db) object to store the results: ```js // ... previous code ... output.push({ receiptId: ev.relatedReceiptId, marketplace, createdOn, nfts, }); const nftMintData = { marketplace: marketplace, block_height: block.header().height, timestamp: createdOn, receipt_id: r.receiptId, nft_data: JSON.stringify(event.data), }; context.db.Nfts.insert(nftMintData); } } catch (e) { console.log(e); } } // ... code continues ... ``` :::tip You can find the migrated NFT indexer source code by [clicking here](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=bucanero.near/nft_migrated). :::
--- sidebar_position: 2 sidebar_label: "Store multiple puzzles" title: "Store multiple crossword puzzles using a specialized collection in NEAR called a LookupMap" --- import {Github} from "@site/src/components/codetabs" import bookPagination from '/docs/assets/crosswords/paging-through-hashes-swing--pierced_staggg.near--pierced_stag.jpg'; import guardsAroundContract from '/docs/assets/crosswords/guards-contract-permissions--connoisseur_dane.near--connoisseurdane.png'; # Using collections As mentioned in the previous chapter, the [online Rust Book](https://doc.rust-lang.org/stable/book) is a great reference for folks getting started with Rust, but there are concepts that differ when we're dealing with the blockchain. One of these differences is the use of collections. The reference-level documentation of the Rust SDK explains this concept well: :::note Motivation for specialized collections >Collections that offer an alternative to standard containers from [Rust's] std::collections::* by **utilizing the underlying blockchain trie storage more efficiently**.<br/> >For example, the following smart contract does not work with state efficiently, because **it will load the entire HashMap at the beginning of the contract call**, and will save it entirely at the end, in cases when there is state modification. **This is fine for small number of elements, but very inefficient for large numbers**. — [NEAR SDK reference documentation](https://docs.rs/near-sdk/latest/near_sdk/collections/index.html) ::: In chapter 1, we set the crossword puzzle solution hash when we first deployed the contract and called the initialization method `new`, passing it. This would only allow us to have only one puzzle, but let's allow for many. At a high level, let's discuss what we'll want to add if our contract is to store multiple crossword puzzles. First, we'll have the concept of many puzzles where some of them will have different states (unfinished and finished) and we'll want to know which ones are unsolved in quick way. Another thing, which is a general rule of thumb when writing smart contracts, is to anticipate what might happen if it gets a lot of usage. What if we end up with 10,000 crossword puzzles? How might that affect how many data structures we use and which ones? ## LookupMap and UnorderedSet Let's try having two specialized NEAR collections: 1. A [LookupMap](https://docs.rs/near-sdk/latest/near_sdk/collections/struct.LookupMap.html) which will store key-value pairs. (Solution hash » Puzzle object) 2. An [UnorderedSet](https://docs.rs/near-sdk/latest/near_sdk/collections/struct.UnorderedSet.html) containing a set (list with no duplicates) of the solution hashes for puzzles which have not been solved yet. As you look at the list of specialized collections in the Rust SDK, you might notice some begin with `Lookup` while others have `Unordered`. As is written in the reference documentation, the `Lookup` is non-iterable while the `Unordered` collections are iterable. This means if you will need to loop through the list of contents of this data structure, you'll likely use an iterable data structure. If you'll only ever be adding and retrieving data by the key, and the key will always be known, it's more efficient to use a non-iterable collection. So why would we have two data structures here? Again, if we end up with a large number of puzzles, we might not be able to loop through all the puzzles, looking for ones that are unsolved. Because of the limit of gas execution per transaction, we must be conscious that there can be operations which will eventually exceed this limit. I suppose we could assume that our `UnorderedSet` of unsolved puzzles wouldn't contain tens of thousands of puzzles. That's one way to avoid running into limits, but we could also learn how to utilize **pagination** through an iterable collection like an `UnorderedSet` which we'll get to later. <figure> <img src={bookPagination} alt="Book showing pagination of hashes. Art created by pierced_staggg.near" width="600"/> <figcaption>Think of our collection as having multiple pages of puzzle hashes.<br/>Art by <a href="https://twitter.com/pierced_stag" target="_blank">pierced_staggg.near</a></figcaption> </figure> <br/> As we remember from the previous chapter, every smart contract has a primary struct containing the `#[near_bindgen]` macro. :::note Naming the primary struct Note in the [previous chapter](../01-basics/01-set-up-skeleton.md#start-writing-rust) we named our primary struct `Contract`, but in this chapter we'll call it `Crossword.` The name of the struct doesn't matter and there's nothing special about naming it `Contract`, though you might see that convention used in several smart contracts on NEAR. We've named it something different simply to illustrate that there's no magic behind the scenes. This *does* mean, however, that our `impl` block will also be `Crossword`. ::: Here's how our struct will look with the iterable and non-iterable NEAR collections: <Github language="rust" start="73" end="79" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/276217ad82c64c610148e998ec926942ba910a12/contract/src/lib.rs" /> Above, we have the `puzzles` and `unsolved_puzzles` fields which are collections. We also have an `owner_id` so we can exercise a common pattern in smart contract development: implementing a rudimentary permission system which can restrict access to certain functions. We'll expand on this thought in a moment. The snippet below shows the first method in the implementation of the `Crossword` struct, where the `new` function sets up these two specialized collections. <Github language="rust" start="81" end="90" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/276217ad82c64c610148e998ec926942ba910a12/contract/src/lib.rs" /> So during the initialization function (`new`) we're setting the `owner_id`. For our purposes the owner will likely be the contract itself, but there can be several reasons to have it be a DAO or another user. Next, let's look at the `b"c"` and `b"u"` bits for the collection fields. ## Collections have prefixes Above, the `new` function is initializing the struct's fields by giving them a unique prefix. You can learn more about [the prefixes here](/sdk/rust/contract-structure/nesting#traditional-approach-for-unique-prefixes), but know that these prefixes (`c` and `u`) should be short and different. Let's take a peek at how we'll add a new crossword puzzle. Note that there will be a new struct here, `Answer`, which we haven't defined yet. We'll also be introducing the concept of enums, like `PuzzleStatus::Solved` and `PuzzleStatus::Unsolved`. We'll be covering these in the next section. Unlike the previous chapter where there was only one crossword puzzle, we'll be inserting into our new collections, so let's create a `new_puzzle` method. <Github language="rust" start="147" end="163" url="https://github.com/near-examples/crossword-tutorial-chapter-2/blob/8ec941c82539e6eafa4971444e1da9e4819330d3/contract/src/lib.rs" /> Now we're set up to store multiple puzzles! ## Permissions or permissionless? <figure> <img src={guardsAroundContract} alt="Guards or bouncers in front of a futuristic club with the label of a NEAR smart contract. Art created by connoisseur_dane.near" width="600"/> <figcaption>Guarding which accounts can enter the smart contract logic.<br/>Art by <a href="https://twitter.com/connoisseurdane" target="_blank">connoisseur_dane.near</a></figcaption> </figure> <br/> **Is NEAR permissionless?** Yes. **What did you mean by a permission system earlier, and what are the ways you can control permissions?** There are two ways that permissions can be controlled: 1. In the smart contract code itself 2. When using function-call access keys We'll get to the second topic in later in this chapter, but will focus on the first item. As you can see in the previous snippet, the first thing that happens in the `new_puzzle` method is a check. It looks to see if the predecessor (the person who most recently called this method, sometimes the same as the signer) is the same as the `owner_id` that we set during the contract's initialization. If someone else is trying to call `new_puzzle`, this check will fail and the smart contract will panic, going no further. This example is the simplest form of a permission. Much more complex system can exist for users. The SputnikDAO smart contracts, for instance, implement custom policies. It's up the smart contract developer to write their roles/policies and apply them to users. Sometimes an allow-list (or whitelist) is used. In short, **any account with a full-access key can call any method on a smart contract**, but that doesn't mean the smart contract will let them continue execution. It's up to the developer to protect their functions with guards like the one in `new_puzzle`. --- Let's dive into structs and enums next.
--- description: Easily onboard new users to the NEAR ecosystem title: NEARDROP sidebar_position: 5 --- --- [NEARDROP](https://app.neardrop.io) is an easy way to onboard someone new to the NEAR ecosystem by sending them a linkdrop URL to which will send the receiver to the NEAR wallet. In this guide you will learn how to mass-generate onboarding links!\ \ **Warning:** Be sure to store your NEARDROP seed phrase in a safe at step 4, you’ll not be able to recover your Linkdrop account on another device without it. ## **How to mass-generate NEAR onboarding links** #### **1. Go to the** [**NEARDROP Dashboard**](http://app.neardrop.io) #### **2. Connect Wallet** ![NEAR Drop](@site/static/img/neardrop1.png) #### **3. Connect to**[ **mynearwallet.com**](https://app.mynearwallet.com/) ![NEAR Drop](@site/static/img/neardrop2.png) #### **4. Backup your NEAR Linkdrop specific seed phrase** ![NEAR Drop](@site/static/img/neardrop3.png) **5. Deposit 5 NEAR to create your own Linkdrop Smart Contract** ![NEAR Drop](@site/static/img/neardrop4.png) **6. Create new Campaign** ![NEAR Drop](@site/static/img/neardrop5.png) **7. Specify Campaign Details** ![NEAR Drop](@site/static/img/neardrop6.png) #### **8. Confirm Campaign details** ![NEAR Drop](@site/static/img/neardrop7.png) #### **9. Confirm in wallet** **** ![NEAR Drop](@site/static/img/neardrop8.png) #### **10. Success, your drops are ready** ![NEAR Drop](@site/static/img/neardrop9.png) #### **11. Generate Custom QR codes out of the Linkdrop URLs** If you wish to generate QR codes you need to submit each of the URLs into a QR code generator tool like [https://www.qrbatch.com/](https://www.qrbatch.com). You can add colours, your own logo and so forth. Be aware if you wish the QR code to look great you need to also shorten each link using a centralized service like [https://bitly.com/](https://bitly.com). ![NEAR Drop](@site/static/img/neardrop10.png) **12. Receiving a linkdrop** ![NEAR Drop](@site/static/img/neardrop11.png) Claiming a linkdrop is easy, just click the URL or scan a linkdrop QR code #### **Any questions?** If you have any questions, feature requests or encounter any problems join this[ Telegram support channel](https://t.me/joinchat/sPqlT3Zt-mAyNmI0).
--- sidebar_position: 3 sidebar_label: Setup title: RPC Setup --- :::warning Please be advised that these tools and services will be discontinued soon. ::: In order to use the RPC API you will need to setup the correct RPC endpoints: - `POST` for all RPC methods - `JSON RPC 2.0` - `id: "dontcare"` - Endpoint URL varies by network - testnet: `https://near-testnet.api.pagoda.co/rpc/v1/` - mainnet: `https://near-mainnet.api.pagoda.co/rpc/v1/` :::note We are working on supporting historical data access in the next phase. ::: ## API Keys When accessing the NEAR network via a node provider, API services like Pagoda require an API key, which allows developers to monitor personal apps and access usage metrics. :::tip For the best development experience, we recommend that you [sign up for a free API key](get-keys.md). ::: With a dedicated API key, developers are able to: - Access higher request throughput and increased concurrent requests - Query data from [Enhanced APIs](api.md), gaining access to free processed data for NFT, FT and NEAR balances, ownership, and metadata - Utlize dedicated, individualized usage metrics ### Test your API keys To quickly test your API keys and connection, try a simple request from your command line: ```sh curl -X POST -H 'x-api-key:<YOUR-API-KEY>' -H 'Content-Type: application/json' -d '{"jsonrpc": "2.0", "id":"dontcare","method":"status","params":[] }' https://near-testnet.api.pagoda.co/rpc/v1/ ``` ## Postman Setup An easy way to test the queries in this documentation page is to use an API request tool such as [Postman](https://www.postman.com/). You only need to configure two things: 1. Make sure you add a header with a key of `Content-Type` and value of `application/json`. ![postman-setup-header](/docs/assets/postman-setup-headers.png) 2. Then select the `Body` tab and choose the `raw` radio button and ensure `JSON` is the selected format. ![postman-setup-header](/docs/assets/postman-setup-body.png) After that is set up, just copy/paste the `JSON object` example snippets below into the `body` of your request, on Postman, and click `send`. ## Command-line Setup ### NEAR CLI 1. If you don’t yet have `near-cli` installed on your machine, follow the [near-cli installation instructions](https://docs.near.org/tools/near-cli#setup). 2. Set your RPC URL: ``` export NEAR_CLI_TESTNET_RPC_SERVER_URL=https://near-testnet.api.pagoda.co/rpc/v1/ ``` 3. Configure your API key: ``` near set-api-key $NEAR_CLI_TESTNET_RPC_SERVER_URL <your API Key> ``` ### HTTPie Setup {#httpie-setup} If you prefer to use a command line interface, we have provided RPC examples you can use with [HTTPie](https://httpie.org/). Please note that params take either an object or array passed as a string. ```bash http post https://near-testnet.api.pagoda.co/rpc/v1/ jsonrpc=2.0 id=dontcare method=network_info params:='[]' ``` ## JavaScript Setup All of the queries listed in this documentation page can be called using [`near-api-js`](https://github.com/near/near-api-js). :::tip For `near-api-js` installation and setup please refer to `near-api-js` [quick reference documentation](https://docs.near.org/tools/near-api-js/quick-reference#install). ::: Add the following code to get started: ```js const { connect, keyStores } = require("near-api-js"); // Can be an empty object if not signing transactions const keyStore = new keyStores.BrowserLocalStorageKeyStore(); const RPC_API_ENDPOINT = 'https://near-testnet.api.pagoda.co/rpc/v1/'; const API_KEY = '<YOUR-API-KEY>'; const ACCOUNT_ID = 'account.near'; const config = { networkId: 'testnet', keyStore, nodeUrl: RPC_API_ENDPOINT, headers: { 'x-api-key': API_KEY }, }; // Example: Fetching account status async function getState(accountId) { const near = await connect(config); const account = await near.account(accountId); const state = await account.state(); console.log(state); } getState(ACCOUNT_ID); ``` :::info All JavaScript code snippets require a `near` object. For examples of how to instantiate, [click here](https://docs.near.org/tools/near-api-js/quick-reference#connect). ::: ## Rust Setup You can use the [near-jsonrpc-client-rs](https://github.com/near/near-jsonrpc-client-rs) library to communicate with the Pagoda RPC endpoints via JSONRPC. Example of asynchronously fetching the latest block using `tokio`: ```rust use near_jsonrpc_client::{auth, methods, JsonRpcClient}; use near_primitives::types::{BlockReference, Finality}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = JsonRpcClient::connect("https://near-testnet.api.pagoda.co/rpc/v1/") .header(auth::ApiKey::new("<YOUR-API-KEY>")?); let request = methods::block::RpcBlockRequest { block_reference: BlockReference::Finality(Finality::Final), }; let response = client.call(request).await?; println!("{:?}", response); Ok(()) } ``` --- ## Using `block_id` param {#using-block_id-param} The `block_id` param can take either the block number (e.g. `27912554`) or the block hash (e.g. `'3Xz2wM9rigMXzA2c5vgCP8wTgFBaePucgUmVYPkMqhRL'` ) as an argument. :::caution The block IDs of transactions shown in [NEAR Explorer](https://explorer.testnet.near.org) are not necessarily the block ID of the executed transaction. Transactions may execute a block or two after its recorded, and in some cases, can take place over several blocks. Due to this, it is important to to check subsequent blocks to be sure all results related to the queried transaction are discovered. ::: --- ## Using `finality` param {#using-finality-param} The `finality` param has two options: `optimistic` and `final`. 1. `optimistic` uses the latest block recorded on the node that responded to your query _(&lt;1 second delay after the transaction is submitted)_ 2. `final` is for a block that has been validated on at least 66% of the nodes in the network _(usually takes 2 blocks / approx. 2 second delay)_
NEAR and Startup Wise Guys Partner on MetaBUILD’s Pre-Accelerator Program NEAR FOUNDATION February 16, 2023 NEAR Foundation is excited to announce a new partnership with Startup Wise Guys — Europe’s biggest startup accelerator, which has empowered over 350 projects across the world. Together with SWG, the Foundation will bring 20 winning projects from the MetaBUILD III hackathon into an 8-week pre-acceleration program to grow and prepare these new teams to bring their first product iteration to market. The partnership’s goal is to bring great new products to life in Web3. After the hack, NEAR Foundation and Startup Wise Guys will prepare all projects to join accelerators, make their first raise, and launch to market. Startup Wise Guys’ Pre-Acceleration Program for MetaBUILD Let’s go over the program. For this occasion, we’ll be running an 8-week program with Startup Wise Guys, covering everything from finding your project’s mission, to setting up team structure, finance, and communication programs for your brand. Each week covers a specific topic, and will feature both recorded and live events as well as exercises for the projects to take on! Each week, all teams will progress to fleshing out their new project’s company setup, brand, and prepare to launch to market. Throughout the program, Startup Wise Guys and NEAR will aid projects with 1-1 mentorships (invited from the ecosystem and from Startup Wise Guys’ network), pitch training and drills, Q&As, and a folder of ready-to-use learning materials. Week 1: Onboarding Session Onboarding of all projects into the program, and setting expectations for all upcoming weeks and events. Week 2: Setting Goals & KPIs Structuring each project’s journey. How to find a mission and vision for your project long term. Week 3: Problem Definition & Pitching Crafting your project’s pitch and problem-to-be-solved to define your selling points. Week 4: Product development & effective planning Planning the product’s development, and identifying key differentiators to give it unique aspects in the market. Week 5: Focus and Execution Crisis-handling in companies, and pace. How to maintain your team’s rhythm. Week 6: Sales & Team Management Basics Sales, marketing, and branding for early startups and projects. How to define your vector for gaining traction in the world. Week 7: Company Communications, Finances, Fundraising Company communications and finance preparations. How to define your key metrics of success, and prepare a structure to present to investors, as well as how to seek and select the right ones. Week 8: Legal Basics How to register your business, understanding your basic legal structure and needs to get started as a company. Also, going over any regulatory requirements like GDPR, and Intellectual Property, as well as minimizing legal needs. Week 9: Graduation & Pitches! Final day! Graduated projects who completed the program will present their project’s revamped pitches and go out to the world. Come Hack, and Build On! NEAR Foundation can’t wait to see the new exciting projects that will be born from MetaBUILD, and is excited about this new partnership with Startup Wise Guys in 2023. The Foundation will share all progress along the way as we finalize the submission phase of MetaBUILD and move onto judging. So stay tuned and follow all updates on Twitter!
NFTs on NEAR: Where Will NFTs Go Next? COMMUNITY May 26, 2022 For a relatively new type of digital asset, non-fungible tokens, have permeated the mainstream at an incredibly fast rate. After Christie’s auction of Beeple’s “Everydays – The First 5000 Days” NFT in 2021, other artists like Pak and Roger Kilimanjaro followed with their own major NFT sales. And Yuga Labs’ Bored Ape Yacht Club collection, released the the same year, turned cartoonish collectible “cards” into a multi-chain NFT art genre. NFTs exist on the blockchain and typically represent ownership of unique digital collectibles like music, video, artwork, land, and more. But beyond creative works, what other NFT use cases already exist? And what other types of NFTs might emerge in the coming months and years? This feature explores how projects building in the NEAR ecosystem are leveraging NFT technology in new and exciting ways. Open Forest Protocol: NFTs for sustainable climate conservation For many nonprofits and volunteer organizations with a social cause, a major challenge is maintaining complete transparency on their activities. This can include initiatives, funding, and resources, as well as a roadmap for accomplishing their goals. But what if an organization’s work was completely transparent, trustless, and easily accessible to all? NEAR-native decentralized community Open Forest Protocol (OFP) is doing precisely this for its environmental conservation efforts. The team of over 30 forest project operators, validators, and community members is working to scale forest-based climate solutions. To do this, the OFP network uses NFTs to represent forestation projects by tracking their progress and growth over time. Each project’s information is permanently stored and updated in the token’s metadata, making it all 100% transparent and traceable. OFP’s blockchain-based validation model rewards the creation and protection of forested zones. This paves the way for the creation of economic incentives around forest regeneration and carbon sequestration (carbon capture). “We are bringing the entire business of forestation on-chain, making forestation not only scalable, but economically viable where it wasn’t before,” says Rimberjack, who leads community development at OFP. According to Rimberjack, NFTs are important because not all assets on-chain are the traditional coins that immediately come to mind. “NFTs allow the on-chain representation of assets like ‘land’ for projects like OFP which validates data from forests,” says Rimberjack. “This then allows us to tie all the data regarding these forest areas to their unique location and characteristics because the underlying asset is represented non-fungibly.” OFP is currently grappling with two major challenges: a general lack of awareness of carbon markets, and mainstream adoption. Many people know little about carbon markets, carbon credits, and other sustainable financial systems that can better protect our world. “By having forests represented on-chain as NFTs, and storing all the data relevant to it in its metadata, we are able to solve all these problems,” says OFP Forest Project Coordinator Sue. “You now know which forest your carbon credits came from, how many trees were planted, how much carbon they sequestered, and whether the data was verified in a legitimate way. It’s all there in the NFT, open to all to verify.” Naksh Marketplace: NFTs by Indian artists from all walks of life Naksh Marketplace is an Indian NFT platform on NEAR that caters to artists and artisans from across the country. The app works with artists from parts of India where blockchain technology is not commonly known or used. The marketplace helps these artists digitize their work and showcase it as NFTs. The Naksh Marketplace hosts a curated collection of artworks produced in the Indian cultural context. The art includes both traditional and new media. The platform’s goal is to resurrect conversations about the ancient Indian practices and artforms that are starting to fade away. Some of the most pressing issues Naksh is facing today have centered on additional NFT implementations and utilities. “We’ve been seeing a lot of conversations around NFTs and utility recently and that’s something that we have plans around,” says Sri Lakshmi, co-founder of Naksh. “At Naksh we have been working on Redeemable NFTs for the fine art we have on our platform, since the uniqueness, artistic style, colors, and medium that are used by the artists at Naksh are very rare.” According to Lakshmi, there is also a lot of ongoing experimentation at Naksh with the apparel and accessories industry. The marketplace is also looking into expanding into fashion, partnering with fashion brands and providing B2B (business-to-business) services. Naksh could partner with fashion brands to to showcase product as NFTs, which customers could buy as both physical and NFT products. “The entire team has dove headfirst into building the product to ensure that we only show the best version of Naksh, and we are very proud of how our marketplace looks!” says Lakshmi. “When we launched our beta we realized that we hadn’t been paying a lot of attention to our community. We’ve been making up for this over the last few months, and we will continue to ramp this up going forward.” NEAR x Publish: An NFT printing service When Samuel Flores co-founded NEAR x Publish in early 2022, he wanted to create a printing service on NEAR. A service that experimented with both digital and physical media via NFTs. Based in San Diego, Flores and a four-person team began creating products with QR codes and other digital features. The vision paid off, as NEAR x Publish was recently featured as San Diego’s NFTCon’s merchandise partner. Through NEAR x Publish, Flores wants to create different, customizable roadmaps for creators to come in and launch their project. How this process unfolds will depend on the creator’s wants and needs. Flores himself is a comic book artist who wanted to create comic book NFT. He parlayed this ambition into work as a colorist and letterer for NFT marketplace Paras Comic. While at Paras Comic, Flores experimented with different marketing and exposure strategies. In the process, he learned a lot about the NFT industry. More recently, the NEAR x Publish team has been focused on building different partnerships with creators and other NFT marketplaces. The goal is to tie all the resources in the NEAR ecosystem together, rather than projects operating in isolation. “When I first entered the NEAR ecosystem, I noticed everyone was super encouraging,” says Flores. “But I also didn’t see a ton of collaboration between guilds and businesses building in the same space.” Flores says that many NFT projects, particularly PFP (profile picture) projects, have one particular idea they want to execute. But after realizing that idea, they aren’t sure what to do next. “The idea was to have an idea of where we want things to go from the beginning so it’s not just a dead end,” says Flores. “So, building roadmaps to facilitate all these different ideations and bringing them full circle.” NEAR x Publish recently collaborated with NEAR Hub, a metaverse experience users can log into using just their NEAR wallets. Within this NEARverse, users have control and ownership of their data and assets. The two projects just launched comics.nearhub.club – a generative comic book cover generator that creates 1 of 1 comic book covers. NEAR x Publish has several upcoming projects in the pipeline. It’s helping the Marma J Foundation, an organizationo on NEAR that is leveraging Web3 technology for social good. And this June, NEAR x Publish is also will be a sponsored partner at the NEAR Hacker House during the Consensus conference in Austin, Texas. Endemic: Carbon-Neutral NFTs with Social Elements The word endemic is often used to describe something native and restricted to a certain place. That’s what Hrvoje Zuanić and Milan Mašanović wanted to build with Endemic, a multichain, carbon-neutral NFT marketplace with social elements. Launched on the Aurora network in February, Endemic showcases quality art from reputable sources to a global network of high-net-worth individuals and institutional collectors. Its art collection comes from artist communities in every part of the world. The Endemic team consists of around 20 members who work in art, curation, development and marketing. The marketplace prides itself on its organic community of a combined 5,000 users across different social media platforms. “We know that a lot of marketplaces pump up their numbers with fake followers and have botted up accounts, so Endemic is taking a completely different and alternative approach,” says co-founder Zuanić. “Of course, we could pump up our numbers artificially but that’s just a short-term pump that has no foundation in your product quality and innovation. We think that it’s most important to focus on the product quality, and when the product is 100% ready then do a big marketing push.” Endemic is the only NFT marketplace whose core team includes a curator and art team. Every piece is curated and carefully selected based on quality and social visibility. Endemic’s embedded social elements, which inludde liking, following, comments and blogging enables artists to make deeper connections. These features also allows artists to grow their audience, and present their art in the best possible way. “Some say that physical art is not suitable for crypto—we disagree,” says Mašanović. “By educating the masses we’re trying to shorten the needed period of time for people to transfer feelings and attachments from the physical world to digital.” Endemic offers both NFTs and physical redeemable art. There are no primary or secondary fees—only a fixed percentage of 2.5% from the buyer and 2.5% from the seller. Artists can also set royalties from 1 to 15%. “Digital ownership is something that we’re going to face more and more, and the new generations are more aware of it. It’s more important to them and we’re going to see even more adaption than we had until now,” says Zuanić. “In every business, especially with marketplaces and NFTs, feedback is important and with social components, there is a two-way conversation all the time. Art can get feedback from customers, users, collectors, community and vice versa—it’s great for the quality of the art, for the quality of the community and the whole sphere.” A Bright Future Ahead? The NFT projects that are building on NEAR play vital roles in the ecosystem. Not only are they expanding use cases but they are also pushing these unique digital assets further into the mainstream. Projects like Open Forest Project, Naksh Market, NEAR x Publish and Endemic are paving the way new and exciting NFT use cases. This will allow NFTs to go beyond art and collectibles into assets that can bring communities together and improve the world as we know it.
--- id: skeleton title: Skeleton and JavaScript Architecture sidebar_label: Contract Architecture --- import {Github} from "@site/src/components/codetabs" > In this article, you'll learn about the basic architecture behind the NFT contract that you'll develop while following this _"Zero to Hero"_ series. > You'll discover the contract's layout and you'll see how the JavaScript files are structured in order to build a feature-complete smart contract. ## Introduction This tutorial presents the code skeleton for the NFT smart contract and its file structure. You'll find how all the functions are laid out as well as the missing JS code that needs to be filled in. Once every file and function has been covered, you'll go through the process of building the mock-up contract to confirm that everything is working correctly. ## File structure Following a regular [JavaScript](https://www.javascript.com/) project, the file structure for this smart contract has: - `package.json` file to define the packages and scripts used in the project. - `src` folder where all the JavaScript source files are stored - `build` folder where the compiled `wasm` will output to. ### Source files | File | Description | | -------------------------------- | -------------------------------------------------------------------------------- | | [approval.ts](#approvalts) | Has the internal functions that controls the access and transfers of non-fungible tokens. | | [enumeration.ts](#enumerationts) | Contains the internal methods to query for NFT tokens and their owners. | | [index.ts](#indexts) | Holds the exposed smart contract functions. | | [metadata.ts](#metadatats) | Defines the token and metadata structures. | | [mint.ts](#mintts) | Contains the internal token minting logic. | | [nft_core.ts](#nft_corets) | Has the internal core logic that allows you to transfer NFTs between users. | | [royalty.ts](#royaltyts) | Contains the internal payout-related functions. | ``` nft-tutorial-js └── src market-contract nft-contract ├── approval.ts ├── enumeration.ts ├── index.ts ├── metadata.ts ├── mint.ts ├── nft_core.ts └── royalty.ts ``` :::tip Explore the code in our [GitHub repository](https://github.com/near-examples/nft-tutorial-js/tree/1.skeleton). ::: --- ## `approval.ts` > This allows people to approve other accounts to transfer NFTs on their behalf. This file contains the internal logic that complies with the standard's [approvals management](https://nomicon.io/Standards/Tokens/NonFungibleToken/ApprovalManagement) extension. Here is a breakdown of the methods and their functions: | Method | Description | | ------------------- | --------------------------------------------------------------------------------------------------------- | | **internalNftApprove** | Approves an account ID to transfer a token on your behalf. Called during **nft_approve**. | | **internalNftIsApproved** | Checks if the input account has access to approve the token ID. Called during **nft_is_approved**. | | **internalNftRevoke** | Revokes a specific account from transferring the token on your behalf. Called during **nft_revoke**. | | **internalNftRevokeAll** | Revokes all accounts from transferring the token on your behalf. Called during **nft_revoke_all**. | <Github language="js" start="9" end="69" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/approval.ts" /> You'll learn more about these functions in the [approvals section](/tutorials/nfts/js/approvals) of the Zero to Hero series. --- ## `enumeration.ts` > This file provides the internal functions needed to view information about NFTs, and follows the standard's [enumeration](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration) extension. | Method | Description | | ------------------------ | ---------------------------------------------------------------------------------- | | **internalNftTotalSupply** | Returns the total amount of NFTs stored on the contract. Called during **nft_total_supply**. | | **internalNftTokens** | Returns a paginated list of NFTs stored on the contract regardless of their owner. Called during **nft_tokens**. | | **internalNftSupplyForOwner** | Allows you view the total number of NFTs owned by any given user. Called during **nft_supply_for_owner**. | | **internalNftTokensForOwner** | Returns a paginated list of NFTs owned by any given user. Called during **nft_tokens_for_owner**. | <Github language="js" start="8" end="62" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/enumeration.ts" /> You'll learn more about these functions in the [enumeration section](/tutorials/nfts/js/enumeration) of the tutorial series. --- ## `metadata.ts` > This file is used to keep track of the information to be stored for tokens, and metadata. > In addition, you can define a function to view the contract's metadata which is part of the standard's [metadata](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata) extension. | Name | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------- | | **TokenMetadata** | This structure defines the metadata that can be stored for each token. (title, description, media, etc. | | **Token** | This structure outlines what information will be stored on the contract for each token. | | **JsonToken** | When querying information about NFTs through view calls, the return information is stored in this JSON token. | | **internalNftMetadata** | This function allows users to query for the contact's internal metadata. Called during **nft_metadata**. | <Github language="js" start="12" end="46" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/metadata.ts" /> You'll learn more about these functions in the [minting section](/tutorials/nfts/js/minting) of the tutorial series. --- ## `mint.ts` > Contains the internal token minting logic. | Method | Description | | ------------ | ----------------------------------------- | | **internalNftMint** | This function mints a non-fungible token. Called during **nft_mint**. | <Github language="js" start="7" end="23" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/mint.ts" /> --- ## `nft_core.ts` > Core logic that allows you to transfer NFTs between users. | Method | Description | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **internalNftTransfer** | Transfers an NFT to a receiver ID. Called during **nft_transfer**. | | **internalNftTransferCall** | Transfers an NFT to a receiver and calls a function on the receiver ID's contract. The function returns `true` if the token was transferred from the sender's account. Called during **nft_transfer_call**. | | **internalNftToken** | Allows users to query for the information about a specific NFT. Called during **nft_token**. | | | **internalNftResolveTransfer** | When you start the `nft_transfer_call` and transfer an NFT, the standard dictates that you should also call a method on the receiver's contract. If the receiver needs you to return the NFT to the sender (as per the return value of the `nft_on_transfer` method), this function allows you to execute that logic. Called during **nft_resolve_transfer**. | <Github language="js" start="10" end="85" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/nft_core.ts" /> You'll learn more about these functions in the [minting section](/tutorials/nfts/js/minting) of the tutorial series. --- ## `royalty.ts` > Contains the internal payout-related functions. | Method | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------------- | | **internalNftPayout** | This internal method calculates the payout for a given token. Called during **nft_payout**. | | **internalNftTransferPayout** | Internal method to transfer the token to the receiver ID and return the payout object that should be paid for a given balance. Called during **nft_transfer_payout**. | <Github language="js" start="7" end="45" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/royalty.ts" /> You'll learn more about these functions in the [royalty section](/tutorials/nfts/js/royalty) of the tutorial series. --- ## `index.ts` > This file outlines the smart contract class and what information it stores and keeps track of. In addition, it exposes all public facing methods that are callable by the user. | Method | Description | | -------------------- | ----------------------------------------------------------------------------------------------- | | **init** | Constructor function used to initialize the contract with some metadata and default state. | | **nft_mint** | Calls the internal mint function to mint an NFT. | | **nft_token** | Calls the internal function to query for info on a specific NFT | | **nft_transfer** | Calls the internal function to transfer an NFT | | **nft_transfer_call** | Calls the internal function to transfer an NFT and call `nft_on_transfer` on the receiver's contract | | **nft_resolve_transfer** | Calls the internal function to resolve the transfer call promise.| | **nft_is_approved** | Calls the internal function to check whether someone is approved for an NFT| | **nft_approve** | Calls the internal function to approve someone to transfer your NFT| | **nft_payout** | Calls the internal function to query for the payout object for an NFT| | **nft_transfer_payout** | Calls the internal function to transfer an NFT and return the payout object. | | **nft_revoke** | Calls the internal function to revoke someone access to transfer your NFT| | **nft_revoke_all** | Calls the internal function to revoke everyone's access to transfer your NFT| | **nft_total_supply** | Calls the internal function to query the total supply of NFTs on the contract.| | **nft_tokens** | Calls the internal function to paginate through NFTs on the contract| | **nft_tokens_for_owner** | Calls the internal function to paginate through NFTs for a given owner| | **nft_supply_for_owner** | Calls the internal function to query for the total number of NFTs owned by someone.| | **nft_metadata** | Calls the internal function to query for the contract's metadata| <Github language="js" start="16" end="157" url="https://github.com/near-examples/nft-tutorial-js/blob/1.skeleton/src/nft-contract/index.ts" /> You'll learn more about these functions in the [minting section](/tutorials/nfts/js/minting) of the tutorial series. --- ## Building the skeleton - If you haven't cloned the main repository yet, open a terminal and run: ```sh git clone https://github.com/near-examples/nft-tutorial-js/ ``` - Next, switch to the `1.skeleton` branch. - Install the dependencies (including the JS SDK): `yarn` - Build the contract with `yarn build`: ```sh git clone https://github.com/near-examples/nft-tutorial-js/ cd nft-tutorial-js git checkout 1.skeleton yarn && yarn build ``` Once this finishes, the `nft-tutorial-js/build` directory should contain the `nft.wasm` smart contract! Building the skeleton is useful to validate that everything works properly and that you'll be able to compile improved versions of this NFT contract in the upcoming tutorials. --- ## Conclusion You've seen the layout of this NFT smart contract, and how all the functions are laid out across the different source files. Using `yarn`, you've been able to compile the contract, and you'll start fleshing out this skeleton in the next [Minting tutorial](/tutorials/nfts/js/minting). :::note Versioning for this article At the time of this writing, this example works with the following versions: - near-sdk-js: `0.4.0-5` - NFT standard: [NEP171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core), version `1.0.0` :::
NEAR and Nansen Partner on On-Chain Analytics for Founders and Investors NEAR FOUNDATION April 18, 2023 NEAR Foundation is excited to announce a new partnership with Nansen, a blockchain analytics firm, on advanced tools for dApp developers and investors. Led by the NEAR Balkans Hub, the partnership with Nansen will give developers and investors new insights and data-driven solutions, like real-time data on transactions, addresses, and network activity. “We are excited to join forces with Nansen to offer our developer community even more valuable insights,” says Marieke Flament, CEO of the NEAR Foundation. “This partnership enables us to enhance our ecosystem and bring advanced analytics tools and data-driven insights to the forefront of the Web3 movement, ultimately accelerating the widespread adoption of decentralized applications.” Nansen gives users access to billions of on-chain data points With Nansen’s analytics platform, developers, investors, and other users get a comprehensive view of blockchain activity. This includes transaction flows, wallet holdings, and on-chain activity. Nansen enables users to analyze billions of on-chain data points with over 250m+ wallet addresses across multiple blockchains, discover opportunities, perform due diligence, and defend their portfolios with real-time dashboards and alerts. The platform also provides users with a suite of tools for monitoring blockchain projects and tracking their performance. Alex Svanevik, CEO of Nansen, said that the platform is excited to join NEAR Foundation in giving NEAR in expediting “the next chapter of Web3 and empower[ing] developers to craft even more robust dApps.” “We’re proud to have led this partnership — our commitment to enabling future Web3 creators is reflected in everything we do, and we are excited to unlock that potential through the power of decentralization,” adds Ida Pandur, CEO of NEAR Balkans. “At the heart of our mission is a desire to empower individuals to create and innovate in a brand new way, and we are committed to continuing our efforts to make this vision a reality.” As NEAR evolves into the Blockchain Operating System, a common layer for browsing and discovering open web experiences, compatible with all blockchains, this collaboration will help drive innovation on NEAR and onboard many new developers, investors, and end users into Web3.
```rust // Set of possible action to take #[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Debug)] #[serde(crate = "near_sdk::serde")] pub enum Action { // Action to add proposal. Used internally. AddProposal, // Action to remove given proposal. Used for immediate deletion in special cases. RemoveProposal, // Vote to approve given proposal or bounty. VoteApprove, // Vote to reject given proposal or bounty. VoteReject, // Vote to remove given proposal or bounty (because it's spam). VoteRemove, // Finalize proposal, called when it's expired to return the funds // (or in the future can be used for early proposal closure). Finalize, // Move a proposal to the hub to shift into another DAO. MoveToHub, } // Validator interface, for cross-contract calls #[ext_contract(ext_dao_contract)] trait ExternalDaoContract { fn act_proposal(&mut self, id: u64, action: Action, memo: Option<String>) -> Promise; } // Implement the contract structure #[near_bindgen] impl Contract { #[payable] pub fn act_proposal(&mut self, id: u64, action: Action, memo: Option<String>) -> Promise { let promise = ext_dao_contract::ext(self.dao_contract.clone()) .with_attached_deposit(env::attached_deposit()) .with_static_gas(Gas(10*TGAS)) .act_proposal(id, action, memo); return promise.then( // Create a promise to callback query_greeting_callback Self::ext(env::current_account_id()) .external_common_callback() ) } #[private] // Public - but only callable by env::current_account_id() pub fn external_common_callback(&self, #[callback_result] call_result: Result<(), PromiseError>) { // Check if the promise succeeded if call_result.is_err() { log!("There was an error contacting external contract") } } } ```
# GenesisConfig ## protocol_version _type: u32_ Protocol version that this genesis works with. ## genesis_time _type: DateTime_ Official time of blockchain start. ## genesis_height _type: u64_ Height of the genesis block. Note that genesis height is not necessarily 0. For example, mainnet genesis height is `9820210`. ## chain_id _type: String_ ID of the blockchain. This must be unique for every blockchain. If your testnet blockchains do not have unique chain IDs, you will have a bad time. ## num_block_producers _type: u32_ Number of block producer seats at genesis. ## block_producers_per_shard _type: [ValidatorId]_ Defines number of shards and number of validators per each shard at genesis. ## avg_fisherman_per_shard _type: [ValidatorId]_ Expected number of fisherman per shard. ## dynamic_resharding _type: bool_ Enable dynamic re-sharding. ## epoch_length _type: BlockIndex,_ Epoch length counted in blocks. ## gas_limit _type: Gas,_ Initial gas limit for a block ## gas_price _type: Balance,_ Initial gas price ## block_producer_kickout_threshold _type: u8_ Criterion for kicking out block producers (this is a number between 0 and 100) ## chunk_producer_kickout_threshold _type: u8_ Criterion for kicking out chunk producers (this is a number between 0 and 100) ## gas_price_adjustment_rate _type: Fraction_ Gas price adjustment rate ## runtime_config _type: [RuntimeConfig](RuntimeConfig.md)_ Runtime configuration (mostly economics constants). ## validators _type: [AccountInfo]_ List of initial validators. ## records _type: Vec\<[StateRecord](StateRecord.md)\>_ Records in storage at genesis (get split into shards at genesis creation). ## transaction_validity_period _type: u64_ Number of blocks for which a given transaction is valid ## developer_reward_percentage _type: Fraction_ Developer reward percentage. ## protocol_reward_percentage _type: Fraction_ Protocol treasury percentage. ## max_inflation_rate _type: Fraction_ Maximum inflation on the total supply every epoch. ## total_supply _type: Balance_ Total supply of tokens at genesis. ## num_blocks_per_year _type: u64_ Expected number of blocks per year ## protocol_treasury_account _type: AccountId_ Protocol treasury account ## protocol economics > For the specific economic specs, refer to [Economics Section](../Economics/Economic.md).
--- NEP: 393 Title: Soulbound Token Authors: Robert Zaremba <@robert-zaremba> DiscussionsTo: Status: Approved Type: Standards Track Category: Contract Created: 12-Sep-2022 Requires: --- # NEP: Soulbound Token ## Summary Soulbound Token (SBT) is a form of a non-fungible token which represents an aspect of an account: _soul_. [Transferability](#transferability) is limited only to a case of recoverability or a _soul transfer_. The latter must coordinate with a registry to transfer all SBTs from one account to another, and _banning_ the source account. SBTs are well suited for carrying proof-of-attendance, proof-of-unique-human "stamps" and other similar credibility-carriers. ## Motivation Recent [Decentralized Society](https://www.bankless.com/decentralized-society-desoc-explained) trends open a new area of Web3 research to model various aspects of what characterizes humans. Economic and governance value is generated by humans and their relationship. SBTs can represent the commitments, credentials, and affiliations of “Souls” that encode the trust networks of the real economy to establish provenance and reputation. > More importantly, SBTs enable other applications of increasing ambition, such as community wallet recovery, Sybil-resistant governance, mechanisms for decentralization, and novel markets with decomposable, shared rights. We call this richer, pluralistic ecosystem “Decentralized Society” (DeSoc)—a co-determined sociality, where Souls and communities come together bottom-up, as emergent properties of each other to co-create plural network goods and intelligences, at a range of scales. Creating strong primitives is necessary to model new innovative systems and decentralized societies. Examples include reputation protocols, non-transferrable certificates, non-transferrable rights, undercollateralized lending, proof-of-personhood, proof-of-attendance, proof-of-skill, one-person-one-vote, fair airdrops & ICOs, universal basic income, non KYC identity systems, Human DAOs and methods for Sybil attack resistance. We propose an SBT standard to model protocols described above. _Verifiable Credentials_ (VC) could be seen as subset of SBT. However there is an important distinction: VC require set of claims and privacy protocols. It would make more sense to model VC with relation to W3 DID standard. SBT is different, it doesn't require a [resolver](https://www.w3.org/TR/did-core/#dfn-did-resolvers) nor [method](https://www.w3.org/TR/did-core/#dfn-did-methods) registry. For SBT, we need something more elastic than VC. ## Specification Main requirement for Soulbound tokens is to bound an account to a human. A **Soul** is an account with SBTs, which are used to define account identity. Often non transferrable NFT (an NFT token with a no-op transfer function) is used to implement SBTs. However, such model is rather shortsighted. Transferability is required to allow users to either recover their SBTs or merge between the accounts they own. At the same time, we need to limit transferability to assure that an SBTs is kept bound to the same _soul_. We also need an efficient on way to make composed ownership queries (for example: check if an account owns SBT of class C1, C2 and C3 issued by issuer I1, I2 and I3 respectively) - this is needed to model emergent properties discussed above. We introduce a **soul transfer**: an ability for user to move ALL SBT tokens from one account to another in a [semi atomic](#soul-transfer) way, while keeping the SBT bounded to the same _soul_. This happens when a user needs to merge his accounts (e.g. they started with a few different accounts but later decides to merge them to increase an account reputation). Soul transfer is different than a token transfer. The standard forbids a traditional token transfer functionality, where a user can transfer individual tokens. That being said, a registry can have extension functions for more advanced scenarios, which could require a governance approval. SBT standard separates the token issuer concept from the token registry in order to meet the requirements listed above. In the following sections we discuss the functionality of an issuer and registry. ### SBT Registry Traditional Token model in NEAR blockchain assumes that each token has it's own balance book and implements the authorization and issuance mechanism in the same smart contract. Such model prevents atomic _soul transfer_ in the current NEAR runtime. When token balance is kept separately in each SBT smart contract, synchronizing transfer calls to all such contracts to assure atomicity is not possible at scale. We need an additional contract, the `SBT Registry`, to provide atomic transfer of all user SBTs and efficient way to ban accounts in relation to the Ban event discussed below. This, and efficient cross-issuer queries are the main reasons SBT standards separates that token registry and token issuance concerns. Issuer is an entity which issues new tokens and potentially can update the tokens (for example execute renewal). All standard modification options are discussed in the sections below. Registry is a smart contract, where issuers register the tokens. Registry provides a balance book of all associated SBTs. Registry must ensure that each issuer has it's own "sandbox" and issuers won't overwrite each other. A registry provides an efficient way to query multiple tokens for a single user. This will allow implementation of use cases such us: - SBT based identities (main use case of the `i-am-human` protocol); - SBT classes; - decentralized societies. ```mermaid graph TB Issuer1--uses--> Registry Issuer2--uses--> Registry Issuer3--uses--> Registry ``` We can have multiple competing registries (with different purpose or different management scheme). An SBT issuer SHOULD opt-in to a registry before being able to use registry. Registries may develop different opt-in mechanisms (they could differ by the approval mechanism, be fully permissioned etc..). One SBT smart contract can opt-in to: - many registries: it MUST relay all state change functions to all registries. - or to no registry. We should think about it as a single token registry, and it MUST strictly implement all SBT Registry query functions by itself. The contract address must be part of the arguments, and it must check that it equals to the deployed account address (`require!(ctr == env::current_account_id())`). It also MUST emit related events by itself. We recommend that each issuer will use only one registry to avoid complex reconciliation and assure single source of truth. The registry fills a central and important role. But it is **not centralized**, as anyone can create their own registry and SBT issuers can choose which registry to use. It's also not too powerful, as almost all of the power (mint, revoke, burn, recover, etc) still remains with the SBT issuer and not with the registry. #### Issuer authorization A registry can limit which issuers can use registry to mint SBTs by implementing a custom issuer whitelist methods (for example simple access control list managed by a DAO) or keep it fully open (allowing any issuer minting withing the registry). Example: an `SBT_1 Issuer` wants to mint tokens using the `SBT_Registry`. The `SBT_Registry` has a DAO which votes on adding a new issuer: ```mermaid sequenceDiagram actor Issuer1 as SBT_1 Issuer actor DAO participant SBT_Registry Note over Issuer1,DAO: Issuer1 connects with the DAO<br>to be whitelisted. Issuer1-->>DAO: request whitelist DAO->>SBT_Registry: whitelist(SBT_1 Issuer) ``` #### Personal Identifiable Information Issuers must not include any PII into any SBT. ### Account Ban `Ban` is an event emitted by a registry signaling that the account is banned, and can't own any SBT. Registry must return zero for every SBT supply query of a banned account. Operations which trigger soul transfer must emit Ban. A registry can emit a `Ban` for use cases not discussed in this standard. Handling it depends on the registry governance. One example is to use social governance to identify fake accounts (like bots) - in that case the registry should allow to emit `Ban` and block a scam soul and block future transfers. NOTE: an SBT Issuer can have it's own list of blocked accounts or allowed only accounts. ### Minting Minting is done by issuer calling `registry.sbt_mint(tokens_to_mint)` method. Standard doesn't specify how a registry authorizes an issuer. A classical approach is a whitelist of issuers: any whitelisted issuer can mint any amount of new tokens. Registry must keep the balances and assign token IDs to newly minted tokens. Example: Alice has two accounts: `alice1` and `alice2` which she used to mint tokens. She is getting tokens from 2 issuers that use the same registry. Alice uses her `alice1` account to interact with `SBT_1 Issuer` and receives an SBT with token ID = 238: ```mermaid sequenceDiagram actor Alice actor Issuer1 as SBT_1 Issuer participant SBT1 as SBT_1 Contract participant SBT_Registry Issuer1->>SBT1: sbt_mint(alice1, metadata) activate SBT1 SBT1-)SBT_Registry: sbt_mint([[alice1, [metadata]]]) SBT_Registry->>SBT_Registry: emit Mint(SBT_1_Contract, alice1, [238]) SBT_Registry-)SBT1: [238] deactivate SBT1 Note over Alice,SBT_Registry: now Alice can query registry to check her SBT Alice-->>SBT_Registry: sbt(SBT_1_Contract, 238) SBT_Registry-->>Alice: {token: 238, owner: alice1, metadata} ``` With `SBT_2 Issuer`, Alice uses her `alice2` account. Note that `SBT_2 Contract` has different mint function (can mint many tokens at once), and validates a proof prior to requesting the registry to mint the tokens. ```mermaid sequenceDiagram actor Alice actor Issuer2 as SBT_2 Issuer participant SBT2 as SBT_2 Contract participant SBT_Registry Issuer2->>SBT2: sbt_mint_multi([[alice2, metadata2], [alice2, metadata3]], proof) activate SBT2 SBT2-)SBT_Registry: sbt_mint([[alice2, [metadata2, metadata3]]]) SBT_Registry->>SBT_Registry: emit Mint(SBT_2_Contract, alice2, [7991, 7992]) SBT_Registry-)SBT2: [7991, 1992] deactivate SBT2 Note over Alice,SBT_Registry: Alice queries one of her new tokens Alice-->>SBT_Registry: sbt(SBT_2_Contract, 7991) SBT_Registry-->>Alice: {token: 7991, owner: alice2, metadata: metadata2} ``` ### Transferability Safeguards are set against misuse of SBT transfer and keep the _soul bound_ property. SBT transfer from one account to another should be strictly limited to: - **revocation** allows issuer to invalidate or burn an SBT in case a token issuance should be reverted (for example the recipient is a Sybil account, that is an account controlled by an entity trying to create the false appearance); - **recoverability** in case a user's private key is compromised due to extortion, loss, etc. Users cannot recover an SBT only by themselves. Users must connect with issuer to request recoverability or use more advanced mechanism (like social recoverability). The recovery function provides additional economical cost preventing account trading: user should always be able to recover his SBT, and move to another, not banned account. - **soul transfer** - moving all SBT tokens from a source account (issued by all issuers) to a destination account. During such transfer, SBT registry emits `SoulTransfer` and `Ban` events. The latter signals that the account can't host nor receive any SBT in the future, effectively burning the identity of the source account. This creates an inherit cost for the source account: it's identity can't be used any more. Registry can have extension functions for more advanced scenarios, which could require a governance mechanism. `SoulTransfer` event can also trigger similar actions in other registries (specification for this is out of the scope of this NEP). This becomes especially important for proof-of-human stamps that can only be issued once per user. #### Revocation An issuer can revoke SBTs by calling `registry.sbt_revoke(tokens_to_revoke, burn)`. Example: when a related certificate or membership should be revoked, when an issuer finds out that there was an abuse or a scam, etc...). Registry, when receiving `sbt_revoke` request from an issuer must always emit the `Revoke` event. Registry must only accept revoke requests from a valid issuer, and only revoke tokens from that issuer. If `burn=true` is set in the request, then the token should be burned and `Burn` event must be emitted. Otherwise (when `burn=false`) the registry must update token metadata and set expire date to a time in the past. Registry must not ban nor emit `Ban` event when revoking a contract. That would create an attack vector, when a malicious registry would thread the registry by banning accounts. #### Recoverability Standard defines issuer recoverability. At minimum, the standard registry exposes `sbt_recover` method, which allows issuer to reassign a token issued by him from one account to another. SBT recovery MUST not trigger `SoulTransfer` nor `Ban` event: malicious issuer could compromise the system by faking the token recovery and take over all other SBTs from a user. Only the owner of the account can make a Soul Transfer transaction and merge 2 accounts they owns. #### Recoverability within an SBT Registry SBT registry can define it's own mechanism to atomically recover all tokens related to one account and execute soul transfer to another account, without going one by one through each SBT issuer (sometimes that might be even not possible). Below we list few ideas a Registry can use to implement recovery: - KYC based recovery - Social recovery ![Social Recovery, Image via “Decentralized Society”](https://bankless.ghost.io/content/images/public/images/cdb1fc23-6179-44f0-9bfe-e5e5831492f7_1399x680.png) SBT Registry based recovery is not part of this specification. #### Soul Transfer The basic use case is described above. Registry MUST provide a permissionless method to allow any user to execute soul transfer. It is essential part of the standard, but the exact interface of the method is not part of the standard, because registries may adopt different mechanism and require different arguments. Soul transfers must be _semi atomic_. That is, the holder account must be non operational (in terms of SBT supply) until the soul transfer is completed. Given the nature of NEAR blockchain, where transactions are limited by gas, big registries may require to implement the Soul Transfer operation in stages. Source and destination accounts should act as a non-soul accounts while the soul transfer operation is ongoing. For example, in the first call, contract can lock the account, and do maximum X amount of transfers. If the list of to be transferred SBTs has not been exhausted, the contract should keep locking the account and remember the last transferred SBT. Subsequent calls by the same user will resume the operation until the list is exhausted. Soul Transfer must emit the `SoulTransfer` event. Example: Alice has two accounts: `alice1` and `alice2` which she used to mint tokens (see [mint diagram](#minting)). She decides to merge the accounts by doing Soul Transfer. ```mermaid sequenceDiagram actor Alice participant SBT_Registry Alice->>SBT_Registry: sbt_soul_transfer(alice1) --accountId alice2 Alice-->>+SBT_Registry: sbt_tokens_by_owner(alice2) SBT_Registry-->>-Alice: [] Alice-->>+SBT_Registry: sbt_tokens_by_owner(alice1) SBT_Registry-->>-Alice: [[SBT_1_Contract, [238]], [SBT_2_Contract, [7991, 7992]]]} ``` Implementation Notes: - There is a risk of conflict. The standard requires that one account can't have more than one SBT of the same (issuer, class) pair. - When both `alice1` and `alice2` have SBT of the same (issuer, class) pair, then the transfer should fail. One of the accounts should burn conflicting tokens to be able to continue the soul transfer. - Soul transfer may require extra confirmation before executing a transfer. For example, if `alice1` wants to do a soul transfer to `alice2`, the contract my require `alice2` approval before continuing the transfer. - Other techniques may be used to enforce that the source account will be deleted. ### Renewal Soulbound tokens can have an _expire date_. It is useful for tokens which are related to real world certificates with expire time, or social mechanisms (e.g. community membership). Such tokens SHOULD have an option to be renewable. Examples include mandatory renewal with a frequency to check that the owner is still alive, or renew membership to a DAO that uses SBTs as membership gating. Registry defines `sbt_renew` method allowing issuers to update the token expire date. The issuer can set a the _expire date_ in the past. This is useful if an issuer wants to invalidate the token without removing it. ### Burning tokens Registry MAY expose a mechanism to allow an account to burn an unwanted token. The exact mechanism is not part of the standard and it will depend on the registry implementation. We only define a standard `Burn` event, which must be emitted each time a token is removed from existence. Some registries may forbid accounts to burn their tokens in order to preserve specific claims. Ultimately, NEAR is a public blockchain, and even if a token is burned, it's trace will be preserved. ### Token Class (multitoken approach) SBT tokens can't be fractionized. Also, by definition, there should be only one SBT per token class per user. Examples: user should not be able to receive few badges of the same class, or few proof of attendance to the same event. However, we identify a need for having to support token classes (aka multitoken interface) in a single contract: - badges: one contract. Each badge will have a class (community lead, OG...), and each token will belong to a specific class; - certificates: one issuer can create certificates of a different class (eg school department can create diplomas for each major and each graduation year). We also see a trend in the NFT community and demand for market places to support multi token contracts. - In Ethereum community many projects are using [ERC-1155 Multi Token Standard](https://eips.ethereum.org/EIPS/eip-1155). NFT projects are using it for fraction ownership: each token id can have many fungible fractions. - NEAR [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) has elaborated similar interface for both bridge compatibility with EVM chains as well as flexibility to define different token types with different behavior in a single contract. [DevGovGigs Board](https://near.social/#/mob.near/widget/MainPage.Post.Page?accountId=devgovgigs.near&blockHeight=87938945) recently also shows growing interest to move NEP-245 adoption forward. - [NEP-454](https://github.com/near/NEPs/pull/454) proposes royalties support for multi token contracts. We propose that the SBT Standard will support the multi-token idea from the get go. This won't increase the complexity of the contract (in a traditional case, where one contract will only issue tokens of the single class, the `class` argument is simply ignored in the state, and in the functions it's required to be of a constant value, eg `1`) but will unify the interface. It's up to the smart contract design how the token classes is managed. A smart contract can expose an admin function (example: `sbt_new_class() -> ClassId`) or hard code the pre-registered classes. Finally, we require that each token ID is unique within the smart contract. This will allow us to query token only by token ID, without knowing it's class. ## Smart contract interface For the Token ID type we propose `u64` rather than `U128`. `u64` capacity is more than 1e19. If we will mint 10'000 SBTs per second, then it will take us 58'494'241 years to fill the capacity. Today, the JS integer limit is `2^53-1 ~ 9e15`. Similarly, when minting 10'000 SBTs per second, it will take us 28'561 years to reach the limit. So, we don't need u128 nor the String type. However, if for some reason, we will need to get u64 support for JS, then we can always add another set of methods which will return String, so making it compatible with NFT standard (which is using `U128`, which is a string). Also, it's worth to note, that in 28'000 years JS (if it will still exists) will be completely different. The number of combinations for a single issuer is much higher in fact: the token standard uses classes. So technically that makes the number of all possible combinations for a single issuer equal `(2^64)^2 ~ 1e38`. For "today" JS it is `(2^53-1)^2 ~ 1e31`. Token IDs MUST be created in a sequence to make sure the ID space is not exhausted locally (eg if a registry would decide to introduce segments, it would potentially get into a trap where one of the segments is filled up very quickly). ```rust // TokenId and ClassId must be positive (0 is not a valid ID) pub type TokenId = u64; pub type ClassId = u64; pub struct Token { pub token: TokenId, pub owner: AccountId, pub metadata: TokenMetadata, } ``` The Soulbound Token follows the NFT [NEP-171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md) interface, with few differences: - token ID is `u64` (as discussed above). - token class is `u64`, it's required when minting and it's part of the token metadata. - `TokenMetadata` doesn't have `title`, `description`, `media`, `media_hash`, `copies`, `extra`, `starts_at` nor `updated_at`. All that attributes except the `updated_at` can be part of the document stored at `reference`. `updated_at` can be tracked easily by indexers. - We don't have traditional transferability. - We propose to use more targeted events, to better reflect the event nature. Moreover events are emitted by the registry, so we need to include issuer contract address in the event. All time related attributes are defined in milliseconds (as per NEP-171). ```rust /// IssuerMetadata defines contract wide attributes, which describes the whole contract. /// Must be provided by the Issuer contract. See the `SBTIssuer` trait. pub struct IssuerMetadata { /// Version with namespace, example: "sbt-1.0.0". Required. pub spec: String, /// Issuer Name, required, ex. "Mosaics" pub name: String, /// Issuer symbol which can be used as a token symbol, eg Ⓝ, ₿, BTC, MOSAIC ... pub symbol: String, /// Icon content (SVG) or a link to an Icon. If it doesn't start with a scheme (eg: https://) /// then `base_uri` should be prepended. pub icon: Option<String>, /// URI prefix which will be prepended to other links which don't start with a scheme /// (eg: ipfs:// or https:// ...). pub base_uri: Option<String>, /// JSON or an URL to a JSON file with more info. If it doesn't start with a scheme /// (eg: https://) then base_uri should be prepended. pub reference: Option<String>, /// Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. pub reference_hash: Option<Base64VecU8>, } /// ClassMetadata defines SBT class wide attributes, which are shared and default to all SBTs of /// the given class. Must be provided by the Issuer contract. See the `SBTIssuer` trait. pub struct ClassMetadata { /// Issuer class name. Required to be not empty. pub name: String, /// If defined, should be used instead of `IssuerMetadata::symbol`. pub symbol: Option<String>, /// An URL to an Icon. To protect fellow developers from unintentionally triggering any /// SSRF vulnerabilities with URL parsers, we don't allow to set an image bytes here. /// If it doesn't start with a scheme (eg: https://) then `IssuerMetadata::base_uri` /// should be prepended. pub icon: Option<String>, /// JSON or an URL to a JSON file with more info. If it doesn't start with a scheme /// (eg: https://) then base_uri should be prepended. pub reference: Option<String>, /// Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. pub reference_hash: Option<Base64VecU8>, } /// TokenMetadata defines attributes for each SBT token. pub struct TokenMetadata { pub class: ClassId, // token class. Required. Must be non zero. pub issued_at: Option<u64>, // When token was issued or minted, Unix time in milliseconds pub expires_at: Option<u64>, // When token expires, Unix time in milliseconds /// JSON or an URL to a JSON file with more info. If it doesn't start with a scheme /// (eg: https://) then base_uri should be prepended. pub reference: Option<String>, /// Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. pub reference_hash: Option<Base64VecU8>, } trait SBTRegistry { /********** * QUERIES **********/ /// Get the information about specific token ID issued by `issuer` SBT contract. fn sbt(&self, issuer: AccountId, token: TokenId) -> Option<Token>; /// Get the information about list of token IDs issued by the `issuer` SBT contract. /// If token ID is not found `None` is set in the specific return index. fn sbts(&self, issuer: AccountId, token: Vec<TokenId>) -> Vec<Option<Token>>; /// Query class ID for each token ID issued by the SBT `issuer`. /// If token ID is not found, `None` is set in the specific return index. fn sbt_classes(&self, issuer: AccountId, tokens: Vec<TokenId>) -> Vec<Option<ClassId>>; /// Returns total amount of tokens issued by `issuer` SBT contract, including expired /// tokens. If a revoke removes a token, it must not be included in the supply. fn sbt_supply(&self, issuer: AccountId) -> u64; /// Returns total amount of tokens of given class minted by `issuer`. See `sbt_supply` for /// information about revoked tokens. fn sbt_supply_by_class(&self, issuer: AccountId, class: ClassId) -> u64; /// Returns total supply of SBTs for a given owner. See `sbt_supply` for information about /// revoked tokens. /// If `class` is specified, returns only owner supply of the given class (either 0 or 1). fn sbt_supply_by_owner( &self, account: AccountId, issuer: AccountId, class: Option<ClassId>, ) -> u64; /// Query sbt tokens issued by a given contract. /// `limit` specifies the upper limit of how many tokens we want to return. /// If `from_token` is not specified, then `from_token` should be assumed /// to be the first valid token id. If `with_expired` is set to `true` then all the tokens are returned /// including expired ones otherwise only non-expired tokens are returned. fn sbt_tokens( &self, issuer: AccountId, from_token: Option<u64>, limit: Option<u32>, with_expired: bool, ) -> Vec<Token>; /// Query SBT tokens by owner. /// `limit` specifies the upper limit of how many tokens we want to return. /// If `from_class` is not specified, then `from_class` should be assumed to be the first /// valid class id. If `with_expired` is set to `true` then all the tokens are returned /// including expired ones otherwise only non-expired tokens are returned. /// Returns list of pairs: `(Contract address, list of token IDs)`. fn sbt_tokens_by_owner( &self, account: AccountId, issuer: Option<AccountId>, from_class: Option<u64>, limit: Option<u32>, with_expired: bool, ) -> Vec<(AccountId, Vec<OwnedToken>)>; /// checks if an `account` was banned by the registry. fn is_banned(&self, account: AccountId) -> bool; /************* * Transactions *************/ /// Creates a new, unique token and assigns it to the `receiver`. /// `token_spec` is a vector of pairs: owner AccountId and TokenMetadata. /// Each TokenMetadata must have non zero `class`. /// Must be called by an SBT contract. /// Must emit `Mint` event. /// Must provide enough NEAR to cover registry storage cost. // #[payable] fn sbt_mint(&mut self, token_spec: Vec<(AccountId, Vec<TokenMetadata>)>) -> Vec<TokenId>; /// sbt_recover reassigns all tokens issued by the caller, from the old owner to a new owner. /// Must be called by a valid SBT issuer. /// Must emit `Recover` event once all the tokens have been recovered. /// Requires attaching enough tokens to cover the storage growth. /// Returns the amount of tokens recovered and a boolean: `true` if the whole /// process has finished, `false` when the process has not finished and should be /// continued by a subsequent call. User must keep calling the `sbt_recover` until `true` /// is returned. // #[payable] fn sbt_recover(&mut self, from: AccountId, to: AccountId) -> (u32, bool); /// sbt_renew will update the expire time of provided tokens. /// `expires_at` is a unix timestamp (in miliseconds). /// Must be called by an SBT contract. /// Must emit `Renew` event. fn sbt_renew(&mut self, tokens: Vec<TokenId>, expires_at: u64); /// Revokes SBT by burning the token or updating its expire time. /// Must be called by an SBT contract. /// Must emit `Revoke` event. /// Must also emit `Burn` event if the SBT tokens are burned (removed). fn sbt_revoke(&mut self, tokens: Vec<TokenId>, burn: bool); /// Similar to `sbt_revoke`. Allows SBT issuer to revoke all tokens by holder either by /// burning or updating their expire time. When an owner has many tokens from the issuer, /// the issuer may need to call this function multiple times, until all tokens are revoked. /// Retuns true if all the tokens were revoked, false otherwise. /// If false is returned issuer must call the method until true is returned /// Must be called by an SBT contract. /// Must emit `Revoke` event. /// Must also emit `Burn` event if the SBT tokens are burned (removed). fn sbt_revoke_by_owner(&mut self, owner: AccountId, burn: bool) -> bool; /// Allows issuer to update token metadata reference and reference_hash. /// * `updates` is a list of triples: (token ID, reference, reference base64-encoded sha256 hash). /// Must emit `token_reference` event. /// Panics if any of the token IDs don't exist. fn sbt_update_token_references( &mut self, updates: Vec<(TokenId, Option<String>, Option<Base64VecU8>)>, ); } ``` Example **Soul Transfer** interface: ```rust /// Transfers atomically all SBT tokens from one account to another account. /// The caller must be an SBT holder and the `recipient` must not be a banned account. /// Returns the amount of tokens transferred and a boolean: `true` if the whole /// process has finished, `false` when the process has not finished and should be /// continued by a subsequent call. /// Emits `Ban` event for the caller at the beginning of the process. /// Emits `SoulTransfer` event only once all the tokens from the caller were transferred /// and at least one token was trasnfered (caller had at least 1 sbt). /// + User must keep calling the `sbt_soul_transfer` until `true` is returned. /// + If caller does not have any tokens, nothing will be transfered, the caller /// will be banned and `Ban` event will be emitted. #[payable] fn sbt_soul_transfer( &mut self, recipient: AccountId, ) -> (u32, bool); ``` ### SBT Issuer interface SBTIssuer is the minimum required interface to be implemented by issuer. Other methods, such as a mint function, which requests the registry to proceed with token minting, is specific to an Issuer implementation (similarly, mint is not part of the FT standard). The issuer must provide metadata object of the Issuer. Optionally, Issuer can also provide metadata object for each token class. Issuer level (contract) metadata, must provide information common to all tokens and all classes defined by the issuer. Class level metadata, must provide information common to all tokens of a given class. Information should be deduplicated and denormalized whenever possible. Example: The issuer can set a default icon for all tokens (SBT) using `IssuerMetadata::icon` and additionally it can customize an icon of a particular token via `TokenMetadata::icon`. ```rust pub trait SBTIssuer { /// Returns contract metadata. fn sbt_metadata(&self) -> IssuerMetadata; /// Returns SBT class metadata, or `None` if the class is not found. fn sbt_class_metadata(&self, class: ClassId) -> Option<ClassMetadata>; } ``` SBT issuer smart contracts may implement NFT query interface to make it compatible with NFT tools. In that case, the contract should proxy the calls to the related registry. Note, we use U64 type rather than U128. However, SBT issuer must not emit NFT related events. ```rust trait SBTNFT { fn nft_total_supply(&self) -> U64; // here we index by token id instead of by class id (as done in `sbt_tokens_by_owner`) fn nft_tokens_for_owner(&self, account_id: AccountId, from_index: Option<U64>, limit: Option<u64>) -> Vec<Token>; fn nft_supply_for_owner(&self, account_id: AccountId) -> U64; } ``` ### Events Event design principles: - Events don't need to repeat all function arguments - these are easy to retrieve by indexer (events are consumed by indexers anyway). - Events must include fields necessary to identify subject matters related to use case. - When possible, events should contain aggregated data, with respect to the standard function related to the event. ```typescript // only valid integer numbers (without rounding errors). type u64 = number; type Nep393Event { standard: "nep393"; version: "1.0.0"; event: "mint" | "recover" | "renew" | "revoke" | "burn" | "ban" | "soul_transfer" | "token_reference" ; data: Mint | Recover | Renew | Revoke | Burn | Ban[] | SoulTransfer | TokenReference; } /// An event emitted by the Registry when new SBT is created. type Mint { issuer: AccountId; // SBT Contract minting the tokens tokens: (AccountId, u64[])[]; // list of pairs (token owner, TokenId[]) } /// An event emitted when a recovery process succeeded to reassign SBTs, usually due to account /// access loss. This action is usually requested by the owner, but executed by an issuer, /// and doesn't trigger Soul Transfer. Registry reassigns all tokens assigned to `old_owner` /// that were ONLY issued by the `ctr` SBT Contract (hence we don't need to enumerate the /// token IDs). /// Must be emitted by an SBT registry. type Recover { issuer: AccountId // SBT Contract recovering the tokens old_owner: AccountId; // current holder of the SBT new_owner: AccountId; // destination account. } /// An event emitted when existing tokens are renewed. /// Must be emitted by an SBT registry. type Renew { issuer: AccountId; // SBT Contract renewing the tokens tokens: u64[]; // list of token ids. } /// An event emitted when existing tokens are revoked. /// Revoked tokens will continue to be listed by the registry but they should not be listed in /// a wallet. See also `Burn` event. /// Must be emitted by an SBT registry. type Revoke { issuer: AccountId; // SBT Contract revoking the tokens tokens: u64[]; // list of token ids. } /// An event emitted when existing tokens are burned and removed from the registry. /// Must be emitted by an SBT registry. type Burn { issuer: AccountId; // SBT Contract burning the tokens tokens: u64[]; // list of token ids. } /// An event emitted when an account is banned within the emitting registry. /// Registry must add the `account` to a list of accounts that are not allowed to get any SBT /// in the future. /// Must be emitted by an SBT registry. type Ban = AccountId; /// An event emitted when soul transfer is happening: all SBTs owned by `from` are transferred /// to `to`, and the `from` account is banned (can't receive any new SBT). /// Must be emitted by an SBT registry. /// Registry MUST also emit `Ban` whenever the soul transfer happens. type SoulTransfer { from: AccountId; to: AccountId; } /// An event emitted when an issuer updates token metadata reference of existing SBTs. /// Must be emitted by an SBT registry. type TokenReference { issuer: AccountId; // Issuer account tokens: u64[]; // list of token ids. } /// An event emitted when existing token metadata references are updated. type TokenReference = u64[]; // list of token ids. ``` Whenever a recovery is made in a way that an existing SBT is burned, the `Burn` event MUST be emitted. If `Revoke` burns token then `Burn` event MUST be emitted instead of `Revoke`. ### Example SBT Contract functions Although the transaction functions below are not part of the SBT smart contract standard (depending on a use case, they may have different parameters), we present here an example interface for SBT issuance and we also provide a reference implementation. These functions must relay calls to an SBT registry, which will emit appropriate events. We recommend that all functions related to an event will take an optional `memo: Option<String>` argument for accounting purposes. ```rust trait SBT { /// Must provide enough NEAR to cover registry storage cost. // #[payable] fn sbt_mint( &mut self, account: AccountId, metadata: TokenMetadata, memo: Option<String>, ) -> TokenId; /// Creates a new, unique token and assigns it to the `receiver`. /// `token_spec` is a vector of pairs: owner AccountId and TokenMetadata. /// Must provide enough NEAR to cover registry storage cost. // #[payable] fn sbt_mint_multi( &mut self, token_spec: Vec<(AccountId, TokenMetadata)>, memo: Option<String>, ) -> Vec<TokenId>; // #[payable] fn sbt_recover(&mut self, from: AccountId, to: AccountId, memo: Option<String>); fn sbt_renew(&mut self, tokens: Vec<TokenId>, expires_at: u64, memo: Option<String>); fn sbt_revoke(token: Vec<u64>, memo: Option<String>) -> bool; } ``` ## Reference Implementation - Common [type definitions](https://github.com/near-ndc/i-am-human/tree/master/contracts/sbt) (events, traits). - [I Am Human](https://github.com/near-ndc/i-am-human) registry and issuers. ## Consequences Being fully compatible with NFT standard is a desirable. However, given the requirements related to _soul transfer_ we didn't find an applaudable solution. Also we decided to use u64 as a Token ID, diverging further from the NFT NEP-171 standard. Given that our requirements are much striker, we had to reconsider the level of compatibility with NEP-171 NFT. There are many examples where NFT standards are improperly implemented. Adding another standard with different functionality but equal naming will cause lots of problems and misclassifications between NFT and SBT. ### Positive - Template and set of guidelines for creating SBT tokens. - Ability to create SBT aggregators. - An SBT standard with recoverability mechanism provides a unified model for multiple primitives such as non KYC identities, badges, certificates etc... - SBT can be further used for "lego" protocols, like: Proof of Humanity (discussed for NDC Governance), undercollateralized lending, role based authentication systems, innovative economic and social applications... - Standard recoverability mechanism. - SBT are considered as a basic primitive for Decentralized Societies. - new way to implement Sybil attack resistance. ### Neutral - The API partially follows the NEP-171 (NFT) standard. The proposed design is to have native SBT API and make it possible for issuer contracts to support NFT based queries if needed (such contract will have a limitation of only issuing SBTs with one `ClassId` only). ### Negative - New set of events to be handled by the indexer and wallets. - Complexity of integration with a registry: all SBT related transactions must go through Registry. ### Privacy Notes > Blockchain-based systems are public by default. Any relationship that is recorded on-chain is immediately visible not just to the participants, but also to anyone in the entire world. Some privacy can be retained by having multiple pseudonyms: a family Soul, a medical Soul, a professional Soul, a political Soul each carrying different SBTs. But done naively, it could be very easy to correlate these Souls to each other. > The consequences of this lack of privacy are serious. Indeed, without explicit measures taken to protect privacy, the “naive” vision of simply putting all SBTs on-chain may well make too much information public for many applications. -- Decentralized Society There are multiple ways how an identity can be doxxed using chain data. SBT, indeed provides more data about account. The standard allows for few anonymization methods: - not providing any data in the token metadata (reference...) or encrypt the reference. - anonymize issuers (standard allows to have many issues for the same entity) and mix it with different class ids. These are just a numbers. Perfect privacy can only be done with solid ZKP, not off-chain walls. Implementations must not store any personal information on chain. ## Changelog ### v1.0.0 The Contract Standards Working Group members approved this NEP on June 30, 2023 ([meeting recording](https://youtu.be/S1An5CDG154)). #### Benefits - SBTs as any other kind of a token are essential primitive to represent real world use cases. This standards provides a model and a guideline for developers to build SBT based solutions. - Token standards are key for composability. - Wallet and tools needs a common interface to operate tokens. #### Concerns | # | Concern | Resolution | Status | | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | 1 | [Robert] Should we Emit NEP-171 Mint and NEP-171 Burn by the SBT contract (in addition to SBT native events emitted by the registry)? If the events will be emitted by registry, then we need new events to include the contract address. | Don't emit NFT events. SBT is not NFT. Support: @alexastrum | resolved | | 2 | [Robert] remove `memo` in events. The `memo` is already part of the transaction, and should not be needed to identify transactions. Processes looking for events, can easily track transaction through event and recover `memo` if needed. | Removed, consequently also removed from registry transactions . Support: @alexastrum | resolved | | 3 | [Token Spam](https://github.com/near/NEPs/pull/393/#discussion_r1163938750) | We have a `Burn` event. Added example `sbt_burn` function, but keeping it not as a part of required interface. Event should be enough. | resolved | | 4 | [Multiple registries](https://github.com/near/NEPs/pull/393/#discussion_r1163951624). Registry source of truth [comment](https://github.com/near/NEPs/pull/393/#issuecomment-1531766643) | This is a part of the design: permissionless approach. [Justification for registry](https://github.com/near/NEPs/pull/393/#issuecomment-1540621077) | resolved | | 5 | [Robert] Approve the proposed multi-token | Support: @alexastrum | resolved | | 6 | [Robert] Use of milliseconds as a time unit. | Use milliseconds. | resolved | | 7 | Should a `burn` function be part of a standard or a recommendation? | We already have the Burn event. A call method should not be part of the standard interface (similarly to FT and NFT). | resolved | | 8 | [Robert] Don't include `sbt_soul_transfer` in the standard interface, [comment](https://github.com/near/NEPs/pull/393#issuecomment-1506969996). | Moved outside of the required interface. | resolved | | 9 | [Privacy](https://github.com/near/NEPs/pull/393/#issuecomment-1504309947) | Concerns have been addressed: [comment-1](https://github.com/near/NEPs/pull/393/#issuecomment-1504485420) and [comment2](https://github.com/near/NEPs/pull/393/#issuecomment-1505958549) | resolved | | 10 | @frol [suggested](https://github.com/near/NEPs/pull/393/#discussion_r1247879778) to use a struct in `sbt_recover` and `sbt_soul_transfer`. | Motivation to use pair `(number, bool)` rather than follow a common Iterator Pattern. Rust uses `Option` type for that, that works perfectly for languages with native Option type, but creates a "null" problem for anything else. Other common way to implement Iterator is the presented pair, which doesn't require extra type definition and reduces code size. | new | ### v1.1.0 In v1.0.0 we defined Issuer (an entity authorized to mint SBTs in the registry) and SBT Class. We also defined Issuer Metadata and Token Metadata, but we didn't provide interface for class metadata. This was implemented in the reference implementation (in one of the subsequent revisions), but was not backported to the NEP. This update: - Fixes the name of the issuer interface from `SBTContract` to `SBTIssuer`. The original name is wrong and we oversight it in reviews. We talk everywhere about the issuer entity and issuer contract (even the header is SBT Issuer interface). - Renames `ContractMetadata` to `IssuerMetadata`. - Adds `ClassMetadata` struct and `sbt_class_metadata` function to the `SBTIssuer` interface. Reference implementation: [ContractMetadata, ClassMetadata, TokenMetadata](https://github.com/near-ndc/i-am-human/blob/registry/v1.8.0/contracts/sbt/src/metadata.rs#L18) and [SBTIssuer interface](https://github.com/near-ndc/i-am-human/blob/registry/v1.8.0/contracts/sbt/src/lib.rs#L49). #### Benefits - Improves the documentation and meaning of the issuer entity. - Adds missing `ClassMetadata`. - Improves issuer, class and token metadata documentation. ## Copyright [Creative Commons Attribution 4.0 International Public License (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/)
Doomslug vs PBFT, Tendermint, and Hotstuff DEVELOPERS February 5, 2020 In this blog post, we will see how Doomslug, our new block production technique, compares to PBFT, Tendermint, and Hotstuff. We will also dig relatively deep into how PBFT, Tendermint and Hotstuff work, cover view changes, pipelining, responsiveness and some other details. On the last day of the previous decade, we published a paper called Doomslug in which we proposed a new way of producing blocks that allows us to achieve some sense of practical finality after just one round of communication, with a finality gadget providing full BFT finality after the second round. What we refer to as practical finality, or doomslug finality is that a block produced by Doomslug is irreversible unless at least one participant is slashed. Doomslug also has a nice property that it continues producing and finalizing blocks for as long as just over half of all the participants are online and honest, not ⅔ as required by BFT consensus algorithms (though the finality gadget of course stalls if less than ⅔ of participants are online). Now that the Doomslug implementation in NEAR is completed, it is a good time to discuss how it works, and how it compares to other approaches. Specifically, we will compare it to Tendermint and HotStuff. If you have questions while you read, feedback is encouraged. Ask your questions and join the discussion here. How Doomslug works In short, Doomslug works by having a set of participants take turns to produce and broadcast blocks. Once a block at height h is received by other participants, they send endorsements on such a block to the participant assigned to the next height h+1. If after some predetermined time the participant assigned to h+1 hasn’t produced a block, the participants who sent an endorsement to her send another message to the participant assigned to h+2 indicating that they suggest skipping the block at h+1. Once a participant has endorsements or skip-messages from more than half of other participants, they can produce their block. With careful handling of message delays and exact slashing conditions, this rather simple technique can provide the property that we discussed above: if a block produced by Doomslug contains endorsements on the previous block from more than half of the block producers, the previous block is irreversible unless at least one of the block producers is slashed. Moreover, it is guaranteed that even if the network is slow, and messages are delayed, a block that contains endorsements from more than half the block producers will be created at some point, so the algorithm never stalls. As mentioned above, there’s a finality gadget that operates together with Doomslug. Under normal circumstances once a block at height `h+1` is produced, and the block at height `h` has doomslug finality, the block at height `h-1` will have a full BFT finality. In other words, at least ⅓ of the total stake would need to be slashed to revert it. We will see how it compares to other consensus algorithms two sections below. Both Doomslug and the finality gadget guarantees around blocks irreversibility do not make any assumptions about how slow or reliable the network is. In other words, both Doomslug and the finality gadget have safety under asynchronous network assumption. However, the guarantee that they cannot stall (a property called “liveness”) assumes a partially synchronous network. It is a rather common assumption, and all the consensus algorithms discussed in this post make this assumption in their liveness proofs. Having both guaranteed safety and liveness under asynchronous network is impossible, a limitation known as FLP impossibility. A Short primer on PBFT, Tendermint, and Hotstuff Before we dig into the comparison of Doomslug with Tendermint and Hotstuff, let’s do a quick review of how they work. In a good case PBFT, Tendermint and Hotstuff all work in a very similar manner: The consensus protocol happens over multiple views, optimistically in just one view. In each view there’s a particular leader who is assigned to carry out the consensus. The leader proposes a particular outcome. In the first view the choice of outcome is arbitrary. The leader sends the proposed outcome to all the remaining participants, and they send back their pre-vote on the outcome. The participants wait until there are pre-votes on the outcome from ⅔ of them, and then each participant sends a pre-commit on the outcome. Once there are pre-commit messages from ⅔ of participants, the consensus is reached. The way the participants exchange messages differs between protocols. In Tendermint the participants use the gossip protocol, and each participant accumulates the pre-vote and pre-commit messages locally, while in Hotstuff the leader accumulates messages and sends them back. The entire process can be made with just a linear amount of network overhead. Indeed, if the leader accumulates the pre-votes and pre-commits, then the initial broadcast of the proposed outcome, as well as other participants communicating back their pre-votes and pre-commits is already linear. The only quadratic overhead naively is sending accumulated pre-votes and accumulated pre-commits, but this can be done with linear overhead as well, if the accumulated messages are compressed using e.g. BLS signatures. If for any reason the leader fails to carry out the consensus, it moves to the next view, in which the next leader will attempt again. The view change is where Hotstuff and Tendermint differ significantly from PBFT. In PBFT each participant has a timer that measures how much time has passed since the beginning of the view, and once the timer crosses a certain threshold, they send a view-change message to the next leader. The next leader needs to accumulate the view-change messages from ⅔ of the participants and send back a new-view message to them. This entire procedure requires at least cubic network overhead, and is also rather hard to implement correctly. Tendermint and Hotstuff handle the view changes differently. Instead, there are timeouts in each phase (pre-vote and pre-commit), and whenever such a timeout is triggered, the participant sends a corresponding pre-vote or a pre-commit on nil, and moves to the next phase or view locally. Thus, the view-change is not an orchestrated process, and is rather implicit. Importantly, the mechanism for the view-change and for committing the block is essentially the same, which significantly simplifies the algorithm. There are two major differences between Tendermint and Hotstuff. One is that Hotstuff is pipelined, meaning that a pre-commit of one view is a pre-vote for the next one, requiring almost twice as few phases as a non-pipelined version. There are proposals to make Tendermint pipelined, but the way it is implemented in Cosmos and presented in the paper are not pipelined. Second, and more frequently discussed, the difference is the fact that Hotstuff has so-called responsiveness, in other words, that an honest leader will always have the consensus reached in time bounded by the network delays, not timeouts. In Tendermint it is not the case, because in the pre-commit phase if a participant observes pre-commits on nil from ⅔ of the participants, they cannot move to the next view until the timeout expires, otherwise, an adversary with careful control of the network can make the algorithm switch between views indefinitely. The responsiveness, while a neat feature, is somewhat misleading. Specifically, it only guarantees that the time it will take for the consensus to be reached will be bound by network delays if the leader is online and honest. If the leader is offline, the system will still wait the full timeout to move to the next view. In practice in Cosmos, which has been running a large instance of Tendermint for a long time presently, all the view-changes that ever occurred were due to the offline leader, and never due to the pre-commit on nil, thus the responsiveness of Hotstuff would have never mattered in Cosmos up to date. I’m also not diving deep here into the fact that Hotstuff requires an extra round of communication to achieve responsiveness. In the first view, such an extra round can be omitted, and in the second view it is compensated with pipelining, thus the extra round rarely becomes an issue. Doomslug vs Tendermint and Hotstuff The optimistic case Now let’s compare how Doomslug with a finality gadget compares to Tendermint and Hotstuff under various conditions. First, let’s consider the case in which no view-changes occur, and all the messages reach the leaders in time. In the figure above, grey blocks are proposed blocks, blue blocks are blocks that have BFT finality, and yellow blocks are blocks that have doomslug finality. Under normal circumstances Hotstuff and Tendermint behave exactly the same way: after a block is proposed, within two rounds of communication the block is final, and after two more rounds the block that immediately follows it is also final. Note that Hotstuff doesn’t pipeline across blocks, only across views, and thus producing two blocks still requires four rounds, not three. Doomslug doesn’t improve on latency to full BFT finality, and thus since the moment the first block is produced, it still takes two rounds of communication until it has the full BFT finality. As discussed above, however, after the first round of communication the block already has a weaker than BFT sense of finality that we refer to as “doomslug finality”, in other words, it is irreversible unless at least one block producer is slashed. Also note that by nature of finality gadgets, their throughput is the same as the underlying block production, and thus after three rounds of communication there are already two blocks that have full BFT finality, and after four rounds there are three such blocks. In other words, while it takes the same time for Doomslug with the finality gadget to reach full BFT finality on a single block, it finalizes twice as many blocks as Tendermint or Hotstuff per long period of time. While it doesn’t improve on latency, it improves the throughput by a factor of two. The less optimistic case Now let’s see what happens in a less optimistic case, in which either some participants are offline, or a view fails for another reason. In the figure above, we show the case in which two consecutive views have failed. In the case of Tendermint, each failed view adds two rounds of communication, and thus it will take six rounds of communication to finalize a block. In the case of Hotstuff, the pipelining kicks in, and the block will be finalized after just four rounds of communication. Due to finality gadgets having the same throughput as the underlying block production, Doomslug with the finality gadget enjoys the same pipelining, and will also finalize the block after four rounds of communication. It is the case, however, that after the first three rounds the block will already have “doomslug finality”, and after the fourth round together with the first block reaching BFT finality, a block built on top of it will already have doomslug finality as well. Other considerations Above we covered one dimension on which block production and consensus algorithms can be compared: the number of rounds to finality under different conditions. There are other considerations. For example, while all the consensus algorithms discussed in this post have liveness (in other words are guaranteed not to stall under certain practical conditions), their exact behavior in presence of network delays and interruptions differs. The amount of time it takes to recover after a period of long loss of connectivity can vary noticeably. Our simulated tests show that Doomslug recovers quickly after long periods of network inactivity (the simulation code can be found here), but generally, very little research was done on comparing the consensus protocols from this perspective. Another dimension is implementation complexity. With an assumption that ⅓ of all the block producers, weighted by stake, can never become corrupted, a protocol built on Tendermint or Hotstuff doesn’t need to implement any logic to handle forks. Doomslug finalizes blocks slower than it produces them, and therefore forks are possible until the blocks are actually final. Correspondingly, the protocol needs to be able to handle such forks, which noticeably increases the complexity of the implementation. In case of NEAR, we switched to Doomslug from a flavor of longest chain protocol, and thus already had all the logic of handling forks and an intensive test coverage for it implemented, but for a new effort to build a protocol not having to deal with forks can result in a considerable reduction of implementation cost. Outro Check out our Whiteboard Series with NEAR, in which we talk to the founders and core developers of other protocols, such as Ethereum Serenity, Cosmos, Polkadot and many others, and dive deep into the details of their technology. All the video episodes are conveniently assembled into a playlist here. NEAR Protocol is an infrastructure for open web and a sharded blockchain protocol. You can learn more about our technology in our sharding design paper, through deep-dive videos, or by exploring our Rust reference client implementation. Follow @NEARprotocol on Twitter to get notified about new content we post, and get the latest updates on the development of the protocol. If you want to get involved, please join the conversation here! Thanks to Zaki Manian and Ethan Buchman from Tendermint for reviewing an early draft of this post and providing feedback!
--- id: dev-environment title: Choose your Dev Environment --- The environments in which you can develop `Components` are divided into two categories: - [Web Tools](#web-tools): Online tools that allow you to quickly start building and sharing components. - [Local Tools](#local-tools): Tools that allow you to develop and test components locally. :::tip Handling collaborations If you plan to collaborate with multiple people, we recommend you to check [this repository template](https://github.com/near-examples/bos-components) which automatically deploys components each time a PR is merged. ::: --- ## Web Tools The quickest way to start building NEAR Components is by using one of the online tools. They are great for taking your first steps, while they let you find other developers and components in the NEAR ecosystem. #### [NEAR Sandbox](https://near.org/sandbox) The [near website](https://near.org/) contains its own [sandbox editor](https://near.org/sandbox). The sandbox allows you to code, preview and deploy your components directly from your browser. #### [Jutsu.ai](https://jutsu.ai) [Jutsu.ai](https://jutsu.ai) is a web IDE made for NEAR developers. It contains examples and tutorials to help onboarding you. --- ## Local Tools If you want to collaborate with a team or work on a larger project, you will likely want more **version control**, automated testing and deployment, and other workflows. For this, the NEAR ecosystem offers a set of tools to easily develop and test your components entirely locally. #### [NEAR VSCode Extension](https://marketplace.visualstudio.com/items?itemName=near-protocol.near-discovery-ide) The [NEAR VSCode Extension](https://marketplace.visualstudio.com/items?itemName=near-protocol.near-discovery-ide) integrates with the VSCode IDE to help you develop, preview and deploy components all within VSCode. #### [BOS Loader](../../3.tutorials/near-components/bos-loader.md) A CLI tool to preview local components in NEAR BOS. A perfect companion to the [BOS CLI](https://github.com/FroVolod/bos-cli-rs). #### [BOS CLI](https://github.com/FroVolod/bos-cli-rs) A command line utility that simplifies local component development for NEAR BOS. #### [BOS Workspace](https://github.com/nearbuilders/bos-workspace) A comprehensive toolset for simplifying the local development of NEAR components and applications, featuring hot reload, TypeScript support, multi-app management, and a local gateway. #### [Além](https://github.com/wpdas/alem) A web3 JavaScript/TypeScript library to create web3 applications for Near BOS. It's developer-friendly and uses React patterns, making it easy to organize files and write code. Access the [Além Docs](https://alem.dev/) to get to know more.
Arpit Sharma Joins NEAR as Managing Director for India, Asia, and Middle East Expansion NEAR FOUNDATION March 1, 2023 The NEAR ecosystem is getting a huge boost in the eastern hemisphere today. NEAR Foundation is appointing Arpit Sharma as managing director for India, South East Asia, and the Middle East to help expand NEAR’s presence in those specific regions and beyond. Sharma brings regional expertise as well as leadership experience from the Polygon ecosystem. “Arpit brings a wealth of experience and passion about Web3 to the table,” said Marieke Flament, CEO of the NEAR Foundation. “With his impressive track record and deep understanding of this space, I am confident he will play a key role in shaping the future of NEAR.” Sharma’s appointment marks a major milestone in expanding NEAR’s presence in some of the fastest-growing Web3 hotspots in the world. Having previously worked as the VP of Global Enterprises at Polygon, Sharma led enterprise adoption and business development in the Asia Pacific and Middle East regions. “I am thrilled to be in this new role as I see the immense opportunity in the region,” Sharma commented. “There is enormous potential to tap into strong grassroots communities as we continue to use the exciting opportunities presented by Web3 to connect, collaborate and change the world.” Sharma and NEAR excited by regional opportunities Favorable demographics and technical resources combined with a strong and diverse consumer base make India, South East Asia, and the Middle East primed for massive Web3 growth in the upcoming decades. As a VP at Polygon, Sharma was a key contributor to enterprise strategy and led the APAC business across enterprise, digital native businesses, and the public sector. Sharma brings a wealth of regional and cross-industry experience along with extreme enthusiasm for the NEAR protocol, ecosystem, and technology. Sharma will champion Near’s developer-first focus and ease of use to drive onboarding in the APAC and Middle East regions. “I’m incredibly impressed by the infinite scalability of NEAR’s platform,” Sharma said. “I believe it’s the best protocol in the ecosystem. It not only delivers on its technical promises but gains the support of the developer community. The potential presented in emerging markets is a win-win for everyone.” As the new regional MD, Sharma will target business opportunities in five of the top ten countries on the 2022 Global Crypto Adoption Index. This includes Vietnam, the Philippines, India, Pakistan, and Thailand. The index has been dominated by emerging markets in recent years, and NEAR’s appointment of Sharma will help the ecosystem benefit from this trend. India in particular boasts the world’s third-largest startup ecosystem and one of the top Web3 talent pools globally. This includes more than 450 active Web3 startups and four unicorns. Sharma will augment NEAR’s current and rapidly growing presence in APAC, with strong regional hubs in South Korea and Vietnam. Sharma’s Web3 expertise extends to a wide array of industries, solutions, and use cases. This includes the metaverse, NFTs, supply chain tracking, and stablecoins. He’s led projects in these areas and his versatility will be well-positioned to create more opportunities and a richer ecosystem in the Middle East, South East Asia, and India.
- Proposal Code Name: access_keys - Start Date: 2019-07-08 - NEP PR: [nearprotocol/neps#0000](https://github.com/near/NEPs/blob/master/nep-0000-template.md) - Issue(s): [nearprotocol/nearcore#687](https://github.com/nearprotocol/nearcore/issues/687) # Summary [summary]: #summary Access keys provide limited access to an account. Each access key belongs to some account and identified by a unique (within the account) public key. One account may have large number of access keys. Access keys will replace original account-level public keys. Access keys allow to act on behalf of the account by restricting allowed transactions with the access key permissions. # Motivation [motivation]: #motivation Access keys give an ability to use dApps in a secure way without asking the user to sign every transaction in the wallet. By issuing the access key once for the application, the application can now act on behalf of the user in a restricted environment. This enables seamless experience for the user. Access keys also enable a few other use-cases that are discussed in details below. # Guide-level explanation [guide-level-explanation]: #guide-level-explanation Here are proposed changes for the AccessKey and Account structs. ```rust /// `account_id,public_key` is a key in the state struct AccessKey { /// The nonce for this access key. /// It makes sense for nonce to not start from 0, in case the access key is recreated /// with the same public key, to avoid replaying of old transactions. pub nonce: Nonce, // u64 /// Defines permissions for the AccessKey pub permission: AccessKeyPermission, } /// Defines permissions for AccessKey pub enum AccessKeyPermission { /// Restricts AccessKey to only be used for function calls. FunctionCall(FunctionCallPermission), /// Gives full access to the account. /// NOTE: It's used to replace account-level public keys. FullAccess, } pub struct FunctionCallPermission { /// `Some` amount that can be spent for transaction fees by this access key from the account balance. /// When used, both account balance and the allowance is decreased. /// To change or increase the allowance, the access key can be replaced using SwapKey. /// NOTE: If you reuse the public key, make sure to keep the nonce from the old AccessKey. /// `None` means unlimited allowance. pub allowance: Option<Balance>, // u128 /// The AccountID of the receiver of the transaction. The access key will restrict transactions to /// only this receiver. pub receiver_id: AccountId, // String /// If `Some`, the access key would be restricted to calling only the given method name. /// `None` means it's restricted to calling the receiver_id contract, but any method name. pub method_name: Option<String>, } /// NOTE: This change removes account-level nonce and public keys. /// Key is `account_id` struct Account { pub balance: Balance(u128), pub code_hash: Hash, /// Storage usage accounts for all access keys pub storage_usage: StorageUsage(u64), /// Last block index at which the storage was paid for. pub storage_paid_at: BlockIndex(u64), } ``` ### Examples #### AccessKey as account-level public key If an AccessKey has the full access to the account and the allowance set to be the max value for u128, then it essentially acts as an account-level public key. Which means we can remove account-level public keys from the account struct and rely only on access keys. An access key example from user `vasya.near` with full access: ```rust /// vasya.near,a123bca2 AccessKey { nonce: 0, permission: AccessKeyPermission::FullAccess, } ``` #### AccessKey for a dApp by a user This is a simple example where a user wants to use some dApp. The user has to authorize this dApp within their wallet, so the dApp knows who the user is, and also can issue simple function call transactions on behalf of this user. To create such AccessKey a dApp generates a new key pair and passes the new public key to the user's wallet in a URL. Then the wallet asks the user to create a new AccessKey with that points to the dApp. User has to explicitly confirm this in the wallet for AccessKey to be created. The new access key is restricted to be only used for the app’s contract_id, but is not restricted for any method name. The user also selects the allowance to some reasonable amount, enough for the application to issue regular transactions. The application might also hint the user about this desired allowance in some way. Now the app can issue function call transactions on behalf of the user’s account towards the app’s contract without requiring the user to sign each transaction. An access key example for chess app from user `vasya.near`: ```rust /// vasya.near,c5d312f3 AccessKey { nonce: 0, permission: AccessKeyPermission::FunctionCall(FunctionCallPermission { // Since the access key is stored on the Chess app front-end, the user has // limited the spending amount to some reasonable, but large enough number. // NOTE: It's needs to be multiplied to decimals, e.g. 10^-18 allowance: Some(1_000_000_000), // This access key restricts access to `chess.app` contract. receiver_id: "chess.app", // Any method name on the `chess.app` contract can be called. method_name: None, }), } ``` #### AccessKey issued by a dApp This is an example where the dApp wants to pay for the user, or it doesn't want to go through the user's sign-in flow. For whatever reason the dApp decided to issue an access key directly for their account. For this to work there should be one account with funds (that dApp controls on the backend) which creates access keys for the users. The difference from the example above is there is only one account (the same for all users) that creates multiple access keys (one per user) towards one other contract (app's contract). To differentiate users the contract has to use the public key of the access key instead of sender's account ID. If the access key wants to support user's identity from the account ID. The contract can provide a public method that links user's account ID with a given public key. Once this is done, a user can request a new access key with the linked public key (sponsored by the app), but it is linked to the user's account ID. There are some caveats with this approach: - The dApp is required to have a backend and to have some sybil resistance for users. It's needed to prevent abuse by bots. - Writing the contract is slightly more complicated, since the contract now needs to handle mapping of the public keys to the account IDs. An access key example for chess app paid by the chess app from `chess.funds` account: ```rust /// chess.funds,2bc2b3b AccessKey { nonce: 0, permission: AccessKeyPermission::FunctionCall(FunctionCallPermission { // Since the access key is given to the user, the developer wants to limit the // the spending amount to some conservative number, since a user might try to drain it. allowance: Some(5_000_000), // This access key restricts access to `chess.app` contract. receiver_id: "chess.app", // Any method name on the `chess.app` contract can be called (but some methods might just ignore this key). method_name: None, }), } ``` #### AccessKey through a proxy This examples demonstrates how to have more granular control on top of built-in access key restrictions. Let's say a user wants to: - limit the number of calls the access key can make per minute - support multiple contracts with the same access key - select which methods name can be called and which can't - transfer funds from the account up to a certain limit - stake from the account, but prevent withdrawing funds To make it work, we need to have a custom logic at every call. We can achieve this by running a portion of a smart contract code before any action. A user can deploy a code on their account and restrict access key to their account and to a method name, e.g. `proxy`. Now this access key will only be able to issue transactions on behalf of the user that goes to the user's contract code and calls method `proxy`. The `proxy` method can find out which access key is used by comparing public keys and verify the request before executing it. E.g. the access key should only be able to call `chess.app` at most 3 times per 20 block and can transfer at most 1M tokens to the `chess.app`. The `proxy` function internally can validate that this access key is used, fetch its config, validate the passed arguments and proxy the transaction. A `proxy` method might take the following arguments for a function call: ```json { "action": "call", "contractId": "chess.app", "methodName": "move", "args": "{...serialized args...}", "amount": 0 } ``` In this case the `action` is `call`, so the function checks the `amount` to be within the withdrawal limit, check that the contract name is `chess.app` and if there were the last 3 calls were not in the last 20 blocks issue an async call to the `chess.app`. The same `proxy` function in theory can handle other actions, e.g. staking or vesting. The benefit of having a proxy function on your own account is that it doesn't require additional receipt, because the account's state and the code are available at the transaction verification time. An example of an access key limited to `proxy` function: ```rust /// vasya.near,3bc2b3b AccessKey { nonce: 0, permission: AccessKeyPermission::FunctionCall(FunctionCallPermission { // Allowance can be large enough, since the user is likely trusting the app. allowance: Some(1_000_000_000), // This access key restricts access to user's account `vasya.near` contract. // Most likely, the contract code can be deployed and upgraded directly from the wallet. receiver_id: "vasya.near", // The method is restricted to proxy, which does all the security checks. method_name: Some("proxy"), }), } ``` # Reference-level explanation [reference-level-explanation]: #reference-level-explanation - Access keys are stored with the `account_id,public_key` key. Where `account_id` and `public_key` are actual Account ID and public keys, and `,` is a separator. They should be stored on the same shard as the account. - Access keys storage rent should be accounted and paid from the account directly without affecting the allowance. - Access keys allowance can exceed the account balance. - To validate a transaction signed with the AccessKey, we need to first validate the signature, then fetch the Account and the AccessKey, validate that we have enough funds and verify permissions. - Account creation should now create a full access permission access key, instead of public keys within the account. - SwapKey transaction should just replace the old access key with the given new access key. ### Technical changes #### `nonce` on the AccessKey level instead of account level Since access keys can be used by the different people or parties at the same time, we need to be able to have separate nonce for each key instead of a single nonce at the account level. With a single nonce on the account level, there is a high probability that 2 apps would use the same nonce for 2 different transactions and one of this transactions would be rejected. Previously we were ordering transactions by nonce and rejecting transactions with a duplicated or lower nonce. With the access key nonce, we still need to order transactions by nonce, but now we need to group them by `account_id,public_key` key instead of just account_id. To prevent one access key from having a priority on other access keys, we should order transactions by hash when determining which transactions should be added to the block. The suggestion from @nearmax: " We need to spec out here how transactions from different access keys are going to be ordered with respect to each other. For example: 3 access keys (A,B,C) issue 3 transactions each: A1, A2, A3; B1,B2,B3; C1, C2, C3; All these transactions operate on the same state so they need to have an order. First transaction to execute is one of {A1,B1,C1} that has lowest hash, let's say it is B1. Second transaction to execute is one of {A1,B2,C1} with lowest hash, etc. " We should also restrict the nonce of the next transaction to be exactly the previous nonce incremented by 1. It will help us with ordering transactions. The transaction ordering should be a separate topic which should also include security for transactions expiration and fork selection. #### `allowance` field Allowance is the amount of tokens the AccessKey can spend from the account balance. When some amount is spent, it's subtracted from both the allowance of the access key and from the account balance. If in some case the user wants to have unlimited allowance for this key, then we have a `None` allowance option. NOTE: In the previous iteration of access keys, we used balance instead of the allowance. But it required to sum up all access keys balances to get the the total account balance. It also prevented sharing of the account balance between access keys. #### Permissions Almost all desired use-cases of access keys can be achieved by using the old permissions model. It restricts access keys to only issue function call with no attached tokens. The function calls are restricted to the selected `receiver_id` and potentially restricted to a single `method_name`. Anything non-trivial can be done by the contract that receives this call, e.g. through `proxy` function. To remove public keys from the account, we added a new permission that full access to the account and not limited by the allowance. #### How is `storage_usage` computed? If we use protobuf size to compute the `storage_usage` value, then protobuf might compress `u128` value and it would affect storage usage every time the `allowance` is modified. The best option would be is to change `storage_usage` only when the access key is created or removed. So that changes to the `allowance` value shouldn't change the `storage_usage` value. For this to work, we might need to update the storage computation formula for the access key, e.g. the one that ignores the compressed size of the `allowance` and instead just relies on the 16 bytes of `u128` size. Especially, because we currently don't use the proto size for the storage_usage for the account itself. # Drawbacks [drawbacks]: #drawbacks Currently the permission model is quite limited to either a function call with one or any method names, or a full access key. But we may add more permissions in the future in order to handle this issue. # Rationale and alternatives [rationale-and-alternatives]: #rationale-and-alternatives ## Alternatives #### More permissions directly on the access key For example we can have multiple method names, multiple contract_id/method_name pairs or different transactions types (e.g. only allow staking transactions). This can be achieved with the contract and a dedicated function that does this control. So to keep the runtime simple and secure we should avoid doing more checks, since they are not accounted for fees. It's also can be achieved if we refactor SignedTransaction to only use method_names instead of oneof body types. #### Balance instead of allowance Allowance enables sharing of a single account balance with multiple access keys. E.g. if you use 5 apps, you can give full allowance to each app instead of splitting balance into 5 parts. It's also easier to work with, than access keys balances. Previously we have AccessKey's balance owner, so the dApp could sponsor users. But it can be achieved by dApps creating access keys from their account, effectively paying for all transactions. #### Not exposing `nonce` on each AccessKey If you use 2 applications at the same time, e.g. a mobile app and a desktop wallet, you might run into a `nonce` collision at the account level, which would cancel one of the transaction. It would happen more frequently with more apps being used. As for the runtime multi nonce handling per account, we need to think and verify security a little more. #### `receiver_id` being an `Option<AccountId>` In the previous design, the `receiver_id` was called `contract_id` and was an option field. But it didn't remove the requirement for the receiver when it was `None`. Instead it was assuming the access key is pointed to the owner's account. We can potentially use `None` to mean unlimited key, and require user to explicitly specify their own account_id if they want to use proxy function. # Unresolved questions [unresolved-questions]: #unresolved-questions #### Transactions ordering and nonce restrictions That question is still unresolved. Whether we should restrict TX nonce to be +1 or not restricting. It's not a blocking change, but it would make sense to do this change with other SignedTransaction security features such as minimum hash of a block header and block expiration. #### Permissions Not clear whether a single pair of `receiver_id`/`method_name` is enough to cover all use-cases at the moment. E.g. if I want to use my account that already has some code on it, e.g. vesting locked account. I can't deploy a new code on it, so I can't use a `proxy` method. # Future possibilities [future-possibilities]: #future-possibilities For all use-cases to work we need to add all missing runtime methods that are currently only possible with `SignedTransaction` at the moment, e.g. staking, account creation, public/access key management and code deployment. Next we might consider refactoring stake out of `Account` and also refactor `SignedTransaction` to support text based method names instead of enums. We should also think about storing the same code (by hash) only once instead of storing for each account. Especially, if we adopt `proxy` model.
--- id: near-cli title: NEAR CLI --- The NEAR [Command Line Interface](https://github.com/near/near-cli) (CLI) is a tool that enables to interact with the NEAR network directly from the shell. Among other things, the NEAR CLI enables you to: - Login with a NEAR account - Deploy a contract - Interact and query information from a deployed contract :::tip Under the hood, NEAR CLI utilizes the [`NEAR JavaScript API`](https://github.com/near/near-api-js) ::: --- :::info The NEAR CLI also comes with an implementation in Rust called [`near-cli-rs`](https://github.com/near/near-cli-rs). If you want to use `near-cli` while you have `near-cli-rs` installed, prefix the following commands with `npx`. ::: ## Overview _Click on a command for more information and examples._ | Command | Description | |-------------------------------------------------|-------------------------------------------------------------------------------------------| | **ACCESS KEYS** | | | [`near add-credentials`](#near-add-credentials) | Stores credentials for an account locally | | [`near add-key`](#near-add-key) | adds a new access key to an account | | [`near delete-key`](#near-delete-key) | deletes an access key from an account | | [`near generate-key`](#near-generate-key) | generates a key pair and **optionally** stores it locally as credentials for an accountId | | [`near list-keys`](#near-keys) | displays all access keys and their details for a given account | | [`near login`](#near-login) | stores a full access key locally using [NEAR Wallet](https://wallet.testnet.near.org/) | | **ACCOUNTS** | | | [`near create-account`](#near-create-account) | creates a new account, either using a faucet to fund it, or an account saved locally | | [`near delete-account`](#near-delete) | deletes an account and transfers remaining balance to a beneficiary account | | [`near list-keys`](#near-keys) | displays all access keys for a given account | | [`near send-near`](#near-send) | sends tokens from one account to another | | [`near state`](#near-state) | shows general details of an account | | **CONTRACTS** | | | [`near call`](#near-call) | makes a contract call which can invoke `change` _or_ `view` methods | | [`near deploy`](#near-deploy) | deploys a smart contract to the NEAR blockchain | | [`near storage`](#near-storage) | Shows the storage state of a given contract, i.e. the data stored in a contract | | [`near view`](#near-view) | makes a contract call which can **only** invoke a `view` method | | **TRANSACTIONS** | | | [`near tx-status`](#near-tx-status) | queries a transaction's status by `txHash` | --- ## Setup ### Installation > Make sure you have a current version of `npm` and `NodeJS` installed. #### Mac and Linux 1. Install `npm` and `node` using a package manager like `nvm` as sometimes there are issues using Ledger due to how OS X handles node packages related to USB devices. [[click here]](https://nodejs.org/en/download/package-manager/) 2. Ensure you have installed Node version 12 or above. 3. Install `near-cli` globally by running: ```bash npm install -g near-cli ``` For example, on Ubuntu 20.04 `near-cli` can be installed by running: ```bash # Install nvm (https://github.com/nvm-sh/nvm?tab=readme-ov-file#installing-and-updating) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc # Install node nvm install node # Install near-cli npm install -g near-cli # near-cli works! near --help ``` #### Windows > For Windows users, we recommend using Windows Subsystem for Linux (`WSL`). 1. Install `WSL` [[click here]](https://docs.microsoft.com/en-us/windows/wsl/install-manual#downloading-distros) 2. Install `npm` [[click here]](https://www.npmjs.com/get-npm) 3. Install ` Node.js` [ [ click here ]](https://nodejs.org/en/download/package-manager/) 4. Change `npm` default directory [ [ click here ] ](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally#manually-change-npms-default-directory) - This is to avoid any permission issues with `WSL` 5. Open `WSL` and install `near-cli` globally by running: ```bash npm install -g near-cli ``` --- ### Network selection > The default network for `near-cli` is `testnet`. - You can change the network by prepending an environment variable to your command. ```bash NEAR_NETWORK=testnet near send ... ``` - Alternatively, you can set up a global environment variable by running: ```bash export NEAR_NETWORK=mainnet ``` - All commands that interact with the network also allow to pass the `--networkId` option. ```bash near send-near ... --networkId mainnet ``` --- ### Custom RPC server selection You can set custom RPC server URL by setting these env variables: ```bash NEAR_MAINNET_RPC NEAR_TESTNET_RPC ``` Clear them in case you want to get back to the default RPC server. Example: ```bash export NEAR_TESTNET_RPC=<put_your_rpc_server_url_here> ``` --- ## Access Keys All keys are stored locally at the root of your `HOME` directory: - `~/.near-credentials` _(MAC / Linux)_ - `C:\Users\YOUR_ACCOUNT\.near-credentials` _(Windows)_ Inside `.near-credentials`, access keys are organized in network subdirectories: `testnet`, and `mainnet`. These network subdirectories contain `.JSON` objects with an: - `account_id` - `private_key` - `public_key` ### `near add-credentials <accountId>` > Stores credentials (full-access-key) locally for an already existing account. - arguments: `accountId` - options: `--seedPhrase` or `--secretKey` **Examples:** ```bash near add-credentials example-acct.testnet --seedPhrase "antique attitude say evolve ring arrive hollow auto wide bronze usual unfold" ``` --- ### `near add-key` > Adds either a **full access** or **function access** key to a given account. > Optionally allows to sign with a Ledger: `--signWithLedger` `--ledgerPath` **Note:** You will use an _existing_ full access key for the account you would like to add a _new_ key to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) #### 1) add a `full access` key - arguments: `accountId` `publicKey` **Example:** ```bash near add-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Adding full access key = Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S to example-acct.testnet. Transaction Id EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg ``` </p> </details> #### 2) add a `function call` key - arguments: `accountId` `publicKey` `--contract-id` - options: `--method-names` `--allowance` > `accountId` is the account you are adding the key to > > `--contract-id` is the contract you are allowing methods to be called on > > `--method-names` are optional and if omitted, all methods of the `--contract-id` can be called. > > `--allowance` is the amount of Ⓝ the key is allowed to spend on gas fees _only_ (default: 0). **Note:** Each transaction made with this key will have gas fees deducted from the initial allowance and once it runs out a new key must be issued. **Example:** ```bash near add-key example-acct.testnet GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi --contract-id example-contract.testnet --method-names example_method --allowance 30000000000 ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Adding function call access key = GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi to example-acct.testnet. Transaction Id H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r ``` </p> </details> --- ### `near delete-key` > Deletes an existing key for a given account. > Optionally allows to sign with a Ledger: `--signWithLedger` `--ledgerPath` - arguments: `accountId` `publicKey` - options: `--networkId`, `force` **Note:** You will need separate full access key for the account you would like to delete a key from. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near delete-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Transaction Id 4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT ``` </p> </details> --- ### `near generate-key` > Displays a key-pair and seed-phrase and optionally stores it locally in `.near-credentials`. - arguments: `accountId` or `none` - options: `--fromSeedPhrase`, `--saveImplicit`, `--queryLedgerPK` **Note:** There are several ways to use `generate-key` that return very different results. Please reference the examples below for further details. --- #### 1a) `near generate-key` > Creates and displays a key pair ```bash near generate-key ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"} Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411 ``` </p> </details> --- #### 1b) `near generate-key --saveImplicit` > Creates and displays a key pair, saving it locally in `.near-credentials` as an implicit account. ```bash near generate-key --saveImplicit ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"} Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411 Storing credentials for account: 9d6e4506ac06ab66a25f6720e400ae26bad40ecbe07d49935e83c7bdba5034fa (network: testnet) Saving key to '~/.near-credentials/testnet/9d6e4506ac06ab66a25f6720e400ae26bad40ecbe07d49935e83c7bdba5034fa.json' ``` </p> </details> --- #### 2) `near generate-key accountId` > Creates a key pair locally in `.near-credentials` with an `accountId` that you specify. **Note:** This does NOT create an account with this name. ```bash near generate-key example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"} Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411 Storing credentials for account: example.testnet (network: testnet) Saving key to '~/.near-credentials/testnet/example.testnet.json' ``` </p> </details> --- #### 3a) `near generate-key --fromSeedPhrase="your seed phrase"` > Uses a seed phrase to display a public key and [implicit account](../1.concepts/protocol/account-id.md#implicit-accounts-implicit-accounts) ```bash near generate-key --seedPhrase="antique attitude say evolve ring arrive hollow auto wide bronze usual unfold" ``` <details> <summary><strong>Example Response</strong></summary> ``` Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"} Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411 ``` </details> --- #### 3b) `near generate-key accountId --seedPhrase="your seed phrase"` Will store the key pair corresponding to the seedPhrase in `.near-credentials` with an `accountId` that you specify. <details> <summary><strong>Example Response</strong></summary> <p> ``` Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"} Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411 ``` </p> </details> --- #### 4a) `near generate-key --queryLedgerPK` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/integrations/implicit-accounts) using the default HD path (`"44'/397'/0'/0'/1'"`) ```bash near generate-key --queryLedgerPK ``` You should then see the following prompt to confirm this request on your Ledger device: ``` Make sure to connect your Ledger and open NEAR app Getting Public Key from Ledger... ``` After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wyeRvKIWv61NjmQZEkWTMzAYgdfx6oSeB2 Implicit account: 42c320xc20739fd9a6bqf2f89z61rd14efe5d3de234199bc771235a4bb8b0e1 ``` </p> </details> --- #### 3b) `near generate-key --queryLedgerPK --ledgerPath="HD path you specify"` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/integrations/implicit-accounts) using a custom HD path. ```bash near generate-key --queryLedgerPK --ledgerPath="44'/397'/0'/0'/2'" ``` You should then see the following prompt to confirm this request on your Ledger device: ``` Make sure to connect your Ledger and open NEAR app Waiting for confirmation on Ledger... ``` After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wye3dfa32rDjmQZEkWTMzAYgCX6oSeB2 Implicit account: 42c320xc20739ASD9a6bqf2Dsaf289z61rd14efe5d3de23213789009afDsd5bb8b0e1 ``` </p> </details> --- ### `near list-keys` > Displays all access keys for a given account. - arguments: `accountId` **Example:** ```bash near list-keys client.chainlink.testnet ``` <details> <summary> <strong>Example Response</strong> </summary> <p> ``` Keys for account client.chainlink.testnet [ { public_key: 'ed25519:4wrVrZbHrurMYgkcyusfvSJGLburmaw7m3gmCApxgvY4', access_key: { nonce: 97, permission: 'FullAccess' } }, { public_key: 'ed25519:H9k5eiU4xXS3M4z8HzKJSLaZdqGdGwBG49o7orNC4eZW', access_key: { nonce: 88, permission: { FunctionCall: { allowance: '18483247987345065500000000', receiver_id: 'client.chainlink.testnet', method_names: [ 'get_token_price', [length]: 1 ] } } } }, [length]: 2 ] ``` </p> </details> --- ### `near login` > locally stores a full access key of an account you created with [MyNEARWallet](https://testnet.mynearwallet.com/). - arguments: `none` - options: `--networkId` **Example:** ```bash near login ``` **Custom wallet url:** The default wallet URL is `https://testnet.mynearwallet.com/`. However, if you want to change to a different wallet URL, you can set the environmental variable `NEAR_MAINNET_WALLET` or `NEAR_TESTNET_WALLET`. ```bash export NEAR_TESTNET_WALLET=https://wallet.testnet.near.org/ near login ``` --- ## Accounts ### `near create-account` > Creates an account using an existing account or a faucet service to pay for the account's creation and initial balance. - arguments: `accountId` - options: `--initialBalance`, `--useFaucet`, `--useAccount`, `--seedPhrase`, `--publicKey`, `--signWithLedger`, `--ledgerPath`, `--useLedgerPK`, `--PkLedgerPath` **Examples:**: ```bash # Creating account using `example-acct.testnet` to fund it near create-account new-acc.testnet --useAccount example-acct.testnet ``` ```bash # Creating account using the faucet to fund it near create-account new-acc.testnet --useFaucet ``` ```bash # Creating a pre-funded account that can be controlled by the Ledger's public key near create-account new-acc.testnet --useFaucet --useLedgerPK ``` ```bash # Creating an account using a Ledger account near create-account new-acc.testnet --useAccount ledger-acct.testnet --signWithLedger ``` **Subaccount example:** ```bash # Using an account to create a sub-account near create-account sub-acct.example-acct.testnet --useAccount example-acct.testnet ``` ```bash # Creating a sub-account using the Ledger that can also be controlled by the ledger near create-account sub.acc.testnet --useAccount sub.acc.testnet --signWithLedger --useLedgerPK ``` **Example using `--initialBalance`:** ```bash near create-account sub-acct2.example-acct.testnet --useAccount example-acct.testnet --initialBalance 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Saving key to '/HOME_DIR/.near-credentials/default/sub-acct2.example-acct.testnet.json' Account sub-acct2.example-acct.testnet for network "default" was created. ``` </p> </details> --- ### `near delete-account` > Deletes an account and transfers remaining balance to a beneficiary account. - arguments: `accountId` `beneficiaryId` - options: `force`, `--signWithLedger`, `--ledgerPath` **Example:** ```bash near delete-account sub-acct2.example-acct.testnet example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Deleting account. Account id: sub-acct2.example-acct.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, beneficiary: example-acct.testnet Transaction Id 4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX Account sub-acct2.example-acct.testnet for network "default" was deleted. ``` </p> </details> --- ### `near send-near` > Sends NEAR tokens (Ⓝ) from one account to another. - arguments: `senderId` `receiverId` `amount` - options: `--signWithLedger`, `--ledgerPath` **Note:** You will need a full access key for the sending account. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near send-near sender.testnet receiver.testnet 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Sending 10 NEAR to receiver.testnet from sender.testnet Transaction Id BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN ``` </p> </details> --- ### `near state` > Shows details of an account's state. - arguments: `accountId` **Example:** ```bash near state example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json { "amount": "99999999303364037168535000", "locked": "0", "code_hash": "G1PCjeQbvbUsJ8piXNb7Yg6dn3mfivDQN7QkvsVuMt4e", "storage_usage": 53528, "storage_paid_at": 0, "block_height": 21577354, "block_hash": "AWu1mrT3eMJLjqyhNHvMKrrbahN6DqcNxXanB5UH1RjB", "formattedAmount": "99.999999303364037168535" } ``` </p> </details> --- ## Contracts ### `near call` > makes a contract call which can modify _or_ view state. **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `contractName` `method_name` `{ args }` `--accountId` - options: `--gas` `--deposit` `--signWithLedger` `--ledgerPath` **Example:** ```bash near call guest-book.testnet addMessage '{"text": "Aloha"}' --account-id example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Scheduling a call: guest-book.testnet.addMessage({"text": "Aloha"}) Transaction Id FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK '' ``` </p> </details> --- ### `near deploy` > Deploys a smart contract to a given accountId. - arguments: `accountId` `.wasmFile` - options: `initFunction` `initArgs` `initGas` `initDeposit` **Note:** You will need a full access key for the account you are deploying the contract to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near deploy example-contract.testnet out/example.wasm ``` **Initialize Example:** ```bash near deploy example-contract.testnet out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}' ``` <details> <summary><strong>Example Response</strong></summary> <p> ``` Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: main.wasm Transaction Id G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt To see the transaction in the transaction explorer, please open this url in your browser https://testnet.nearblocks.io/txns/G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt Done deploying to example-contract.testnet ``` </p> </details> --- ### `near storage` > Shows the storage state of a given contract, i.e. the data stored in a contract. - arguments: `contractName` - options: `--finality`, `--utf8`, `--blockId`, `--prefix` **Example:** ```bash near storage hello.near-examples.testnet --finality optimistic --utf8 ``` <details> <summary><strong>Example Response</strong></summary> ```bash [ { key: 'STATE', value: '\x10\x00\x00\x00Passei por aqui!' } ] ``` </details> --- ### `near view` > Makes a contract call which can **only** view state. _(Call is free of charge)_ - arguments: `contractName` `method_name` `{ args }` - options: `default` **Example:** ```bash near view guest-book.testnet getMessages '{}' ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash View call: guest-book.testnet.getMessages({}) [ { premium: false, sender: 'waverlymaven.testnet', text: 'TGIF' }, { premium: true, sender: 'waverlymaven.testnet', text: 'Hello from New York 🌈' }, { premium: false, sender: 'fhr.testnet', text: 'Hi' }, { premium: true, sender: 'eugenethedream', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'hello' }, { premium: true, sender: 'dongri.testnet', text: 'hey' }, { premium: false, sender: 'hirokihori.testnet', text: 'hello' }, { premium: true, sender: 'eugenethedream', text: 'hello' }, { premium: false, sender: 'example-acct.testnet', text: 'Aloha' }, [length]: 10 ] ``` </p> </details> --- ## Transactions ### `near tx-status` > Queries transaction status by hash and accountId. - arguments: `txHash` `--accountId` - options: `default` **Example:** ```bash near tx-status FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK --accountId guest-book.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json Transaction guest-book.testnet:FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK { status: { SuccessValue: '' }, transaction: { signer_id: 'example-acct.testnet', public_key: 'ed25519:AXZZKnp6ZcWXyRNdy8FztYrniKf1qt6YZw6mCCReXrDB', nonce: 20, receiver_id: 'guest-book.testnet', actions: [ { FunctionCall: { method_name: 'addMessage', args: 'eyJ0ZXh0IjoiQWxvaGEifQ==', gas: 300000000000000, deposit: '0' } }, [length]: 1 ], signature: 'ed25519:5S6nZXPU72nzgAsTQLmAFfdVSykdKHWhtPMb5U7duacfPdUjrj8ipJxuRiWkZ4yDodvDNt92wcHLJxGLsyNEsZNB', hash: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK' }, transaction_outcome: { proof: [ [length]: 0 ], block_hash: '6nsjvzt6C52SSuJ8UvfaXTsdrUwcx8JtHfnUj8XjdKy1', id: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK', outcome: { logs: [ [length]: 0 ], receipt_ids: [ '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', [length]: 1 ], gas_burnt: 2427979134284, tokens_burnt: '242797913428400000000', executor_id: 'example-acct.testnet', status: { SuccessReceiptId: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU' } } }, receipts_outcome: [ { proof: [ [length]: 0 ], block_hash: 'At6QMrBuFQYgEPAh6fuRBmrTAe9hXTY1NzAB5VxTH1J2', id: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', outcome: { logs: [ [length]: 0 ], receipt_ids: [ 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', [length]: 1 ], gas_burnt: 3559403233496, tokens_burnt: '355940323349600000000', executor_id: 'guest-book.testnet', status: { SuccessValue: '' } } }, { proof: [ [length]: 0 ], block_hash: 'J7KjpMPzAqE7iX82FAQT3qERDs6UR1EAqBLPJXBzoLCk', id: 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', outcome: { logs: [ [length]: 0 ], receipt_ids: [ [length]: 0 ], gas_burnt: 0, tokens_burnt: '0', executor_id: 'example-acct.testnet', status: { SuccessValue: '' } } }, [length]: 2 ] } ``` </p> </details> --- ## Global Options | Option | Description | |-----------------------------|-------------------------------------------------------------------------------------------------| | `--help` | Show help [boolean] | | `--version` | Show version number [boolean] | | `-v, --verbose` | Prints out verbose output [boolean] [default: false] |
```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: 'add_proposal', args: { proposal: { description: "My first proposal", kind: { Transfer: { token_id: "", receiver_id: "bob.near", amount: "10000000000000000000000000", }, }, }, }, contractId: DAO_CONTRACT_ADDRESS, gas: 300000000000000, deposit: 100000000000000000000000 }); ``` _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
Stake Wars Week 2 Retro DEVELOPERS November 18, 2019 On Nov 11, 4pm PST we had the second Stake Wars call with around 20 people. Due to the issues uncovered last week, we took more caution this time and chose to start the genesis in house and invite external people to join afterwards. The network was started several minutes before the call, and during the call, Peter demonstrated how to join the network and stake to become a validator. The network went down at 14560 blocks at around 9:00pm PST on Monday. All validating nodes crashed almost simultaneously. From the logs we observed that the nodes had dramatic increase in memory and cpu usage right before the crash. Due to the lack of proper logging, we were not able to determine the cause of the crash and therefore decided to restart the network on Tuesday with more careful debugging and logging setup. The network crashed again on Tuesday night, around 11pm PST. From the valgrind output we saw that a function that broadcasts message to the network used an unreasonable amount of memory. After some investigation and sifting through logs of more than 1GB we found that there is a subtle bug in our network code that would only be triggered under a specific circumstance. We quickly deployed a quick fix that prevents such bug in normal situations but are still working on fully fixing the issue in the byzantine setting. We restarted the network again on Wednesday and it has been running without any downtime since then. Released v0.4.6 with updates (fully implemented finality gadget) and fixes described below. Issues: The aforementioned network bug. More specifically, when we receive account announcement we check whether it already exists in the routing table by doing an exact match. However, since account announcement has epoch id, and because a newly joined peer would rebroadcast the account announcement they receive from peers, if a node in the network announce their account for the next epoch at the same time, it causes the announcement to overwrite each other. Each overwrite would lead to a broadcasting to the entire network and therefore causes exponential growth of network messages, which causes the entire network to crash. The issue is temporarily fixed in https://github.com/nearprotocol/nearcore/pull/1688 and we are still working on fully fixing the issue. We also noticed that, even though we fixed some major memory leaks last week, nodes were still leaking memory slowly. Through inspection we found that some caches in ShardsManager were not properly implemented and caused the leak. This issue is fixed in https://github.com/nearprotocol/nearcore/pull/1706 (which is pending more testing). There is also some issue with rpc that makes wallet sometimes nonfunctional. Validators complained that they have to try multiple times to register one account name. This issue is fixed in https://github.com/nearprotocol/nearcore/pull/1699. The experience this week shows that stability of our network is improving with each week. For next week, we will again open registration for stake wars to the public with a customized landing page that does input validation. We also invite validator to start actually trying malicious or DDOS types of attacks to start testing non vanilla behaviors.
--- id: epoch title: Epoch --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; An **epoch** is a unit of time when validators of the network remain constant. It is measured in blocks: - Both `testnet` and `mainnet` have an epoch duration of 43,200 blocks. Ideally epochs last about 12 hours, since blocks are created every second (in reality, they take slightly longer to be created). - You can view this setting by querying the **[`protocol_config`](/api/rpc/setup#protocol-config)** RPC endpoint and searching for `epoch_length`. **Note:** Nodes garbage collect blocks after 5 epochs (~2.5 days) unless they are [archival nodes](https://near-nodes.io/intro/node-types#archival-node). **Example:** <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "EXPERIMENTAL_protocol_config", "params": { "finality": "final" } } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_protocol_config \ params:='{ "finality": "final" }' ``` </TabItem> </Tabs> **Example Response:** ```json { "jsonrpc": "2.0", "result": { "protocol_version": 44, "genesis_time": "2020-07-21T16:55:51.591948Z", "chain_id": "mainnet", "genesis_height": 9820210, "num_block_producer_seats": 100, "num_block_producer_seats_per_shard": [ 100 ], "avg_hidden_validator_seats_per_shard": [ 0 ], "dynamic_resharding": false, "protocol_upgrade_stake_threshold": [ 4, 5 ], "epoch_length": 43200, "gas_limit": 1000000000000000, "min_gas_price": "1000000000", "max_gas_price": "10000000000000000000000", "block_producer_kickout_threshold": 90, "chunk_producer_kickout_threshold": 90, // ---- snip ---- } ``` You can learn more about how epochs are used to manage network validation in the [Validator FAQ](https://github.com/near/wiki/blob/master/Archive/validators/faq.md#what-is-an-epoch). :::tip Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> Ask it on StackOverflow! </a> :::
An Update from the NEAR Foundation NEAR FOUNDATION January 11, 2024 Dear NEAR Community, The NEAR Foundation’s vision has always been to help the world create a truly Open Web, giving all people full control of their data, privacy, and power of governance. In 2023, the NEAR ecosystem saw remarkable progress towards this vision, with the NEAR Protocol now home to three of the top ten apps in Web3, a record number of daily users, and closer collaboration than ever with the Ethereum community. With the NEAR Foundation Council (NFC), we’ve conducted a thorough review of the Foundation’s activities. During this process, we heard feedback that the Foundation has not always been as effective as it could be, sometimes moving too slowly and trying to do too many things at once. Following this review, we have decided to significantly consolidate the core Foundation team to focus on a narrower and higher-impact set of activities. Over time, Foundation’s footprint will continue to contract as the ecosystem further decentralizes and various nodes drive more activity in the network and across the ecosystem. As part of this realignment, NEAR Foundation will reduce its team by approximately 40%, impacting 35 colleagues, primarily across the marketing, business development, and community teams. The NEAR Protocol Engineering Team at Pagoda will continue to operate as it has. The NEAR Foundation will provide support to affected colleagues during this time to help them find new opportunities in the NEAR ecosystem, the Web3 industry, and beyond. We thank each of our departing colleagues for your efforts and contributions towards our shared vision of the Open Web. The NEAR Foundation treasury remains strong and well-managed, with over $285m fiat, 305m NEAR (worth over $1B), and $70m of investments and loans. The Foundation is well-placed to continue to support the ongoing growth, development, and further decentralization of the NEAR Protocol and ecosystem. Thank you to everyone in the NEAR community for your ongoing efforts and support. We are excited to move forward with more focus, more efficiency, and more speed. We’ll share more updates soon about what comes next as we work to advance chain abstraction, user-owned AI, and mainstream adoption of the Open Web. Keep building,
Embracing Decentralization: What’s Next for the NEAR Wallet DEVELOPERS July 12, 2023 When NEAR Mainnet launched in late 2020, it included a wallet built and hosted by Pagoda’s (then known as Near Inc.) core team on https://wallet.near.org to support NEAR’s unique account model. Nearly three years later, the NEAR wallet ecosystem is home to a myriad of high quality, open source wallets supported by NEAR’s community of active contributors. This significant milestone reflects NEAR’s ongoing commitment to empower users and foster decentralization. The evolution of NEAR wallets also showcases the substantial growth of the ecosystem, as NEAR now supports a diverse list of cross-chain wallets, as well as native wallets with innovative onboarding approaches such as FastAuth. To celebrate these excellent contributions from across the NEAR community, and to reflect the priority of decentralization, over the next few months Pagoda will start migrating the domain https://wallet.near.org from being a browser wallet to being a wallet hub. In this way, https://wallet.near.org will become the reference place for all NEAR wallets, allowing users to discover and implement the right wallets for their specific needs. If you currently use https://wallet.near.org as your main wallet, you have nothing to worry about. The Pagoda team has been working hard to build a Wallet Transfer Wizard to help you transfer your accounts to a new wallet easily and smoothly, while keeping your funds and assets safe. The Transfer Wizard will allow you to choose between Browser and Extension-based wallets, so you will still have the same friendly wallet experience you are accustomed to after the Wizard is finished. For more details, visit the Migrating from NEAR Wallet page. Timeline for transitioning the main wallet domain The NEAR Wallet will remain a browser wallet until January 1st, 2024, during which time the wallet will encourage and help you to transfer your accounts to a new wallet. You can do this manually with your recovery phrase or use the Transfer Wizard to securely migrate your accounts to the wallet of your choice. Do not worry if you have not transferred your accounts by January 1st, 2024 —the Transfer Wizard will still be available after the wallet functionality sunsets. Rest assured that your assets will remain secure until you import them to a new wallet. The Transfer Wizard will remain available on the new wallet landing page at wallet.near.org indefinitely. This repurposed page will act as an introduction to the various options for wallets in the NEAR ecosystem. A new era for NEAR Wallets This new step moves NEAR closer to achieving a truly decentralized ecosystem driven by its own community. Thanks to the wallet hub and the wallet selector (which enables the use of any compatible NEAR wallet in web applications), users will now be able to use any wallet they like. This will not only improve their experience on NEAR, but also the full spectrum of available Web3 experiences thanks to the BOS.
July in Review: 700 Projects Milestone, NEARCON Tickets, and Women in Web3 COMMUNITY August 1, 2022 Hello, NEAR! There’s been lots of action in July, from new milestones and the NEARCON 2022 announcement to a major new initiative aimed at expanding diversity in Web3. Let’s take a look at what’s been happening across the NEAR ecosystem, from communities to NEAR Foundation initiatives and beyond. Ecosystem Panel: Helping the Climate with Web3 In July, the NEAR Town Hall got a makeover. The new town hall format, Ecosystem Panel, allows the NEAR community to focus on projects and initiatives popping up across the ecosystem. In the first Ecosystem Panel, “Helping the Climate with Web3”, learn how blockchain, crypto and the world of Web3 will enable social good and take climate, transparency, and finance to the next level. Moderated by David Morrison, the new Community Engagement Lead at NEAR Foundation, the panel features Frederic Fournier, CEO and Co-founder of Open Forest Protocol, Candice Ammori, Director of On Deck Climate Tech, and Emiliano Gutierrez, CEO and Co-founder of Raiz vertical farms. Twitter Spaces AMA on Social Good On July 25th, NEAR hosted an AMA on “social good” on Twitter Spaces. The AMA featured moderator David Morrison (Community Engagement Lead at NEAR Foundation), Open Forest Protocol’s Frederic Fournie, On Deck Climate Tech’s Candice Ammori, and Raiz Farm’s Emiliano Gutierrez. Check out the Twitter Spaces AMA here. Foundation News This month, NEAR Foundation announced NEARCON Beta, the second edition of its flagship conference. NEARCON is returning to the beautiful coastal city of Lisbon, Portugal, and the foundation has the ambitious goal of selling more than 3,000 tickets. Spread the word! The Foundation also launched Women in Web3 Changemakers, an an exciting new initiative that will celebrate the pivotal role women are playing in the Web3 story. We’ve teamed up with Forkast, one of the fastest growing media companies in the Web3 space. Nominations are now open. So, if you know of women who are making a difference in this space, nominate them! NEAR Foundation has also been publishing “NEAR & Social Good”, its July content series. The series explores a number of projects that are building for social good on the NEAR ecosystem. Read part one, part two, part three, and part four. Ecosystem News The NEAR ecosystem is popping. It just hit a huge milestone of 700 projects now building on NEAR. This demonstrates incredible growth from last year when the number was a fraction of the new total. At EthCC, NEAR Protocol Co-founder Illia Polosukhin gave a talk on governance. As Illia noted, decentralized governance is one of NEAR’s core pillars. To get it working smoothly at the protocol and individual DAO level, Illia recommends the community begin a major effort to experiment with and iterate governance. NEAR now offers more institutional custody options through its partnership with BitGo. This is a huge step for the ecosystem, as institutional investors now have more ways to support NEAR’s continued growth. In other ecosystem news, Sweatcoin recently broke 11m wallets created. In Stake Wars II: A New Validator, NEAR introduced the Chunk-Only Producer—the next step in network decentralization. Elsewhere, Globe Exchange announced a NEAR listing, and Pocket Network now supports NEAR. By adding RPC support for NEAR, the ecosystem is now able to serve the needs of developers who can now access reliable and highly decentralized blockchain data on demand. Wallet provider Nightly received a NEAR grant, joining a growing list of wallets in the NEAR ecosystem. Also, CornerstoneDAO announced an airdrop for LiNEAR users, while Aurora launched a community grants program. Oh, and NEAR Wallet issues are now fixed. Pagoda successfully worked through a series of issues with currency prices on the main NEAR Wallet. Get up to speed with the complete update here. NEAR in the press Open Forest Protocol, which is bringing the forestration industry into the Web3 era, is now on NEAR mainnet. OFP’s mainnet launch made the press in Fintech & Finance News. Forkast, a Web3 news publication, interviewed NEAR Foundation CEO Marieke Flament on the gender gap in Web3. Flament said, amongst other things, that despite progress on this front, there is more work to be done. Read the full interview with Marieke here. ICYMI: Man on the Streets interviews At Consensus 2022, NEAR Foundation’s Community Engagement Lead, David Morrison, caught up with several ecosystem figures to talk about the latest happenings on NEAR. David spoke with NEAR Co-founder Illia Polosukhin, NEAR Foundation CEO Marieke Flament, NEAR Foundation CMO Jack Collier, and Mya Shofany, the Foundation’s Regulatory Specialist, amongst others. Watch short “Man on the Street” interviews of them talking about the NEAR’s new Javascript SDK implementation, ecosystem values like openness and inclusivity, and the regulatory space. What excites @mariekeflament, NEAR Foundation CEO, the most about Web3? Catch up with Marieke at #Consensus2022 where she shares her thoughts on what true ownership really means and how Web3 can solve the world's biggest challenges. Watch now 👇 pic.twitter.com/EV006K3AXB — NEAR Protocol | NEARCON.org | Lisbon | Sept 11-14 (@NEARProtocol) July 18, 2022
--- title: 3.6 Staking description: Defining and understanding liquidity in DeFi --- # 3.6 All Roads Lead to Liquidity, and Liquid Staking The elephant in the room when discussing the principles of decentralized finance, is the practical liquidity needs that an ecosystem as a whole needs, in order to sustain continuous development of different DeFi, NFT, Gaming, Metaverse, and financial protocols. The reason this topic remains an elephant in the room is because builders and teams are usually only focused on their specific product or protocol, and are unaware of how the aggregate state of liquidity in an ecosystem can determine the success of future products. **_Defining Liquidity: From the highest level, liquidity refers to the ease with which an asset can be bought or sold on a market without affecting the price. A liquid market is one where there are many buyers and sellers, and the asset can be traded quickly and easily. Meanwhile, an illiquid market is one where there are few buyers or sellers, and the asset may be difficult to trade._** With this in mind, we can ask the most essential question on the topic: _Which products or dApps, require liquidity in crypto?_ Upon scrutinizing this question we find the following: * All decentralized marketplaces and lending protocols, require liquidity as a basis for executing loans or trades (AMMs/Orderbooks/etc.). * All NFT marketplaces require liquidity and volume, in order to sustain user confidence and price discovery in the underlying asset that is being purchased. * All marketplaces for game items, widgets, and characters, requires liquidity insofar as users are incentivized or are confident in their ability to re-sell their rewards / purchase in-game perks. * Any digital metaverse, with land, object, or user purchases. The underlying principle from these points, is that when we are not dealing with centralized entities, that can pool liquidity in siloes or hide liquidity shortages, or ultimately receive loans and credit injections when needed (think Repo markets in mainstream finance), we are faced with a very serious and new problem: _Open-source systems, and decentralized protocols, require liquidity in order to function both at their inception and at scale_. The idea of an open-source value imbued system, is one that is sustained by the collective of participants. Put another way, if we wish to create an internet where users have ownership of their money, data, and identity, then in order for different markets to function properly, it is up to the users to collectively pool their resources into these protocols! There is no central bank or federal reserve capable of bailing out these systems. ## The Liquidity Solar System To pull all of these topics under a single heading, we refer to the concept of a _liquidity solar system_ as it is illustrative of the role that liquidity plays in an ecosystem. The total value locked in an ecosystem, is much like the sun - the different protocols and dApps are like planets orbiting the sun. The concept is simple: So long as liquidity can move around the different protocols and dApps, and there are net _inflows_ into the ecosystem in question, virtually any future dApp or protocol has the capacity to steal liquidity from other protocols as they gain in popularity. This increase in popularity, usually triggers further liquidity inflows from either outside of crypto, or other ecosystems, and the process then repeats itself. Instead of looking at the Total Value Locked (TVL) if each individual protocol, if one takes a step back and looks at [the TVL of an entire ecosystem,](https://defillama.com/chains) it becomes crystal clear that the ecosystems with the most TVL also tend to be (1) The strongest in terms of price of token, (2) the largest in terms of active users, (3) the most innovative in terms of dApps being launched and new designs being pioneered, (4) The ones that attract the largest communities over time (exceptions include Tron - which is largely concentrated in China / East Asia). ![](@site/static/img/bootcamp/mod-em-3.6.1.png) [https://defillama.com/chains](https://defillama.com/chains) There are two fundamental dynamics that any ecosystem should prioritize when thinking about long-term growth in liquidity: 1. **Liquidity Inflows:** Why is there an interest from users and institutions, in bringing liquidity into an ecosystem, and how concretely is this done? What kind of ‘bridge’ is used? Is the bridge decentralized? What catalysts trigger the movement of value across the bridge? 2. **Ecosystem Generated Value:** Refers to new value, natively created inside of the ecosystem. The implicit premise of ecosystem generated value, is that if it is _valuable_ it will require a pair with some form of stable coin or other token in order to be traded. As such there is a direct correlation between the amount of ecosystem generated value, and the demand for liquidity inflows to support markets for that newly minted value (could be fungible, non-fungible value). ## Composability and Liquidity: Two Sides of the Same Coin? We have mentioned before, the fundamental innovation of crypto centering upon the notion of _composability_. The idea that value can flow and speak with each other, in a way that lowers transaction costs, and enhances user-choice. Liquidity should be understood, as a necessary precondition for composability in the following manner: In order for different types of value, to flow between and among other types of value, there must be an existing market or automatic swap mechanism that is willing to substitute one type of value for another. Concretely we can think of this through a number of examples: * I cannot loan out my NFT, unless there is a counterparty willing to accept the value of it, in exchange for credit (in stables or something other unit of value). Set value of my NFT is only possible through established price as through market discoverability (i.e. liquidity in the market). * I cannot create a market for exogenous value of things like DNA, Carbon Credits, or Art, without sufficient liquidity to trade against these items - regardless of whether they are fungible or non-fungible. * I cannot bring tokenized assets on-chain for a synthetic market, unless each asset that is mirrored on-chain has sufficient liquidity to trade on its own. Liquidity works very much like the blood of a crypto-ecosystem: It allows value to move between products and protocols, while also grounding new products that may emerge. A lack of liquidity in an ecosystem, risks limiting the growth of the ecosystem as a whole, due to limited capacity for markets to emerge, price-discovery to be set for particular assets, and users to convert assets across dApps. Interestingly, there is a common currency that can help facilitate the flow of liquidity within an ecosystem, and that happens to be the L1 mother token. ## Liquid Staking For any L1 ecosystem that exists, the native token of the blockchain is commonly used in proof of stake systems to be locked up within a node on the network. The tradeoff for the L1 ecosystem in question is the following: If more and more of the genesis token supply is locked on the network, then less and less of the token is available for liquidity pairing with other ecosystem tokens. In other words, the value in the ecosystem is fractured between securing the blockchain itself, and being used to stimulate value transfer within the ecosystem. Liquid staking solves this problem in the following manner: _“Liquid staking solves the illiquidity problem. A liquid staking provider takes token deposits, stakes those tokens, and gives the depositor a receipt which is redeemable for the staked tokens. The receipt is a representation of those staked tokens that can be traded or used as collateral elsewhere. For this reason, liquid staking tokens are sometimes referred to as liquid staking derivatives.” ([Finoa](https://www.finoa.io/blog/guide-liquid-staking/#what-is-liquid-staking-and-how-does-it-work))_ In other words, a node on the network can issue ‘staked NEAR’ or ‘staked ETH’ out to any delegator who wishes to deposit their real NEAR or real ETH into the node, to be secured on the network. The delegator can then use this ‘staked token’ as open liquidity in the ecosystem, while still being able to earn rewards from securing the network. This helps alleviate the original problem of limited liquidity from the blockchain base token, but in itself it is not sufficient to guarantee ecosystem wide liquidity across pairs. ## A Need For Better Liquidity Incentives? Liquidity incentives have traditionally been designed in two ways: 1. To directly reward liquidity providers by offering them a percentage return on the amount of value they have put into a liquidity pool - usually as the mother token of the protocol, or a basket of tokens in an ecosystem. This leads to what is known as _liquidity farming_. 2. To entice liquidity providers and users to actively engage with the protocol with the understanding that at a later point in time there will be a ‘snapshot’ of the active accounts and a resultant airdrop in which the protocols native token will launch, and all of the users up until this point will be eligible to receive free money. DYDX is an example of this strategy. Neither of these strategies have been wildly successful in their own right, however the first strategy has been successful insofar as the original LP tokens that were released did maintain much of their value, due to the first-mover nature of many of the protocols (Compound for example and the COMP token), and as a result significant amounts of liquidity have remained in the protocols. Suffice is to say, there is plenty of room for innovation in playing with liquidity incentives as a method of attracting long-term and sustainable liquidity providers into a protocol or ecosystem. ## How Early On Is The ‘Liquidity’ Game? On a historical note, it was these types of yield farming strategies that jump started DeFi summer in 2020, and from which launched the bull market of 2020-2022. Until 2020, there was minimal liquidity inside of crypto - yet from that time, liquidity has grown significantly: As of December 2, 2018: ![](@site/static/img/bootcamp/mod-em-3.6.2.png) As of November 2022: ![](@site/static/img/bootcamp/mod-em-3.6.3.png) In terms of ecosystems breakdown, Ethereum has led the way, followed by Binance Smart Chain (BSC): ![](@site/static/img/bootcamp/mod-em-3.6.4.png) ## Open Questions For Addressing Liquidity In The Future The rapid collapse of FTX prompted a direct withdrawal of liquidity from the Solana ecosystem, dropping it from around 3.9 billion TVL at its peak, to less than 250mm TVL by December of 2022. Meanwhile, in spite of the contagion prompted from FTX, Ethereum’s liquidity dropped by barely 15% in the same timeframe. This begs a number of important questions when looking at liquidity in an ecosystem: * To what extent does institutional capital, centralized exchanges, and custodial on-ramps play a role in improving the TVL of an ecosystem? * To what extent do original, innovative products attract sticky liquidity? * What additional incentives can be coordinated on a protocol wide level so as to attract liquidity in the ecosystem over a long-period of time? * Can an ecosystem survive without liquidity? Is composability possible without liquidity?
Etherscan will Launch on Aurora COMMUNITY September 1, 2021 Aurora, an Ethereum scaling solution that allows projects built on Ethereum to utilise the cutting-edge technology of NEAR has teamed up with Etherscan, the leading block explorer for Ethereum to allow developers to use the same familiar tool. While Aurora utilises NEAR as its foundation, it has always envisioned a future in which projects can move seamlessly between blockchains to suit their needs. The partnership with Etherscan is a significant step in that direction. “Etherscan provides the familiar interface of the explorer,” says Alex Shevchenko, the CEO of Aurora Labs. “Users and devs won’t need to educate themselves on how to use the Aurora block explorer, instead they would get the familiar tool.” While Etherscan is most commonly known as a block explorer for Ethereum, it’s capable of so much more: from statistics, and token transfers and listing; to smart contract source code verification and ability to issue read and write calls directly from the UI. Making those tools available to a greater number of devs is key to Aurora’s mission. “Aurora is always focused on making the experience of devs and users as seamless as possible,” says Shevchenko. The explosive growth of DeFi and NFTs frequently causes surges in Ethereum gas prices––a problem that economically limits the participation of many users, and prevents dApp developers from scaling their businesses to their full potential. Helping developers to grow their business is a mission Etherscan shares with Aurora. “We are happy to utilize our experience in building block explorer solutions into supporting Aurora, and extend our own vision of providing equitable access to blockchain data”, says Matthew Tan, Founder & CEO of Etherscan. While today marks the start of the integration process, the product will be available later in the year. Stay tuned for updates on the release and other upcoming ones from the Aurora team. 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. Join NEAR’s community: Telegram: https://t.me/cryptonear Discord: https://discord.com/invite/UY9Xf2k Twitter: @NEAR_Blockchain & @NEARProtocol About Aurora Aurora is an EVM built on the NEAR Protocol, delivering a turn-key solution for developers to operate their apps on an Ethereum-compatible, high-throughput, scalable and future-safe platform, with low transaction costs for their users.
Škoda Ventures into NFTs with NEAR to Create the Škodaverse India NEAR FOUNDATION June 20, 2023 Škoda India, in collaboration with NEAR Protocol, announces its foray into the world of NFTs and blockchain technology with Škodaverse India. This new platform forms a part of the global Škodaverse initiative and will bringa fresh wave of digital innovation to Škoda automobile fans in India. Škoda, one of Europe’s biggest car manufacturers headquartered in the Czech Republic, is quickly becoming one of the most forward-thinking industry brands in Web3 and the metaverse. Late last year, the company announced its global Škodaverse initiative, integrating virtual test drives and NFTs into an immersive environment. And now the Škodaverse is coming to the Indian market, powered by the NEAR Protocol, that will enable Škoda fans to buy, trade, and engage with NFTs in Web3. It’s a crucial step in the brand’s journey towards building a tight-knit community of Škoda loyalists, offering a space for fans to connect, co-create, and establish long-term relationships with the brand. Steering Škoda fans towards NFTs with NEAR Mr. Christian Cahn von Seelen – Executive Director of Sales, Marketing, and Digital, Škoda at Auto Volkswagen India – expressed excitement at the unveiling of the Škodaverse India NFT platform. He envisions it as a dynamic hub for connection and creativity, exemplifying Škoda’s commitment to its customers and fans in India. The Škodaverse India will offer unique and immersive experiences to a rapidly growing market. “Škodaverse India signifies the brand’s leap into uncharted digital territory,” said von Seelen. It’s not just about creating extraordinary digital assets, it’s about forging deep connections with a community that shares an unwavering passion for the brand and its initiatives in India. It also showcases our commitment to sustainability and innovation, through leveraging carbon-neutral blockchain technology that enables secure, transparent, and decentralized transactions.” Škodaverse India is designing its metaverse platform to be exciting and engaging for Škoda enthusiasts of all demographics, whether they’re familiar with blockchain technology or not. Whether it’s an image, video, sound, or ticket, each NFT collection released on the Škodaverse India platform will be curated to create memorable driving experiences The first NFT collection, honoring sustainability, will be created on NEAR Protocol. As a South Pole-certified, carbon-neutral blockchain, NEAR’s eco-first philosophy aligns seamlessly with Škoda India’s sustainability efforts. Driving Škoda India’s Web3 Strategy into the future As part of the brand’s intensified Web3 strategy, Škoda Auto India is collaborating with Antier, a leading blockchain consulting firm, to foster the creation and minting of innovative NFTs. Each NFT collection released on the Škodaverse India platform will be thoughtfully curated to represent memorable driving experiences. These unique collectibles will unlock exclusive experiences, strengthening the bond between Škodaverse and its community of users. The Škodaverse India platform also ensures users stay updated with the latest in the creation and sale of NFTs. Users can sign in, create, and maintain their profiles, and monitor for updates via Škodaverse India’s Discord, Telegram, and Twitter. With the launch of Škodaverse India, Škoda Auto India embraces blockchain technology, signaling a significant move towards Web3 applications. Powered by NEAR Protocol, Škodaverse India will offer engaging, community-building experiences, further solidifying Škoda’s position as a forward-thinking automobile brand in Web3 and the metaverse.
Post Mortem: NEAR Discord Security Incident NEAR FOUNDATION May 22, 2023 This is a post mortem report regarding the recent security incident that occurred on the NEAR Discord server. The purpose of this report is to provide analysis of the incident, identify the root cause, outline the impact, and propose actions to potentially limit similar incidents in the future. Summary: On Wednesday, May 17th, the NEAR Discord server experienced a security incident. This resulted in unauthorized access to a singular moderator account. The incident occurred due to a successful spear-phishing attempt on one of our server’s moderators. The attacker used their access to promote a fraudulent airdrop campaign, with the intent to deceive users and drain their wallets. Root Cause Analysis: The investigation revealed the following root causes: Successful spear-phishing: One of the NEAR Discord moderators was targeted by a phishing campaign, leading to the theft of their Discord credentials. Lack of Two-Factor Authentication (2FA): The absence of 2FA for user accounts provided an opportunity for attackers to gain unauthorized access. Impact: The security incident had the following impacts: Unauthorized Access: The attacker gained unauthorized access to our Discord server. Removal of Moderators: The attacker used their access to ban existing moderators that tried to intervene. Content Deletion: Unauthorized deletion of two Discord channels. Disruption of Services: During the incident investigation and subsequent remediation, there was a temporary disruption in server availability and functionality. Invite links were invalidated during the process and are being rebuilt. Actions Taken: In response to the security incident, we have taken the following actions: Incident Response and Investigation: Immediately upon detection, our security team initiated an incident response plan. They conducted a thorough investigation to determine the extent of the incidents and identify the source of the entry point. Timeline of events: At 7:47 PM UTC, a malicious webhook was installed by a compromised Discord Moderator account. At 10:47 PM UTC, the attacker — using the compromised moderator account — began posting in Discord. From there, other Discord members attempting to mitigate the attack were subsequently banned. The attacker used their access to promote a fraudulent airdrop campaign, with the intent to deceive users and drain their wallets. 10:57 PM UTC, The Pagoda Security team was notified. Triage began and we identified the problem account and began resetting permission immediately. 11:13 PM UTC, all attackers had been removed and all threats neutralized. User Notification and Password Reset: Affected users have been notified about the incident, and a mandatory password reset has been implemented to ensure the security of their accounts. Required 2FA for Moderators: Moderators are now required to use 2FA in the NEAR Discord. Preventive Measures: To prevent similar incidents, the following actions will be taken: measures: Regular Security Audits: Implement regular security audits of our Discord server to identify and address vulnerabilities promptly. Ongoing Monitoring and Incident Response Improvement: Enhance our monitoring capabilities to detect any suspicious activities and continually improve our incident response procedures. Security Education and Awareness: Continue to educate our team on the importance of strong passwords, multi-factor authentication, and general security best practices. Conclusion: The security incident on the NEAR Discord server served as a crucial reminder of the significance of having robust security measures in place. Prompt action to minimize the impact was taken and the team have since implemented preventive measures to avoid similar incidents moving forward. Ensuring the security and privacy of our users and their data continues to be our utmost priority.
```js import { Wallet } from './near-wallet'; const DAO_FACTORY_CONTRACT_ADDRESS = "sputnik-dao.near"; const wallet = new Wallet({ createAccessKeyFor: DAO_FACTORY_CONTRACT_ADDRESS }); await wallet.callMethod({ method: 'create', args: { name: "primitives", args: btoa({ config: { name: "Primitives", purpose: "Building primitives on NEAR", metadata: "" }, policy: ["bob.near"] }), }, contractId: DAO_FACTORY_CONTRACT_ADDRESS, gas: 300000000000000, deposit: 6000000000000000000000000 }); ``` :::note The full list of roles and permissions you can find [here](https://github.com/near-daos/sputnik-dao-contract#roles-and-permissions). ::: _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
NEAR and The Graph Partnership COMMUNITY February 18, 2021 NEAR and The Graph partner to bring Indexing and Querying to the NEAR blockchain Developers building applications on NEAR will be able to build subgraphs (open APIs), and index blockchain data more efficiently. The Graph is excited to announce an official integration plan with NEAR, expanding the decentralized indexing network of NEAR’s infrastructure. The Graph currently supports Ethereum and IPFS. This partnership will support developers to build powerful applications on NEAR using The Graph, and enable developers from all supported ecosystems to explore querying of subgraphs (open APIs) for data across different blockchains. Subgraphs exist for applications like Uniswap, Synthetix, AAVE, Gnosis, Balancer, Foundation, and many others. The Graph is the indexing and query layer of the decentralized web. Indexing is a way of structuring and categorizing data so it can be easily searched for and queried by users. Developers build and publish open APIs, called subgraphs, that applications can query using GraphQL. The Graph solves the problem of centralized data indexing by building a decentralized protocol for indexing blockchain data, users no longer have to trust teams to operate servers and developers can deploy to reliable public infrastructure they don’t have to manage. Growing the Open Web with The Graph NEAR is a decentralized application platform 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 open technologies in their hands. It is built atop a public proof-of-stake blockchain, which combines the scalability that is needed to drive the Open Web with the common-sense usability that is needed to make it successful. “NEAR is excited to work with The Graph ecosystem. The Graph Protocol provides essential infrastructure for developers to build and query required representations of blockchain data. Tools like The Graph empower NEAR developers to build decentralized applications faster, which will attract more builders and users to the Open Web,” said Illia Polosukhin, NEAR Co-Founder. Eva Beylin, Director of The Graph Foundation added, “We’re excited about NEAR being one of the first multi-blockchain expansions for The Graph, enabling developers to build more interoperable dapps within the Web3 ecosystem.” The partnership will empower NEAR’s ecosystem builders to build with a truly decentralized indexing layer and allow them to collaborate with The Graph’s network of developers. Furthermore, it provides a solution to composability issues in blockchain by creating decentralized APIs that serve data from a number of different chains. The Graph aims to grow overall Web3 development and help developers build interoperable applications. The Integration with NEAR will accelerate both projects’ goal of ‘Opening the Web’. About The Graph The Graph is a protocol and decentralized network for querying and indexing blockchain data. At The Graph, our mission is to make serverless applications possible and to make building on Web3 accessible to anyone. Before NEAR, The Graph was integrated with many applications on Ethereum and IPFS that use subgraphs for retrieving data. To date, over 8,000 subgraphs have been deployed by over 10,000 active developers for applications, such as Uniswap, Synthetix, Aragon, Gnosis, Balancer, Livepeer, DAOstack, AAVE, Decentraland, and many others. The Graph Foundation invites developers, researchers and community members alike to apply to The Graph Grants Program. Anyone contributing to supported blockchains can apply for a grant for Protocol Infrastructure, Tooling, Decentralized Applications or Community Building. The Foundation is aiming to distribute up to ~25M GRT in grants in The Graph ecosystem in 2021.The Graph would also love to welcome you to be Indexers, Curators and/or Delegators on The Graph’s mainnet. Join The Graph community by introducing yourself in The Graph Discord for technical discussions, join The Graph’s Telegram chat, or follow The Graph on Twitter! The Graph’s developers and members of the community are always eager to chat with you, and The Graph ecosystem has a growing community of developers who support each other. About NEAR NEAR exists to enable community-driven innovation to benefit people around the world. NEAR is a decentralized application platform that secures high value assets like money and identity with the performance necessary to make them useful for everyday people, putting the power of Open Finance and the Open Web in their hands. NEAR’s unique account model allows developers to build secure apps that consumers can actually use similarly to today’s web apps, something which requires multiple second-layer add-ons on other blockchains. Technically speaking, NEAR Protocol is a brand new, public, proof-of-stake blockchain which is built using a novel consensus approach called Doomslug. NEAR Protocol uses a new sharding mechanism called Nightshade which splits the network into multiple pieces so that the computation is done in parallel. Parallelism radically increases throughput and allows the network to scale up as the number of nodes on it increases. With NEAR, there isn’t a theoretical limit on the network’s capacity. NEAR invites you to join us on the journey to make blockchain accessible to everyday people who are excited for the future of the Open Web. If you’re a developer, be sure to sign up for our developer program and join the conversation in our Discord chat. You can also keep up to date on future releases, announcements, and event invitations by subscribing to our newsletter or following us on our Twitter for the latest news on NEAR.
--- id: storage-staking title: Storage Staking sidebar_label: Storage Staking --- > When you deploy a smart contract to NEAR, you pay for the storage that this contract requires using a mechanism called storage staking. > > In storage staking (sometimes called _state_ staking), the account that owns a smart contract must stake (or lock) tokens according to the amount of data stored in that smart contract, effectively reducing the balance of the contract's account. <blockquote className="info"> <strong>Coming from Ethereum?</strong><br /><br /> If you’re familiar with Ethereum’s pricing model, you may know that, like NEAR, the protocol charges a fee (called "gas") for each transaction. Unlike NEAR, Ethereum's gas fee accounts for the amount of data stored via that transaction. This essentially means that anyone can pay once to store permanent data on-chain. This is a poor economic design for at least two reasons: 1. The people running the network (miners, in the case of Ethereum 1) are not appropriately incentivized to store large amounts of data, since a gas fee far charged in the distant past can increase storage costs forever, and 2. The users of a smart contract are charged for the data they send to store in it, rather than charging the owner of the smart contract. </blockquote> ## How does NEAR's design align incentives? Storage-staked tokens are unavailable for other uses, such as validation staking. This increases the yield that validators will receive. Learn more in [the economics whitepaper](https://pages.near.org/papers/economics-in-sharded-blockchain/). ## When do tokens get staked? On each incoming transaction that adds data. Let's walk through an example: 1. You launch [a guest book app](https://examples.near.org/guest-book), deploying your app's smart contract to the account `example.near` 2. Visitors to your app can add messages to the guest book. This means your users will, [by default](/concepts/protocol/gas#what-about-prepaid-gas), pay a small gas fee to send their message to your contract. 3. When such a call comes in, NEAR will check that `example.near` has a large enough balance that it can stake an amount to cover the new storage needs. If it does not, the transaction will fail. ## The "million cheap data additions" attack Note that this can create an attack surface. To continue the example above, if sending data to your guest book costs users close to nothing while costing the contract owner significantly more, then a malicious user can exploit the imbalance to make maintaining the contract prohibitively expensive. Take care, then, when designing your smart contracts to ensure that such attacks cost potential attackers more than it would be worth. ## btw, you can remove data to unstake some tokens People familiar with the "immutable data" narrative about blockchains find this surprising. While it's true that an _indexing node_ will keep all data forever, _validating nodes_ (that is, the nodes run by most validators in the network) do not. Smart contracts can provide ways to delete data, and this data will be purged from most nodes in the network within a few [epochs](../basics/epoch.md). Note that a call to your smart contract to remove data has an associated gas fee. Given NEAR's gas limit, this creates an upper limit on how much data can be deleted in a single transaction. ## How much does it cost? Storage staking is priced in an amount set by the network, which is set to **1E19 yoctoNEAR per byte**, or **100kb per NEAR token (Ⓝ)**. [^1] [^2] NEAR's JSON RPC API provides [a way to query this initial setting](/api/rpc/setup#genesis-config) as well as a [a way to query the live config / recent blocks](/api/rpc/setup#protocol-config). ## Example cost breakdown Let's walk through an example. A [non-fungible token](https://github.com/near/NEPs/pull/4) is unique, which means each token has its own ID. The contract must store a mapping from token IDs to owners' account ID. If such an NFT is used to track **1 million** tokens, how much storage will be required for the token-ID-to-owner mapping? And how many tokens will need to be staked for that storage? Let's calculate the storage needs when using a `PersistentMap` that stores data as UTF-8 strings. Here's our `PersistentMap`: ```ts type AccountId = string; type TokenId = u64; const tokenToOwner = new PersistentMap<TokenId, AccountId>("t2o"); ``` Behind the scenes, all data stored on the NEAR blockchain is saved in a key-value database. That `'t2o'` variable that's passed to `PersistentMap` helps it keep track of all its values. If your account `example.near` owns token with ID `0`, then at the time of writing, here's the data that would get saved to the key-value database: - key: `t2o::0` - value: `example.near` So for 1 million tokens, here are all the things we need to add up and multiply by 1 million: 1. The prefix, `t2o`, will be serialized as three bytes in UTF-8, and the two colons will add another two. That's 5 bytes. 2. For an implementation where `TokenId` auto-increments, the values will be between `0` and `999999`, which makes the average length 5 bytes. 3. Let's assume well-formed NEAR `AccountId`s, and let's guess that NEAR Account IDs follow the approximate pattern of domain names, which [average about 10 characters](https://www.gaebler.com/Domain-Length-Research.htm), plus a top-level name like `.near`. So a reasonable average to expect might be about 15 characters; let's keep our estimate pessimistic and say 25. This will equal 25 bytes, since NEAR account IDs must use characters from the ASCII set. So: 1_000_000 * (5 + 5 + 25) 35 million bytes. 350 times 100Kib, meaning Ⓝ350. To do the exact math: Multiplying by 1e19 yoctoNEAR per byte, we find that the `tokenToOwner` mapping with 35m bytes will require staking 3.5e26 yoctoNEAR, or Ⓝ350 Note that you can get this down to Ⓝ330 just by changing the prefix from `t2o` to a single character. Or get rid of it entirely! You can have a zero-length prefix on one `PersistentVector` in your smart contract. If you did that with this one, you could get it down to Ⓝ250. ## Calculate costs for your own contract Doing manual byte math as shown above is difficult and error-prone. Good news: you don't have to! You can test the storage used using the [SDK environment](../../2.build/2.smart-contracts/anatomy/environment.md) and checking `env.storage_usage()` ## Other ways to keep costs down Storing data on-chain isn't cheap for the people running the network, and NEAR passes on this cost to developers. So, how do you, as a developer, keep your costs down? There are two popular approaches: 1. Use a binary serialization format, rather than JSON 2. Store data off-chain ### Use a binary serialization format, rather than JSON The core NEAR team maintains a library called [borsh](https://borsh.io/), which is used automatically when you use `near-sdk-rs`. Someday, it will probably also be used by `near-sdk-js`. Imagine that you want to store an array like `[0, 1, 2, 3]`. You could serialize it as a string and store it as UTF-8 bytes. This is what `near-sdk-js` does today. Cutting out spaces, you end up using 9 bytes. Using borsh, this same array gets saved as 8 bytes: \u0004\u0000\u0000\u0000\u0000\u0001\u0002\u0003 At first glance, saving 1 byte might not seem significant. But let's look closer. The first four bytes here, `\u0004\u0000\u0000\u0000`, tell the serializer that this is a `u32` array of length `4` using little-endian encoding. The rest of the bytes are the literal numbers of the array – `\u0000\u0001\u0002\u0003`. As you serialize more elements, each will add one byte to the data structure. With JSON, each new element requires adding two bytes, to represent both another comma and the number. In general, Borsh is faster, uses less storage, and costs less gas. Use it if you can. ### Store data off-chain This is especially important if you are storing user-generated data! Let's use this [Guest Book](https://github.com/near-examples/guest-book-examples) as an example. As implemented today, visitors to the app can sign in with NEAR and leave a message. Their message is stored on-chain. Imagine this app got very popular, and that visitors started leaving unexpectedly long messages. The contract owner might run out of funding for storage very quickly! A better strategy could be to store data off-chain. If you want to keep the app decentralized, a popular off-chain data storage solution is [IPFS](https://ipfs.io/). With this, you can represent any set of data with a predictable content address such as: QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG Such a content address could represent a JSON structure or an image or any other type of data. Where does this data get physically stored? You could use [Filecoin](https://filecoin.io/) or run your own IPFS server to pin your app's data. With this approach, each record you add to your contract will be a predictable size. ## Summary NEAR's structure incentivizes network operators while giving flexibility and predictability to contract developers. Managing storage is an important aspect of smart contract design, and NEAR's libraries make it easy to figure out how much storage will cost for your application. :::tip Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"><h8>Ask it on StackOverflow!</h8></a> ::: ## Footnotes [^1]: [Storage staking price](https://gov.near.org/t/storage-staking-price/399) [^2]: [Lower storage cost 10x](https://github.com/near/nearcore/pull/3881)
Evolving NEAR Foundation’s Funding Strategy NEAR FOUNDATION November 21, 2022 NEAR Foundation is publishing a series of blogs on the state of funding, including updates from the Grants Team and an upcoming Transparency Report for Q3. This is part of our continued commitment to transparency, as well as more frequent and open communication with the NEAR community. NEAR Foundation’s role is to support the NEAR ecosystem and community. This means that the Foundation can deploy capital to help promote growth, alongside its efforts to grow awareness of NEAR and onboard a billion users to Web3. Among Layer 1 protocols, NEAR is in an excellent position to thrive despite the very difficult market conditions. Our 5+ years of runway will help the NEAR ecosystem weather the bear market, which is likely to last for some time. The Treasury Team’s careful spending and responsible Treasury management has equipped the ecosystem to emerge from this crypto winter with NEAR as the protocol of choice for people and projects building on Web3. While the market has created a new reality for the entire Web3 ecosystem, NEAR sees this as a moment of great opportunity and a time to stick to our convictions. We’ve outlined the Foundation’s new strategy around facilitating Web2.5 and making NEAR the de facto bridge from Web2 to Web3. Staying true to NEAR’s decentralized vision, the NEAR Digital Collective (NDC) was recently launched and led by the Governance Working Group (GWG). We’ve also delegated some decision-making to the community through grassroots DAOs: the DeveloperDAO, MarketingDAO, and CreativesDAO. NEAR Foundation has provided capital to many projects over the last two-plus years, with clear milestones and goals designed to maximize potential value added to the ecosystem. Grants have been a major part of that capital allocation strategy since the program was first announced in 2021. Although the Foundation has a substantial amount of runway to support the ecosystem for several years to come, we need to ensure that we are stewarding NEAR’s Treasury as responsibly and sustainably as possible. With these long-term views in mind, NEAR Foundation is looking critically at all of its capital allocation in the last few years in order to determine what has had the most impact and where we should consider revising our approach. We will also be heavily scrutinizing upcoming capital deployments. The Foundation must focus on supporting the highest quality projects with the most potential and alignment with our vision for NEAR. What does this mean for the community? To make NEAR the leading Web2.5 bridge, NEAR Foundation will back those projects and initiatives that help best grow and support the ecosystem for years to come. This also means that some tough decisions are coming about where not to deploy funding. However, in the areas where funding or granting is pared back, the Foundation will do its absolute best to support those affected by upcoming funding decisions. We will make our best efforts to help these community members find new homes with other ecosystem projects. NEAR Foundation will also ensure that we are as transparent as possible about the new Funding strategy as it rolls out. The Foundation will communicate as often and as much as possible, and encourage the community to continue giving feedback so we can iterate more quickly as we build the NEAR Ecosystem together. NEAR Foundation has already made significant steps to make NEAR’s funding more transparent. Through the NEAR Digital Collective (NDC), we are empowering the community to evolve governance and coordinate together through the ecosystem DAOs. (Read more and get involved at the NDC gov.nearpages.wpengine.com page.) In September, NEAR formed a working group to set standards for this on-chain style of self-governance. The Foundation has been calling this the “bottom-up” approach to supporting the community, encouraging grassroots coordination and decentralized decision-making that works in parallel with the Foundation’s more “top-down” stewardship and funding strategy. The Foundation also started publishing a regular Transparency Report in the spirit of accountability to the ecosystem. The first Transparency report, which came out just before NEARCON, was an important start—but we want to make it even better for the community. The next report will be coming out in a couple of weeks and will include more granularity where possible. You can also check out a recent update from the NEAR Grants team titled “Funding Beyond Grants”. It’s also important for the community to understand that while transparency and open communication are an essential part of NEAR Foundation’s commitment to all of you, we cannot be entirely transparent about every funding decision or commercial agreement we make. This is primarily due to legal restrictions that can be imposed on NEAR Foundation in its dealings with third parties. The Foundation will share as much as possible about the exciting collaborations being made in the months ahead. NEAR Foundation highly encourages people to get involved with the NEAR community. By becoming more participatory, community members can take ownership in the new bottom-up approach to decision making we are helping foster across the ecosystem. NEAR Foundation is keeping an eye on the long term for the entire NEAR ecosystem. By being fiscally responsible and deploying capital in a sustainable way, the Foundation can ensure that NEAR emerges from this bear market stronger than ever, and well positioned to help builders keep building the future of Web3.
--- id: overview title: Quick Overview --- Lets start with a quick overview of the different elements that compose the NEAR blockchain. --- ## Accounts NEAR uses human-readable account names such as `alice.near` or `bob.near` instead of a public hash such as`0x71C7656EC7ab88b098defB751B7401B5f6d8976F`. These accounts also have the permission to create subaccounts such as `nft.alice.near` or `example2.bob.near`. It's important to know that only the root account can create the subaccount. So only `alice.near` can create `nft.alice.near` and only `nft.alice.near` can create `example.nft.alice.near`. Note that `alice.near` ***does not*** have permission to create `example.nft.alice.near`. Only the direct parent account has permission to create a subaccount. :::tip For more information see the **[accounts section](/concepts/protocol/account-model)**. ::: <hr className="subsection" /> ## Keys On most blockchains, there is one [public/private key pair](https://en.wikipedia.org/wiki/Public-key_cryptography) per account. On NEAR, each account can have many key pairs associated with them which we call "Access Keys". There are two types of "Access Keys": - [Full Access](/concepts/protocol/access-keys#full-access-keys) _(Grants full control to the account)_ - [Function Call](/concepts/protocol/access-keys#function-call-keys) _(Allows for only non-monetary transaction signing)_ Full access keys allow for full control of the account. You can send funds, create sub-accounts, delete the account, and more. Function call keys only allow for calling certain methods on a specific smart contract that **do not** allow the transferring of funds. These keys can be used by dApp developers to allow users to sign simple transactions that mutate state on the blockchain without having to constantly re-direct to the user's wallet to prompt for authorization. They can be widely or narrowly scoped depending on the use case. :::tip For more information see the **[access keys section](/concepts/protocol/access-keys)**. ::: <hr className="subsection" /> ### Contracts Every NEAR account can hold **a** smart contract, which is a small piece of logic embedded directly in the account. Smart contracts in NEAR can be developed using either Javascript or [Rust](https://www.rust-lang.org/). Smart contracts that have been deployed can be [updated](/sdk/rust/building/prototyping) at any time but not removed. This is where [sub-accounts](#concepts/protocol/account-model#subaccounts) can come in handy. NEAR allows users to organize and create a hierarchy for their accounts. As an example, benji could have the root account `benji.near`. He then stores all his NFT contracts as sub-accounts of `nft.benji.near`. For example, he worked on a cool lazy minting contract deployed to `lazy.nft.benji.near`. This not only allows for better organization but it allows developers to easily delete and re-create accounts in order to clear state. :::tip For more information see a guide on **[deploying contracts](/sdk/rust/promises/deploy-contract)**. ::: <hr className="subsection" /> ### Storage Any information that is stored on NEAR is accounted for using a mechanism called [storage staking](/concepts/storage/storage-staking). In short, an account must maintain a certain balance that is locked in order to cover the cost of storage. If that storage is released, the funds become available once again. This is why named account IDs on NEAR cost an initial deposit to create. If you attempt to store state on-chain without having the necessary balance in your account to cover the cost, an error will be thrown which will tell you to add more NEAR to your account. :::tip For more information on storage staking, see the **[storage staking section](/concepts/storage/storage-staking)**. :::
```js await wallet.callMethod({ method: 'storage_deposit', args: { account_id: 'alice.near', }, contractId: TOKEN_CONTRACT_ADDRESS, deposit: 1250000000000000000000 }); ``` _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
Shred Spots and NEAR Foundation: Kick-Flipping Into the Future of Social NFTs NEAR FOUNDATION July 12, 2023 Action sports such as skateboarding and snowboarding are gaining momentum, especially among Gen Z, and are quickly outpacing traditional sports. Today, Gen Z is one of the biggest growth populations in skateboarding, highlighting the relevance of action sports and their surrounding community to the TikTok generation. This is where NEAR Foundation’s newest partner, Shred Spots, steps in. Shred Spots is a unique social platform specifically designed for active participants and community members in the street sports realm. Despite impressive growth, a dedicated, verticalized social platform that caters to these Gen Z skaters has been noticeably absent – until now. In a convergence of skating and the open web, Shred Spots has partnered with NEAR Foundation to create a unique, interactive experience for street sports enthusiasts. This fusion will empower skaters to create, compete, and immortalize their achievements via innovative NFT technology within the action sports metaverse. Shred Spots: grinding in popularity among the open web generation Shred Spots has established itself as a go-to app for street skaters and has formed partnerships with significant street sports brands like Red Bull, GoPro, and XGames. It’s a community-driven digital platform that allows its users to track their achievements, compete with their peers, and express themselves creatively. A unique feature of Shred Spots is its live map, updated by the community, where users can find and add sports locations. They can search based on the type of obstacle, difficulty level, or even the likelihood of getting “busted.” These attributes have led Wired to proclaim Shred Spots as “the only app street skaters will ever need.” In a recent interview, Shred Spots founder, Lev Filimonov, also emphasized the app’s unique ability to combine skaters’ experience with AR and NFTs, fostering a dynamic interaction with the history and culture of skate spots worldwide while allowing users to monetize their art and achievements. Shred Spots’ popularity is a testament to its success. With its growth primarily driven by word-of-mouth within the street sports community, it has rapidly emerged as an essential tool for skaters worldwide. This organic growth underscores the platform’s ability to resonate with its audience and fulfill a clear need with Web3 and NEAR. Making every trick memorable with Shred Spots x NEAR The partnership between NEAR and Shred Spots brings an innovative twist to the realm of action sports, introducing the transformative potential of Web3 technologies to this vibrant community. Shred Spots plan to leverage NEAR’s blockchain to generate unique, collectible NFTs from skating highlights, enriching the overall user experience. In this exciting new chapter, every trick recorded and uploaded onto Shred Spots could be minted into an NFT within the street art metaverse. This integration not only adds a rewarding layer to the platform but also deepens the connection between skaters and the fascinating world of blockchain. Growth within the Shred Spots community has been largely organic, a testament to its widespread acceptance within the skating community. This partnership with NEAR amplifies the platform’s user experience through the integration of NFT technology, extending the reach of Web3 into the action sports world. The alignment of Shred Spots and NEAR’s vision aids in democratizing access to Web3 technologies, introducing an entirely new user base to the possibilities of blockchain. This marks a pivotal step in broadening the horizons of the street sports community, linking their passions with the power of Web3 and digital ownership. The collaboration between NEAR and Shred Spots epitomizes how the open web can enrich user experiences in growing niche communities like skateboarding and action sports. It also illustrates the future confluence of the open web, sports, and real-world achievements. And it’s bringing the blockchain to a whole new generation of action sports enthusiasts.
--- title: Open Source description: Overview on how NEAR BOS empowers open source projects sidebar_position: 11 --- # Decentralization, Open-Source, and the Blockchain Operating System Decentralization and Open-Source development are cornerstones of a free and open web. They promote transparency and collaboration and reduce the power of people who seek to control the web for their own profit or power. Decentralized, open-source projects have been essential in building the Internet by encouraging autonomy, innovation, and community-driven development. They’re also at the core of the Blockchain Operating System (BOS). The World Wide Web has become more and more centralized over time as our online experiences and identities have become increasingly controlled by a small number of large corporations. Unfortunately, this centralization has increased the power and profits of those very few people and organizations. As more people understand this problem, there are growing calls and efforts to return to the decentralized principles that built the Internet in the first place, with a particular focus on taking back control of our information and ownership of our digital lives. The BOS is one of these projects. ## Decentralization _The dispersion or distribution of power_ At its core, decentralization aims to create a more democratic, participatory, and efficient system by giving individuals and communities greater control over their lives. It encourages the participation of everyone in decision-making processes. While this benefits all of us, it can be particularly helpful for marginalized and underrepresented groups who have had less power in the past. Decentralized internet systems ensure network resilience by distributing their resources across multiple nodes, ensuring no single point of failure exists. This allows information to flow freely, making it more difficult for governments or organizations to dominate and control. Decentralization also helps counter the power of tech giants, promoting a more equitable distribution of wealth and influence across the internet. ## Open Source _Having the source code freely available for inspection, modification, and redistribution._ Open Source contributes to the democratization of technology as it fosters collaboration and innovation among individuals worldwide. As source code is accessible to the public, it allows people to understand how systems work, identify vulnerabilities, and suggest improvements to security and reliability over time. This transparency helps build trust as the Open Source development process lets people see how decisions are made and verify software integrity. Having this information freely accessible empowers individuals, regardless of financial resources, to access powerful knowledge and tools they might not otherwise have the privilege of utilizing. This provides the opportunity for a more diverse community of contributors and ultimately promotes a more open and inclusive world. ## The BOS: a Decentralized, Open Source Platform for All The Blockchain Operating System is built from the ground up as a decentralized operating system powered by Open Source software. Blockchain technology ensures that decentralization is achieved as every node in the network can validate the authenticity of the code and stored data. While this decentralization is true of all blockchains, the BOS takes this further by making all aspects of the applications that run on it both decentralized and Open Source. On the BOS, all code is stored on the NEAR Blockchain and can be reviewed by others. Any node that tampers with the code or data is flagged and rejected. The BOS allows developers of all backgrounds to start building quickly with composable apps and the ability to code in JavaScript. Its focus on simplicity, UX, and discoverability benefits developers, enterprises, and users alike and helps bring us much closer to a decentralized digital future where users own and control their data.
--- id: intro title: QueryAPI Overview sidebar_label: Introduction --- Near QueryAPI is a fully managed solution to build indexer functions, extract on-chain data, store it in a database, and be able to query it using GraphQL endpoints. ## Indexing complexity Blockchain Indexers are known to be challenging to create, maintain, and operate. You have to focus on the business logic of your indexer, while you also have to take care of everything else around it. A dedicated team member could be needed to deal with all these challenges. Common indexing challenges include: #### Creation - Design Database Schema and provision it with correct configurations for security, data retention, and performance. - Write and test indexer code that interacts with the database - Deploy Indexer to a Cloud provider. Ensure network permissions firewalls, PCs, or other network-related settings are setup correctly. - Create an API endpoint to retrieve data from your database for your fronted applications #### Maintenance - Monitor the performance of your database and scale it as needed - Manage permissions and database access with changing requirements #### Operation - Re-index data due to issues and updates. Ensuring that production environments don't get disrupted. - Perform database schema migrations - Scale the API as your application grows - Keep up with all the underlying blockchain nodes and upgrades ## QueryAPI As you can see, running indexers is a complex and comprehensive set of processes and Near QueryAPI tries to cover most (or all) of these needs, offering an open-source solution for creating, managing, and exploring indexers. ### NEAR Component QueryAPI has a [`QueryApi.App` NEAR widget](https://near.org/#/dataplatform.near/widget/QueryApi.App), hosted under the `dataplatform.near` account. With this component, you can see all the public indexers currently available on the Near blockchain. If you would like to create a new indexer, simply click [**Create New Indexer**](https://near.org/#/dataplatform.near/widget/QueryApi.App/?view=create-new-indexer). ![QueryAPI Dashboard](/docs/assets/QAPIScreen.png) ### Indexers stored on-chain QueryAPI stores all the indexer logic and schemas used to provision the databases on-chain. Whenever you interact with the QueryAPI NEAR component, in the background it's making an RPC query to [`queryapi.dataplatform.near`](https://stats.gallery/mainnet/queryapi.dataplatform.near/contract?t=week), where a smart contract stores all of your indexer logic as well as your schemas. For example, if you select the _feed-indexer_ and click on [**View indexer**](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=dataplatform.near/feed-indexer) you'll see all the details about an indexer that powers the [near.org](https://near.org)'s main posts feed. You're free to review the JavaScript code of the indexer function, or check the SQL that defines the database schema. ## Known limitations - Currently under closed beta testing. - Only supports JavaScript indexers. (we plan to support Rust in the future) - It always takes the latest `@near-lake/primitives` library. - It doesn't support schema migrations. - If you have an indexer whose schema needs to change, you may need to create a new indexer and do a historical backfill on that new indexer again. - There's no way to stop or restart your indexer, truncating all tables. - Historical backfill works in parallel to the real-time indexing. - Historical processing won't happen in order. (it will happen at the same time as top of network) - Keep that in mind to ensure you don't have unintended side effects. :::tip Join the Beta If you want to join the closed beta, please [fill out this form](http://bit.ly/near-queryapi-beta) for access. ::: :::info Pricing Pagoda currently doesn't charge for storing your indexer code and data or running the indexer, but we will introduce this soon. :::
NFTs on NEAR: Why NFT? COMMUNITY May 23, 2022 Non-fungible tokens, or NFTs, have been around for years but really blew up in 2020. Inspired by Beeple’s $69 million NFT artwork auction, other major artists and musicians began minting artworks last year, spurring a cultural frenzy that has carried over into 2022. Everyone from Eminem and Mozart to the National Football League and Coca-Cola have found a special place on the blockchain through NFTs. Despite their rapid ascent, it looks like NFTs are here to stay. And as unique digital assets that can represent just about anything, like artwork, audio or video content, it’s easy to see why. But why did they become so popular? What makes the underlying tech so powerful to those wielding it? And what role is NEAR playing in all of this? More than just a fad NFTs first made headlines because of the seemingly obscene amounts of money being spent on them. Who would spend $1.3 million on a single grey pixel, some asked? And what is the point of snapping up a digital image when you could just screenshot it? It seemed to many just a passing craze for people with a lot of money. But, fast forward to 2022: NFTs have proven they are more than just a fad, or just an investment for the rich. The unstoppable rise of NFTs has much to do with how they make us reimagine ownership. Now, an NFT’s cryptographic stamp is recorded on the blockchain, proving ownership of things like art, music, and even documentation, like a driving license or medical documents. “They are going to be everywhere and have lots of uses,” says Monish, community builder at The Auction, a secondary sale NFT marketplace built on NEAR. “No one can resist. Everyone will have an NFT in their wallet—this includes anything from an RC book to a driving license. They are not just an investment.” Monish captures something essential about NFTs. They were just an investment, and largely limited to the art world. But now developers are capitalizing on their other use cases to transform industries. Here’s how. What else can NFTs do? An NFT is essentially a digital container which holds intellectual property (IP). These containers are minted, bought, and sold. And since the blockchain stores that IP, it guarantees the owner is the only owner with a place in an unmodifiable public ledger. This is useful if one wants to be the rightful owner of a piece of art, and good for the artist who might want to know who bought their work. But, there are plenty of other things NFTs can do—especially NFTs that run on NEAR’s blockchain. Vandal, a music producer and founder of DAOrecords, a record label built on NEAR, talks of how music NFTs will get a better deal for artists and those involved in music production. Think about it like this: if a CD is sold, or a song is streamed, it is up to the record label or streaming service to determine how and when to pay the royalty splits. Artists can wait a long time for their cut of the royalty. But if a musician releases a record in the form of an NFT, the technology automatically and immediately pays the artist and other co-creators a set amount. NEAR Protocol’s NFT standard automatically bakes royalty splits into the smart contract, streamlining the payout process. “NEAR’s NFT technology is so powerful because it has the ability for people to do multiple splits,” says Vandal. “You can set various wallets at different percentages of an NFT and automate those splits. That’s a really good feature. And I think the reason for that feature is the low transaction cost and network speed.” While still novel, music NFTs are already common. From major acts like Kings of Leon—the first band in the world to sell an NFT album—to smaller independent artists, like UK-based Origin Beats, many musicians have been experimenting with NFTs in the last year. “My personal biggest thing is the creative flexibility and control,” Vandal says. “That’s what excited me the most and hooked me immediately 11 months ago. And self-releasing music and cutting out the middleman is huge.” NFTs on NEAR now even have the power to give rewards to their creators or owners. Users can stake assets on a platform or protocol, earning interest for those involved. Paras, an NFT marketplace launched on NEAR in 2021, recently introduced the staking of its native utility coin $PARAS. As Co-founder Rahmat “Riqi” Albariq noted, $PARAS’s use cases include an exclusive pass to future deals and events, as well as a foundational piece of the Paras DAO governance. Shifting the cultural paradigm with NFTs NFTs are changing the game for those previously not involved in the crypto or tech worlds. Naksh, an NFT marketplace used by artists in India, is just one example. Built on NEAR, Naksh puts traditional art on the blockchain. Founded by art graduates Sri Lakshmi and Nivedita Vivek, the platform is working to help resurrect the traditional art market in India. The two, who had no crypto background, say they want a future where art exchanges help both the buyer and the artist. Lakshmi says they chose NEAR’s blockchain for their platform because it is carbon neutral. Now the two are focusing all their energy on NFTs and getting artists the best deals for their work. Sri adds that although Naksh onboarded some artists at first, more are onboarding as the project gets more publicity and funding. “As with any new tech that comes up, everyone is skeptical and not 100% sure it will work,” she says. “A lot of these artists come from rural parts of India and are not very educated, so to get them to understand an up and coming technology and digital assets is a task. And even though we have confidence, they are still skeptical about the scalability of this.” “A lot of artists made their livelihood through physical artforms so it can be hard to convince them,” she adds. “But the ones who are now on board swear by it.” A user-friendly NFT experience Web3 developers and investors are confident that NFT technology will continue to transform industries—and not just the art world. Many think NFTS will eventually create entirely new economies. Play-to-earn gamers in the Philippines, for instance, already participate in an NFT economy. And in the near future, it’s likely that NFTs will be currencies in the metaverse. The challenge will be convincing crypto-skeptics of their utility. And Web3 apps will require a simple user experience that people have come to expect in Web2.
MetaBUILD 2 Hackathon Winners COMMUNITY March 31, 2022 For the last three months, NEAR developers and entrepreneurs from across the globe have been hard at work on the MetaBUILD 2 hackathon. For the NEAR community, this hybrid virtual-physical event is a hotbed of Web3 ideas, creativity, and innovation. Developing on NEAR’s simple, scalable, and secure blockchain, these projects are the integral building blocks laying the foundation for a better future. A future where millions of new users and developers work together to create and share completely new journeys in Web3. Just as the NEAR community has grown by leaps and bounds, so too has MetaBUILD. Similar to the first hackathon, MetaBUILD 2 has a total of $1 million in prizes to give away. But this time nearly 4,000 participants joined the hackathon, submitting over 356 projects—of which, 186 were eligible—across NFTs, DeFI, Gaming, DAOs, infrastructure apps and tools, and EVM apps. For the NEAR MetaBUILD 2 hackathon, we had Welcome and Natives tracks, as well as 35 Sponsor Challenges. If you’d like to get in touch with any of our winners, join our Discord channel. Grand Prize Winners 1st Place – Voog A blockchain app-builder, Voog is a super simple UI-based smart contract builder, featuring one-click deployment to NEAR and an auto-generated UI to implement contracts. Learn more about Voog. 2nd Place – MetaAds A brand new decentralized online-2-offline (O2O) protocol, MetaAds aggregates Metaverse ads with Indoor and Outdoor ads in the real world. Learn more about MetaAds. 3rd Place – NEAR Playground A browser-based editor, NEAR Playground empowers developers to write, compile, test, and call NEAR Rust and AssemblyScript smart contracts in the browser. Learn more about NEAR Playground. Welcome Track – Best Technology Winners The Welcome Track was for those developers who already had an app and wanted to integrate NEAR blockchain into it. The Welcome Track was also for non-blockchain developers who may have had an idea for a NEAR app but wanted to get familiar with the Web3 technology. Those hackers who wanted to be eligible for one more of the 35 sponsor prizes were encouraged to bake a challenge solution into their project. Below are the Welcome Track’s “Best Technology” winners. Rainbow Bridge Explorer An API for exploring bridge transactions between NEAR, Aurora, and Ethereum, the Rainbow Bridge Explorer allows users to explore their bridging activities and discover trends on the Rainbow Bridge. Learn more about Rainbow Bridge Explorer. MineLand A Play-to-Earn NFT collectible game, MineLand allows players to mint mines and collect resources with advanced game logic. Learn more about MineLand. NEAR Playground A browser-based editor, NEAR Playground empowers developers to write, compile, test, and call NEAR Rust and AssemblyScript smart contracts in the browser. Learn more about NEAR Playground. Natives Track – Best Technology Winners The Natives Track was designed for developers already familiar with NEAR, Aurora, or Octopus blockchain, or who wanted to build an ecosystembuild ecosystem and tooling apps (using blockchain data, not the technology). As with the Welcome Track, Native Track participants were eligible for one more of the 35 sponsor prizes if they tackled at least one of the challenges in their project. Below are the Natives Track’s “Best Technology” winners. Shizo A metaverse map based on a map of the physical world, Shizo is the place where you can buy and sell digital roads and lands, as well as change their appearance. Learn more about Shizo. MetaAds A brand new decentralized online-2-offline (O2O) protocol, MetaAds aggregates Metaverse ads with Indoor and Outdoor ads in the real world. Learn more about MetaAds. Voog A blockchain app-builder, Voog is a super simple UI-based smart contract builder, featuring one-click deployment to NEAR and an auto-generated UI to implement contracts. Learn more about Voog. Brave CryptoDino Challenge Winners Jeffrey The Dinosaur’s Dinotastic Blockchain Adventure First place winner of the Brave CryptoDino challenge, Jeffrey the Dinosaur’s Dinotastic Blockchain Adventure allows users to log in with NEAR and equip skin NFTs from their wallets. The game mechanics are largely the same as the original, although this one’s cacti are a little bit taller. Learn more about Jeffrey The Dinosaur’s Dinotastic Blockchain Adventure. OpenSkin Second place winner of the Brave CryptoDino challenge, OpenSkin allows players to earn “dino points” as they play, which are then added to the user’s NEAR wallet. The team also created a marketplace called OpenSkin, where artists can upload their game skins as jpegs, which are then converted into tokens that users can collect. Learn more about OpenSkin. MetaBUILD 2 Co-Organizer Track Winners Sponsors NEAR Foundation, Aurora, Brave, and Octopus Network co-organized MetaBUILD 2. Here are the hackathon winners for this co-organizer track. “Calling All Liberal Artists” – Bit Civilization A multi-chain DAO infrastructure service protocol, Bit Civilization aims to transform all aspects of human society like family, tool, language, belief, law, culture and art. Learn more about Bit Civilization. “Airtable Is the New Excel” – NEAR Validators Dashboard NEAR Validators Dashboard gives users a view of all validator details on the NEAR network. Learn more about NEAR Validators Dashboard. “Build an NFT Marketplace” – Borealis The winner of Aurora’s sponsor track, Borealis NFT marketplace facilitates the creation, buying, and selling of NFTs in an automated environment. Learn more about Borealis. “Oracles” – Symm Finance Symm, The winner of Aurora’s “Oracles” sponsor track, is a decentralized, fully on-chain exchange for perpetual futures built on NEAR’s Aurora, an Ethereum Virtual Machine. Learn more about Symm Finance. “ERC20-Factory” – Kahu Kahu, the winner of Aurora’s “ERC2-Factory” sponsor track, allows non-technical blockchain users to easily mint ERC20 Tokens on Aurora, using advanced features. Learn more about Kahu. “Appchain Challenges” – SmartCV SmartCV, winner of Octopus Network’s “Appchain Challenges” sponsor track, aims to help organizations find the right talent at low cost. It also allows employees to easily find the job positions most suitable for their talents and skills. Learn more about SmartCV. The Full List of MetaBUILD 2 Winners Curious about all of the other winning projects? Check out the full list of MetaBUILD 2 hackathon winners.
NFTs on NEAR: A Deep Dive into Paras COMMUNITY May 19, 2022 Paras, an NFT marketplace for digital art cards, is one of the most active communities within the NEAR ecosystem. What began as a decentralized social media platform is now a vibrant mecca for crypto art. Everything from one-off artworks to themed series can be found on Paras. Late last year, the Jakarta-headquartered team released a new product, Paras Comic. As the first home for digital comics on NEAR, writers and illustrators can upload their digital comics as collectible NFTs. Now, comics and crypto art fans alike can interact, engage, and support creators by buying NFTs, and even tipping the artists. The Paras team isn’t stopping with NFT artworks and comics. As co-founder Rahmat “Riqi” Albariqi tells NEAR Foundation, Paras plans to release a few other features in the coming months. It’s all part of the plan to be a broad cultural hub for NFTs. Paras: an origin story It was 2017, and Riqi was in his final year at university. Like many early crypto adopters, he was initially attracted to the trading. But, as a developer, Riqi also began familiarizing himself with blockchain’s more technical aspects. He was interested in building decentralized apps, but didn’t feel the time was right to build a dapp. Fast forward to 2020. The crypto space was moving beyond trading. New protocols were emerging, and developers were building atop them. So, after leaving his job and taking a two-month break, Riqi dove head first into Web3 app development with his partner, Afiq Shofy. After successfully building some functional decentralized apps on Blockstacks, Riqi and Shofy launched Paras in March 2020. Initially, the two envisioned Paras as a “persona website generator”—a single page where users could present their avatar, resume, CV, and so on. “Then Afiq and I thought, why don’t we just do something bigger?,” Riqi recalls. “Why don’t we just make a decentralized social media platform because, you know, we already have the profiles, the avatars. We just need to build the post and comment [feature].” Taking Paras to NEAR At about this time, Riqi and Shofy were looking for a more scalable blockchain. Ultimately, they landed on NEAR Protocol. “At the end of the day, we just use NEAR because it’s way better than all the other blockchains out there,” says Riqi. “It’s scalable, easy to use. The tooling and everything else is great.” This social media iteration of Paras launched on NEAR’s testnet in Q3 of 2020. But, as Riqi notes, within a few months it had failed. There weren’t many users, and the ones who did use Paras were part of an easily observable niche: novice digital artists. So, it was back to the drawing board for Riqi and Shofy. For months, the two considered turning Paras into a social media platform for digital artists. Something like Deviant Art, but on the blockchain. However, after researching NFTs on Ethereum, Riqi quickly realized there was steady NFT sales growth from August through October of 2020. “NFTs were getting hot and we thought, why not build an NFT marketplace instead of a social media platform,” says Riqi. “And when we interviewed users, they said they wanted to make more money from their art. So, NFTs solve the problem, right?” Riqi and Shofy quickly reworked Paras into an NFT marketplace. “We rewrote everything,” says Riqi. In December, the two re-launched Paras as an NFT marketplace on NEAR. By early 2021, Paras had onboarded over 70 artists and 80 active collectors, who were generating revenue by selling and trading digital art cards. The number of artists and collectors using Paras has grown exponentially in the last year, thanks to the low-cost of minting artworks on NEAR. Paras now boasts 90K registered users, 20K of which are regular users. Together, 12K artists and 50K collectors have generated approximately $18 million in artwork sales. This low barrier to entry has helped make Paras one of the the most popular NFT marketplaces and decentralized apps on the NEAR ecosystem. Paras and NFT curation Some NFT marketplaces suffer, both visually and content-wise, from their decentralized nature. The sheer number and variety of NFT artworks, while inspiring, can quickly become confusing from a user experience perspective. Not so with Paras. Riqi, Shofy, and the rest of the team have given Paras a simple UX design, making it easy for users to find what they’re looking for. On the Paras homepage, users can peruse Featured Collections, which spotlight some of the platform’s most notable NFT artworks. There are also categories for the Top Collections of the last seven days, as well as works generating the Highest Sales. And if one is curious who the Top Buyers and Sellers are on Paras, those curatorial categories exist too. The “Publication” feature allows creators to enhance their visuals through a storytelling format. Within the Publication vertical, Paras empowers community curation via storytelling, but also offers a weekly Editorial, through which the team profiles the latest NFT creators and art. These curatorial efforts also extend to social media. The Paras Twitter account, in particular, showcases artworks popping up on their ecosystem. “If you look at our social media, we always promote indie artists or smaller creators,” Riqi explains. “We just retweet the artists’ post and give it some context and whatnot.” “That’s really how we think about supporting smaller artists: just giving them more exposure,” he adds. “If we can nurture them, if we can connect them with the right person, if we can promote them, some can actually become big artists. And that’s how we think about it.” Paras Comic In December 2021, a year after launching on NEAR, the Paras team released its most recent feature—Paras Comic. A standalone app of sorts, Paras Comic is a way for creators, readers, and collectors to engage with comics without a centralized intermediary. On this new comics publishing platform, users can support creators by collecting NFT comics. Paras Comic already has titles like action fantasy manga ATMA, and the trippy fantasy comicBob Boom!!. And, if collectors like what they see and read, they can even tip the artists. Gary Edmund, a comics artist who has worked with Marvel and indie publishers, says publishing Bob Boom on Paras has been an absolute adventure. As he sees it, Paras and comics artists are doing something that’s never been done before. “I’ve worked for major (Marvel/Dynamite) comic book companies and indie companies for years: I was institutionalized to the boundaries of producing a comic in print form,” Edmund says. “Most digital comics are still done in that “printable format” form. Once I wrapped my head around the fact that I don’t have to do that within the NFT Universe, and I could just go fucking crazy, I did.” Edmund says the Bob Boom! Plot is bonkers, even though it’s packaged as a “bounty hunter” comic. People might expect a Star Wars-esque story, but Edmund promises something different. A comic that obliterates the genre. He believes entertaining the Paras audience in this way is his job, in part, to counter the oversaturation of superhero movies, science fiction movies, and comics. “People think they have seen it all, but with Bob Boom! I’m able to shatter that with multiple art styles and insane plot twists,” he says. “Maybe some people think Bob Boom! goes too far at some points. I think it’s just the tip of the iceberg.” “Once word gets out outside of the Paras community it’s going to blow up even bigger,” he adds. “Right now it’s the Paras community’s advantage to be able to invest in this comic when so many comic readers haven’t even dipped their toes into the NFT marketplace. Once your average ordinary everyday collector and your high end, high dollar, have to have the first of everything collectors are on Paras they are going to want these pioneering comics.” Paras token staking, gaming, and other new features Earlier this year, Paras launched NFT staking for the $PARAS token. Created as a utility token back in September 2021, $PARAS’s use cases include an exclusive pass to future deals and events, as well as for DAO governance. $PARAS staking will also be the foundation of governance, which is set to launch in the next couple of weeks. There will be other ways to earn on the Paras platform. With ExVerse, Paras is beginning to explore play-to-earn (P2E) gaming. A free P2E MMO Battle Royale game, ExVerse is bridging the gap between the mainstream gaming industry and Web3. Think of it as a decentralized Fortnite. Or, as the ExVerse team calls it, “the first ever battle metaverse”, where players can sell NFT skins, boxes, and more. “[The creators of ExVerse] already have the playable game even before they sell it, so that’s something really unique in the NFT space,” says Riqi. “They have a really great team, great developers, and that’s why we partnered with them.” “The big vision of Paras is to expand the endgame of NFTs—that’s really our big tagline,” says Riqi. “When we started with NFTs we thought, okay, some NFT art and games, and that’s it. But, now we believe that there is a lot more that can be built on top of the NFT ecosystem.” NFTs as pop culture Riqi believes mainstream crypto adoption starts with Paras Comic. Using it as a gateway, Paras plans to leverage comics culture and fandom to onboard more and more users, paving the way for future NFT offerings. “We are currently working with a lot of different studios, from comic series, obviously, to Game Studios and IP [intellectual property] studios,” Riqi says. “You can’t really add more features to the Paras NFT marketplace, so in the next three to six months we’re going to launch several smaller projects.” Paras will either develop these projects in-house or support entrepreneur teams with their financial or technical expertise. Riqi says the team is currently looking at digital books and fashion as just a few near future NFT offerings on Paras. “If you take a look at comic markets, the fashion industry, the gaming industry, all of them are related to this pop culture kind of stuff, right?” Riqi says. “So, that’s where Paras is heading.” “We want to be known as a place for pop culture-related NFTs.”
How blockchain will save the Creator Economy CASE STUDIES July 7, 2021 Why NFTs, DAOs and Open Finance will change the world for artists and their communities. Creators are Innovators Creative industries have always led innovation because they’re fundamentally exploratory and hungry for ways to help create sustainably. Hip Hop, for example, pushed the envelope in almost every possible way during its ascent from the streets to becoming the dominant form of music in the world. DJ Kool Herc, its commonly acknowledged progenitor, birthed a new art form when he extended dance-friendly breaks by combining multiple records across turntables in the ‘70s and others in the industry have driven innovation ever since. Just like that first technological experimentation to make better dance parties in the Bronx started a revolution in music production, today we’re seeing the emergence of a new set of tools with the same power to enable artists to engage their fans and change the world. In this post, I’ll walk through some of the problems that creators and communities face today and how a new blockchain-enabled toolkit will make them more aligned, engaged and sustainable. The Creator Economy The advent of the Internet in the late ’90s ushered in an era where people around the world could both create and consume much more easily than ever before. You can do more with a Macbook today than a whole studio could 20 years ago. It also became substantially easier to find communities of common interest regardless of geography, and a larger portion of all our lives migrated into the digital realm. New hardware and software tools made it much easier to produce content — whether multi-platinum albums or simply micro-niche blog posts — while the web’s scale made it much easier to distribute this content. Unfortunately, the boom in creation and the massive expansion of platforms to support large fanbases wasn’t matched by a similar boom in the sustainability of creators. In fact, while the increased size of audiences allowed top creators to reach a grander scale, the infinite replication of content and the power of distributors as middlemen made it more difficult for most other creators to benefit from their intellectual property (“IP”). The relationship between creators and their communities drives the so-called Creator Economy, which is a dynamic between 3 factors: Creators who produce something of value Communities who support these creators Financial tools and platforms to help make creators and their communities sustainable The line between creators and communities can be blurry, for example when users generate content, but ultimately someone has to pay for something in order to create a sustainable economy. Today, this economy is generally a one-way path where the creator produces something (eg an album), gets fans to consume it (typically losing most of the proceeds to the middlemen who control their relationship with fans) and tries to earn real income from secondary revenue streams like concerts or merchandise or sponsorships. This system is rife with problems and it’s only sustainable for creators with enormous or highly engaged fan bases, particularly if they’ve given away their IP rights along the way. This leaves the so-called “long tail” of smaller creators underserved and makes things tough even for the larger ones due to all the middlemen who have their hands in the pie. What’s Changing Today So how do we make the creator economy more sustainable for everyone? It requires improving the underlying technology of the web to unlock new tools for both creators and their communities to build stronger, more sustainable bonds. Specifically, it means merging the technological revolution which started with Bitcoin in 2008 with today’s Internet to create new tools like NFTs, DAOs, Fungible Tokens and Open Finance (“defi”). Here’s how it all fits together. If you go back to the Creator Economy Triangle from before, each corner has needs that weren’t met before: Creators haven’t been able to sustainably benefit from their IP because of the commodification of content in the digital world which devalues their creativity and which leaves them at the mercy of their distribution partners and the platforms holding their fanbases. Communities haven’t been able to effectively self-organize outside of existing social platforms, make themselves sustainable or align their interests with those of the creators they support. Financial tooling has limited the economy itself to one-time or recurring payments for goods or services because the tooling has been anchored in a world of bank accounts and Paypal-like providers. Royalty schemes and payments are also notoriously arcane, inconsistent and exploitative to creators. In 2021, blockchain technology has finally arrived at the point where it can solve all three of these issues and unblock the Creator Economy. This is because each of the key aspects of the Creator Economy is served by a specific set of tools which weren’t possible to combine like this before a platform like NEAR was available. This gives us a new Creator Economy Triangle, which shows how these tools — NFTs, DAOs, Fungible Tokens and Open Finance (“defi”) — interact: At a high level, it breaks down like this: NFTs are basically digital containers which can hold IP but which liberated it to be owned and traded so creators have a world of new ways to produce, distribute, remix and monetize content. DAOs are basically like shared bank accounts for communities which are entirely digital so it’s really easy for communities to act almost like official co-ops or companies and build sustainable models for themselves. They can issue fungible tokens which are basically membership cards with a lot more potential superpowers to drive more engagement. Open (“decentralized”) Finance is a whole toolkit which allows creators, communities, NFTs, DAOs, fungible tokens and all the other pieces of the digital economy to plug into each other in ways that no one has ever done before, allowing entirely new ways of earning income for creators or benefitting from the upside of membership for community members. Let’s look a little deeper into each of these pieces and why they’re so powerful to help creators. NFTs: Tools for Creators NFTs are understandably confusing for many people, so I’ll break it down in plain English. The most important concept in NFTs is that, after decades of infinitely sharing creative output on the Internet, we finally have digital scarcity. That means that we can finally prove that a particular file or piece of content or piece of data is uniquely owned by a single person. > Aside: Bitcoin to NFTs All digital tokens, including NFTs, are based on the same principle as Bitcoin because it uses the same type of technology — “blockchain.” What the creator of Bitcoin figured out is that, if we create a globally shared ledger that records the owner of every single bitcoin in the world, we can always know exactly how many Bitcoin there are in the world and make sure no one is spending them twice. If you ever hosted a website on Geocities back in the day and watched it get lost forever because their platform shut down, you understand the value of protecting your important assets from deletion. What Bitcoin figured out is that you can essentially share the hosting of this ledger among thousands of people around the world so, unlike Geocities, it can never get deleted just because one of them got shut down. So, fundamentally, an NFT is just like a Bitcoin — it’s a unique piece of data that everyone in the world agrees is owned by, say, Joe Smith because thousands of people are running the NEAR network together and agree on it. What’s different is that NFTs are much more advanced than Bitcoins. A bitcoin is really pretty boring — I can show you that I own one, I can send it to my friend to pay for something and I can do a few more simple operations with it. An NFT, because it’s built on a much more advanced network, is basically an empty container that can hold any type of data AND you can program it to do anything just like software. Why NFTs are so powerful Here’s why that’s so useful for artists, using a simple example. Let’s say an artist has created a piece of digital artwork. In today’s world, those rights are usually stored in the server of some record label somewhere and backed up by a paper signature on some lawyer’s document or, if the creator is independent, it’s at least protected by copyright law so the artist just owns it. Every time the artist allows someone to use it (officially), they or their manager have to explicitly allow it to happen with some sort of signature, which really slows things down and limits how it can be used. If the artist assigns the IP rights to an NFT, that NFT becomes like a bearer-bond because whoever holds it can now use the legal right. In the simplest case, that person can display it on their digital wall just like a piece of art in the real world and they can know that it’s truly *theirs* to display. But, unlike a painting in the real world which can be bought or sold in a smoke-filled room somewhere and the artist never knows, NFTs are digital objects that can be programmed to do anything and you can always know where they are. In the physical world, the artist makes revenue from selling an original edition and maybe the rights to produce more. When these things are resold, the artist never knows about it and never earns any income from it. Because NFTs are digital objects that live on the NEAR blockchain, every time they are bought and sold, the artist can be notified and paid a commission. Every time, in every location. Not just that, but the NFT can be programmed to permanently split that revenue however you want — maybe 10% goes to the artist, 5% to the agency which helped create it, 4% to the artist’s union and 1% to a charity they support. Maybe 5% gets split among everyone who previously owned this NFT so they are incentivized to help it retain value. Anything is possible. That’s not even the best part. Because NFTs can send cash back to the artist automatically when they’re traded, they can be traded anywhere. Before today, digital items were stuck in centralized marketplaces because that was the only way that companies could pull revenue from their resales. For example, digital skins which are created and traded in the Fortnite ecosystem need to be purchased on Fortnite’s proprietary platform so they can get their cut. But now that the NFT itself will always send the money back home, it can be traded anywhere and the artist or original IP holder will always get paid. Let me ask you — back when you were a kid and traded collectibles, did you do so on some official company marketplace or unofficially among your friends? Exactly. Now, everyone from artists to big IP-holding companies are incentivized to set their NFTs free so people can trade them anywhere in the world. Suddenly, everyone’s interests are aligned to set the art free! This will result in orders of magnitude more transactions. More trading. Because NFTs are infinitely programmable, we don’t even know yet all the cool ways they can be used. It’s possible to use NFTs as membership cards which give people access to special events. The artwork becomes more than just a thing to display or a cash flow, they become a special designation of status that the artist or anyone else can use to give special privileges to the holder of. What else might be possible? DAOs and FTs: Tools for Communities A “DAO” is a decentralized autonomous organization–– which uses an admittedly clunky acronym to represent a formalized community that can self-govern and take on some aspects of a company. Everyone who uses the blockchain gets a NEAR account. It’s sort of like a Facebook or Google or bank account except that, just like NFTs, it’s permanent because it lives on NEAR’s “forever network” and it’s not associated with any particular company. It’s 100% yours and you can call it whatever you want – for example by naming it after your Twitter or Insta handle (I see you `machoman99`). This account can store your tokens, your NFTs or pretty much anything else you do on the platform. A DAO is basically just a more advanced account which can be shared between a group of people. In this way, it’s similar to a bank account but it doesn’t actually need a bank. Why DAOs are so powerful DAOs are useful because they can do anything an individual user can but they can also represent all of the users who are their members. In the simplest example, you can store a bunch of tokens in a DAO and the group of users in the community can vote to send them to different places. Let’s use the example of a fanclub DAO we’ll call `dj_blokk_fanclub`, where fans of that artist pool funds to buy VIP tickets for a show and raffle them off. Because the community exists on a permanent platform like NEAR, it isn’t lost if Facebook or Snap suddenly become less popular. This example is simple but bear with me. Just like NFTs, DAOs are a basic tool that quickly gets extremely powerful. For example, a community can issue a token (it’s called a “Fungible Token” aka “FT”) and use that token to determine what kind of privileges their members get. For example, let’s say our DAO issues 10,000 `$BLOKK` tokens to split among the fanclub’s early members and then automatically creates another 10,000 each year that can be distributed to new members, really helpful members who help the group govern itself, or people who refer new members. And let’s say members need to hold 10 `$BLOKK` tokens to join the VIP Discord server. This incentivizes community members to be extra engaged and helpful. Or maybe the community’s DAO issues the same 10,000 `$BLOKK` tokens but gives 1,000 to the actual DJ Blokk in appreciation and DJ Blokk gives special VIP show access to anyone who holds more than 100 `$BLOKK` tokens. This is important because now the creator and the community are beginning to directly align themselves. And the token suddenly has value as well. Finally, it gets magical when we combine the DAO with NFTs. Let’s say DJ Blokk is putting together a new single and wants to fund it from within the community. The artist can sell `$BLOKK` tokens and, in exchange, issue an NFT that sends some of its royalty stream back to the community’s DAO. Suddenly, you’ve unlocked: A way for communities to be platform independent and distribute funds A crowdfunding mechanism for artists A way for community members to be financially aligned with making the artists they support successful, creating extremely high engagement and virality. As with NFTs, we still don’t know all the ways you can use DAOs to support creators and communities but just these few are enough to break existing industry models. Decentralized Finance: Making it Sustainable Creators usually only think about payments when they’re broken. “Can people in [insert country] buy my merch? Great.” As a quick review, we’ve already introduced some new NEAR-powerd financial tools — NFTs can be programmed to send royalties anywhere when they are traded DAOs give communities the ability to send payments and issue tokens without a traditional bank account As before, let’s explore what’s possible by building up from the simple stuff. For starters, our creator’s NFTs or our community’s `$BLOKK` token need to be bought and sold somehow. Consumers need to easily click an Instagram link to purchase the initial NFT, buy it on a marketplace somewhere or get their hands on `$BLOKK` tokens so they can get in the VIP club. This is all straightforward stuff that can be done with familiar credit card processing on NEAR. Things get more interesting when you consider what people might do when they are holding their new NFT or `$BLOKK` token in their accounts. Before today, if I bought a collectible online or received it for attending a concert, it would just sit in my account on that one single platform or scattered across multiple independent platforms which don’t communicate with each other. Today, getting those collectibles is just the beginning. For example, a community of fans may decide to set up a DAO for themselves which purchases very rare NFTs. These NFTs can then be used as collateral in automated lending platforms to borrow more money to participate in future sales that might only be open to the holders of those NFTs. The community DAO could even issue their own tokens so small pieces of the portfolio can be easily traded and people around the world can participate. All of this is part of a stable, global financial system which has previously only been accessible to the wealthier countries. Essentially, assets that were created in the digital world have access to the entire suite of sophisticated financial tools that historically were only available to wealthy investors. Because of this, there are markets around the world for each of these tokens and NFTs which makes them much more liquid and thus more desirable to hold. It’s hard to sell a Picasso, but much easier to sell tiny portions of NFTs from the DAO above. More simply, holders of these collectibles can buy, sell, trade or combine them with others to access real world benefits, play in digital games, or otherwise engage more deeply with their creators. If you’re lost in the financial language, the key takeaway is this — NFTs issued by artists typically benefit most when they are frequently traded and the new decentralized financial toolkit makes this extremely easy compared to the way it works in the traditional world. But, as with NFTs and DAOs, we still haven’t even figured out all the ways this technology can be used. Luckily, it’s easier to remix these tools than it ever has been. A developer in a single weekend can now build sophisticated financial products that securely handle these assets and their cash flows, which normally would take a team of developers with millions of dollars in venture capital months to put together. This means that the speed of innovation is finally moving at the pace of creativity so artists can get directly involved in the creation, building, remixing and experimentation of new tools that produce new art, engage fans and generate novel revenue streams. Tying it all Together Where are we now and where is the ball going? While blockchains have been around since Bitcoin arrived in 2008 and many of the core ideas — NFTs, DAOs, Fungible Tokens and Defi — have been in experimentation on Ethereum since 2016, NEAR’s launch late last year was the first time a platform came to life which could make these tools accessible to everyday creators, communities and fans. A lot of the financial tooling of Defi was built and tested on Ethereum, particularly during mid-2020, but remains prohibitively expensive and complicated for most people to use. NFTs had a moment in late 2020 and early 2021 when a bunch of artists started making eye-popping sales and big companies started playing with gamification but these experiences were incomplete because they either couldn’t be accessed by everyday people due to cost and and usability concerns or they were part of wholly owned “walled gardens” which leave the assets isolated. DAOs are just starting to pick up momentum because, until now, there hasn’t been a way to make them useful to consumers due to cost and usability concerns. Now that this final piece has been solved on NEAR, DAOs will finally be able to serve communities as they were meant to. So, the tech has finally arrived to use these tools but we’re still in the explore-and-mix phase. It’s like the first time DJ Kool Herc kept that break beat going between two records — we just had the major “aha!” moment and now it’s up to the creators and communities of the world to take these tools and get this party started. …and, if you’re ready to do so, reach out! For creators or IP holders with massive fanbases, reach out to [email protected] to see how this can be transformed into an engaging, repeated revenue stream. For community leaders interested in upleveling their community engagement and sustainability, reach out to [email protected]. Finally, if you’re a developer who wants to hack on this stuff, check out https://docs.near.org and the free 5-day bootcamp at https://learnnear.club/certified-near-developer-application/.
# Consensus ## Definitions and notation For the purpose of maintaining consensus, transactions are grouped into *blocks*. There is a single preconfigured block $G$ called *genesis block*. Every block except $G$ has a link pointing to the *previous block* $\operatorname{prev}(B)$, where $B$ is the block, and $G$ is reachable from every block by following those links (that is, there are no cycles). The links between blocks give rise to a partial order: for blocks $A$ and $B$, $A < B$ means that $A \ne B$ and $A$ is reachable from $B$ by following links to previous blocks, and $A \le B$ means that $A < B$ or $A = B$. The relations $>$ and $\ge$ are defined as the reflected versions of $<$ and $\le$, respectively. Finally, $A \sim B$ means that either $A < B$, $A = B$ or $A > B$, and $A \nsim B$ means the opposite. A *chain* $\operatorname{chain}(T)$ is a set of blocks reachable from block $T$, which is called its *tip*. That is, $\operatorname{chain}(T) = \{B \mid B \le T\}$. For any blocks $A$ and $B$, there is a chain that both $A$ and $B$ belong to iff $A \sim B$. In this case, $A$ and $B$ are said to be *on the same chain*. Each block has an integer *height* $\operatorname{h}(B)$. It is guaranteed that block heights are monotonic (that is, for any block $B \ne G$, $\operatorname{h}(B) > \operatorname{h}(\operatorname{prev}(B))$), but they need not be consecutive. Also, $\operatorname{h}(G)$ may not be zero. Each node keeps track of a valid block with the largest height it knows about, which is called its *head*. Blocks are grouped into *epochs*. In a chain, the set of blocks that belongs to some epoch forms a contiguous range: if blocks $A$ and $B$ such that $A < B$ belong to the same epoch, then every block $X$ such that $A < X < B$ also belongs to that epoch. Epochs can be identified by sequential indices: $G$ belongs to an epoch with index $0$, and for every other block $B$, the index of its epoch is either the same as that of $\operatorname{prev}(B)$, or one greater. Each epoch is associated with a set of block producers that are validating blocks in that epoch, as well as an assignment of block heights to block producers that are responsible for producing a block at that height. A block producer responsible for producing a block at height $h$ is called *block proposer at $h$*. This information (the set and the assignment) for an epoch with index $i \ge 2$ is determined by the last block of the epoch with index $i-2$. For epochs with indices $0$ and $1$, this information is preconfigured. Therefore, if two chains share the last block of some epoch, they will have the same set and the same assignment for the next two epochs, but not necessarily for any epoch after that. The consensus protocol defines a notion of *finality*. Informally, if a block $B$ is final, any future final blocks may only be built on top of $B$. Therefore, transactions in $B$ and preceding blocks are never going to be reversed. Finality is not a function of a block itself, rather, a block may be final or not final in some chain it is a member of. Specifically, $\operatorname{final}(B, T)$, where $B \le T$, means that $B$ is final in $\operatorname{chain}(T)$. A block that is final in a chain is final in all of its extensions: specifically, if $\operatorname{final}(B, T)$ is true, then $\operatorname{final}(B, T')$ is also true for all $T' \ge T$. ## Data structures The fields in the Block header relevant to the consensus process are: ```rust struct BlockHeader { ... prev_hash: BlockHash, height: BlockHeight, epoch_id: EpochId, last_final_block_hash: BlockHash, approvals: Vec<Option<Signature>> ... } ``` Block producers in the particular epoch exchange many kinds of messages. The two kinds that are relevant to the consensus are **Blocks** and **Approvals**. The approval contains the following fields: ```rust enum ApprovalInner { Endorsement(BlockHash), Skip(BlockHeight), } struct Approval { inner: ApprovalInner, target_height: BlockHeight, signature: Signature, account_id: AccountId } ``` Where the parameter of the `Endorsement` is the hash of the approved block, the parameter of the `Skip` is the height of the approved block, `target_height` is the specific height at which the approval can be used (an approval with a particular `target_height` can be only included in the `approvals` of a block that has `height = target_height`), `account_id` is the account of the block producer who created the approval, and `signature` is their signature on the tuple `(inner, target_height)`. ## Approvals Requirements Every block $B$ except the genesis block must logically contain approvals of a form described in the next paragraph from block producers whose cumulative stake exceeds $^2\!/_3$ of the total stake in the current epoch, and in specific conditions described in section [epoch switches](#epoch-switches) also the approvals of the same form from block producers whose cumulative stake exceeds $^2\!/_3$ of the total stake in the next epoch. The approvals logically included in the block must be an `Endorsement` with the hash of $\operatorname{prev}(B)$ if and only if $\operatorname{h}(B) = \operatorname{h}(\operatorname{prev}(B))+1$, otherwise it must be a `Skip` with the height of $\operatorname{prev}(B)$. See [this section](#approval-condition) below for details on why the endorsements must contain the hash of the previous block, and skips must contain the height. Note that since each approval that is logically stored in the block is the same for each block producer (except for the `account_id` of the sender and the `signature`), it is redundant to store the full approvals. Instead physically we only store the signatures of the approvals. The specific way they are stored is the following: we first fetch the ordered set of block producers from the current epoch. If the block is on the epoch boundary and also needs to include approvals from the next epoch (see [epoch switches](#epoch-switches)), we add new accounts from the new epoch ```python def get_accounts_for_block_ordered(h, prev_block): cur_epoch = get_next_block_epoch(prev_block) next_epoch = get_next_block_next_epoch(prev_block) account_ids = get_epoch_block_producers_ordered(cur_epoch) if next_block_needs_approvals_from_next_epoch(prev_block): for account_id in get_epoch_block_producers_ordered(next_epoch): if account_id not in account_ids: account_ids.append(account_id) return account_ids ``` The block then contains a vector of optional signatures of the same or smaller size than the resulting set of `account_ids`, with each element being `None` if the approval for such account is absent, or the signature on the approval message if it is present. It's easy to show that the actual approvals that were signed by the block producers can easily be reconstructed from the information available in the block, and thus the signatures can be verified. If the vector of signatures is shorter than the length of `account_ids`, the remaining signatures are assumed to be `None`. ## Messages On receipt of the approval message the participant just stores it in the collection of approval messages. ```python def on_approval(self, approval): self.approvals.append(approval) ``` Whenever a participant receives a block, the operations relevant to the consensus include updating the `head` and initiating a timer to start sending the approvals on the block to the block producers at the consecutive `target_height`s. The timer delays depend on the height of the last final block, so that information is also persisted. ```python def on_block(self, block): header = block.header if header.height <= self.head_height: return last_final_block = store.get_block(header.last_final_block_hash) self.head_height = header.height self.head_hash = block.hash() self.largest_final_height = last_final_block.height self.timer_height = self.head_height + 1 self.timer_started = time.time() self.endorsement_pending = True ``` The timer needs to be checked periodically, and contain the following logic: ```python def get_delay(n): min(MAX_DELAY, MIN_DELAY + DELAY_STEP * (n-2)) def process_timer(self): now = time.time() skip_delay = get_delay(self.timer_height - self.largest_final_height) if self.endorsement_pending and now > self.timer_started + ENDORSEMENT_DELAY: if self.head_height >= self.largest_target_height: self.largest_target_height = self.head_height + 1 self.send_approval(head_height + 1) self.endorsement_pending = False if now > self.timer_started + skip_delay: assert not self.endorsement_pending self.largest_target_height = max(self.largest_target_height, self.timer_height + 1) self.send_approval(self.timer_height + 1) self.timer_started = now self.timer_height += 1 def send_approval(self, target_height): if target_height == self.head_height + 1: inner = Endorsement(self.head_hash) else: inner = Skip(self.head_height) approval = Approval(inner, target_height) send(approval, to_whom = get_block_proposer(self.head_hash, target_height)) ``` Where `get_block_proposer` returns the next block proposer given the previous block and the height of the next block. It is also necessary that `ENDORSEMENT_DELAY < MIN_DELAY`. Moreover, while not necessary for correctness, we require that `ENDORSEMENT_DELAY * 2 <= MIN_DELAY`. ## Block Production We first define a convenience function to fetch approvals that can be included in a block at particular height: ```python def get_approvals(self, target_height): return [approval for approval in self.approvals if approval.target_height == target_height and (isinstance(approval.inner, Skip) and approval.prev_height == self.head_height or isinstance(approval.inner, Endorsement) and approval.prev_hash == self.head_hash)] ``` A block producer assigned for a particular height produces a block at that height whenever they have `get_approvals` return approvals from block producers whose stake collectively exceeds 2/3 of the total stake. ## Finality condition A block $B$ is final in $\operatorname{chain}(T)$, where $T \ge B$, when either $B = G$ or there is a block $X \le T$ such that $B = \operatorname{prev}(\operatorname{prev}(X))$ and $\operatorname{h}(X) = \operatorname{h}(\operatorname{prev}(X))+1 = \operatorname{h}(B)+2$. That is, either $B$ is the genesis block, or $\operatorname{chain}(T)$ includes at least two blocks on top of $B$, and these three blocks ($B$ and the two following blocks) have consecutive heights. ## Epoch switches There's a parameter $\operatorname{epoch\_ length} \ge 3$ that defines the minimum length of an epoch. Suppose that a particular epoch $e_{cur}$ started at height $h$, and say the next epoch will be $e_{next}$. Say $\operatorname{BP}(e)$ is a set of block producers in epoch $e$. Say $\operatorname{last\_ final}(T)$ is the highest final block in $\operatorname{chain}(T)$. The following are the rules of what blocks contain approvals from what block producers, and belong to what epoch. - Any block $B$ with $\operatorname{h}(\operatorname{prev}(B)) < h+\operatorname{epoch\_ length}-3$ is in the epoch $e_{cur}$ and must have approvals from more than $^2\!/_3$ of $\operatorname{BP}(e_{cur})$ (stake-weighted). - Any block $B$ with $\operatorname{h}(\operatorname{prev}(B)) \ge h+\operatorname{epoch\_ length}-3$ for which $\operatorname{h}(\operatorname{last\_ final}(\operatorname{prev}(B))) < h+\operatorname{epoch\_ length}-3$ is in the epoch $e_{cur}$ and must logically include approvals from both more than $^2\!/_3$ of $\operatorname{BP}(e_{cur})$ and more than $^2\!/_3$ of $\operatorname{BP}(e_{next})$ (both stake-weighted). - The first block $B$ with $\operatorname{h}(\operatorname{last\_ final}(\operatorname{prev}(B))) >= h+\operatorname{epoch\_ length}-3$ is in the epoch $e_{next}$ and must logically include approvals from more than $^2\!/_3$ of $\operatorname{BP}(e_{next})$ (stake-weighted). (see the definition of *logically including* approvals in [approval requirements](#approvals-requirements)) ## Safety Note that with the implementation above a honest block producer can never produce two endorsements with the same `prev_height` (call this condition *conflicting endorsements*), neither can they produce a skip message `s` and an endorsement `e` such that `s.prev_height < e.prev_height and s.target_height >= e.target_height` (call this condition *conflicting skip and endorsement*). **Theorem** Suppose that there are blocks $B_1$, $B_2$, $T_1$ and $T_2$ such that $B_1 \nsim B_2$, $\operatorname{final}(B_1, T_1)$ and $\operatorname{final}(B_2, T_2)$. Then, more than $^1\!/_3$ of the block producer in some epoch must have signed either conflicting endorsements or conflicting skip and endorsement. **Proof** Without loss of generality, we can assume that these blocks are chosen such that their heights are smallest possible. Specifically, we can assume that $\operatorname{h}(T_1) = \operatorname{h}(B_1)+2$ and $\operatorname{h}(T_2) = \operatorname{h}(B_2)+2$. Also, letting $B_c$ be the highest block that is an ancestor of both $B_1$ and $B_2$, we can assume that there is no block $X$ such that $\operatorname{final}(X, T_1)$ and $B_c < X < B_1$ or $\operatorname{final}(X, T_2)$ and $B_c < X < B_2$. **Lemma** There is such an epoch $E$ that all blocks $X$ such that $B_c < X \le T_1$ or $B_c < X \le T_2$ include approvals from more than $^2\!/_3$ of the block producers in $E$. **Proof** There are two cases. Case 1: Blocks $B_c$, $T_1$ and $T_2$ are all in the same epoch. Because the set of blocks in a given epoch in a given chain is a contiguous range, all blocks between them (specifically, all blocks $X$ such that $B_c < X < T_1$ or $B_c < X < T_2$) are also in the same epoch, so all those blocks include approvals from more than $^2\!/_3$ of the block producers in that epoch. Case 2: Blocks $B_c$, $T_1$ and $T_2$ are not all in the same epoch. Suppose that $B_c$ and $T_1$ are in different epochs. Let $E$ be the epoch of $T_1$ and $E_p$ be the preceding epoch ($T_1$ cannot be in the same epoch as the genesis block). Let $R$ and $S$ be the first and the last block of $E_p$ in $\operatorname{chain}(T_1)$. Then, there must exist a block $F$ in epoch $E_p$ such that $\operatorname{h}(F)+2 = \operatorname{h}(S) < \operatorname{h}(T_1)$. Because $\operatorname{h}(F) < \operatorname{h}(T_1)-2$, we have $F < B_1$, and since there are no final blocks $X$ such that $B_c < X < B_1$, we conclude that $F \le B_c$. Because there are no epochs between $E$ and $E_p$, we conclude that $B_c$ is in epoch $E_p$. Also, $\operatorname{h}(B_c) \ge \operatorname{h}(F) \ge \operatorname{h}(R)+\operatorname{epoch\_ length}-3$. Thus, any block after $B_c$ and until the end of $E$ must include approvals from more than $^2\!/_3$ of the block producers in $E$. Applying the same argument to $\operatorname{chain}(T_2)$, we can determine that $T_2$ is either in $E$ or $E_p$, and in both cases all blocks $X$ such that $B_c < X \le T_2$ include approvals from more than $^2\!/_3$ of block producers in $E$ (the set of block producers in $E$ is the same in $\operatorname{chain}(T_1)$ and $\operatorname{chain}(T_2)$ because the last block of the epoch preceding $E_p$, if any, is before $B_c$ and thus is shared by both chains). The case where $B_c$ and $T_1$ are in the same epoch, but $B_c$ and $T_2$ are in different epochs is handled similarly. Thus, the lemma is proven. Now back to the theorem. Without loss of generality, assume that $\operatorname{h}(B_1) \le \operatorname{h}(B_2)$. On the one hand, if $\operatorname{chain}(T_2)$ doesn't include a block at height $\operatorname{h}(B_1)$, then the first block at height greater than $\operatorname{h}(B_1)$ must include skips from more than $^2\!/_3$ of the block producers in $E$ which conflict with endorsements in $\operatorname{prev}(T_1)$, therefore, more than $^1\!/_3$ of the block producers in $E$ must have signed conflicting skip and endorsement. Similarly, if $\operatorname{chain}(T_2)$ doesn't include a block at height $\operatorname{h}(B_1)+1$, more than $^1\!/_3$ of the block producers in $E$ signed both an endorsement in $T_1$ and a skip in the first block in $\operatorname{chain}(T_2)$ at height greater than $\operatorname{h}(T_1)$. On the other hand, if $\operatorname{chain}(T_2)$ includes both a block at height $\operatorname{h}(B_1)$ and a block at height $\operatorname{h}(B_1)+1$, the latter must include endorsements for the former, which conflict with endorsements for $B_1$. Therefore, more than $^1\!/_3$ of the block producers in $E$ must have signed conflicting endorsements. Thus, the theorem is proven. ## Liveness See the proof of liveness in [Doomslug Whitepaper](https://discovery-domain.org/papers/doomslug.pdf) and the recent [Nightshade](https://discovery-domain.org/papers/nightshade.pdf) sharding protocol. The consensus in this section differs in that it requires two consecutive blocks with endorsements. The proof in the linked paper trivially extends, by observing that once the delay is sufficiently long for a honest block producer to collect enough endorsements, the next block producer ought to have enough time to collect all the endorsements too. ## Approval condition The approval condition above > Any valid block must logically include approvals from block producers whose cumulative stake exceeds 2/3 of the total stake in the epoch. For a block `B` and its previous block `B'` each approval in `B` must be an `Endorsement` with the hash of `B'` if and only if `B.height == B'.height + 1`, otherwise it must be a `Skip` with the height of `B'` Is more complex that desired, and it is tempting to unify the two conditions. Unfortunately, they cannot be unified. It is critical that for endorsements each approval has the `prev_hash` equal to the hash of the previous block, because otherwise the [safety proof](#safety) above doesn't work, in the second case the endorsements in `B1` and `Bx` can be the very same approvals. It is critical that for the skip messages we do **not** require the hashes in the approvals to match the hash of the previous block, because otherwise a malicious actor can create two blocks at the same height, and distribute them such that half of the block producers have one as their head, and the other half has the other. The two halves of the block producers will be sending skip messages with different `prev_hash` but the same `prev_height` to the future block producers, and if there's a requirement that the `prev_hash` in the skip matches exactly the `prev_hash` of the block, no block producer will be able to create their blocks.
NEAR Foundation and ARterra Labs Level Up Gaming Fandom for the Open Web NEAR FOUNDATION May 31, 2023 The ever-expanding gaming landscape faces significant challenges such as engagement and identity fragmentation. As fans navigate platforms like Twitch, Discord, and YouTube, brands and creators struggle to monetize their fan bases effectively. This is where ARterra Labs steps in — a company on a mission to revolutionize fan engagement and unlock Web3 fandom for the gaming industry. ARterra Labs aims to transform fan engagement in gaming by integrating its innovative Web3 solutions into existing Web2 ecosystems. Bridging the gap between platforms and simplifying monetization, ARterra Labs is set to attract millions of gamers through strategic partnerships and an ambitious plan to onboard over 5 million users, positioning itself as a game-changer in the industry. As ARterra Labs redefines gaming engagement, the NEAR Foundation’s blockchain technology will play a crucial role, powering ARterra’s innovative solutions such as the credential-based fan passport and the Battle Pass system. How ARterra’s Battle Pass is energizing Web3 gaming ARterra Labs deploys three distinct products aimed at transforming the gaming landscape. With a credential-based fan passport, they offer a secure platform for fans to exhibit their unique identities and interests. In addition, they introduce metaverse experiences, allowing fans to interact, engage, and form deeper bonds with their favorite franchises. Completing the trifecta is the Battle Pass system, a tiered reward structure that gamifies fan engagement, incentivizing both participation and loyalty. ARterra Labs’ metaverse experiences immerse fans in virtual worlds where they can interact, engage, and connect with their favorite franchises. And the Battle Pass system gamifies fan engagement with a tiered reward system, incentivizing participation and loyalty. Central to ARterra’s strategy, the Battle Pass is a reward system on the NEAR blockchain, connecting to other chains via the BOS and LayerZero. It propels NFT liquidity within the NEAR ecosystem and unites gaming communities across networks. By rewarding active engagement, Battle Pass bolsters user loyalty and underscores NEAR’s role in settling cross-chain gaming transactions. Together, these three products serve as the foundation for ARterra Labs’ Experience Hub — an open-source marketplace that enables the creation of User-Generated Content (UGC) experiences for distribution to their extensive network. ARterra’s User-Generated Content (UGC) — primarily enabled through Fortnite’s Creative mode — serves as another cornerstone to its success, already captivating over 46 million gamers and maintaining a steady base of 500,000 monthly players. User experience and seamless onboarding play a critical role in ushering these gamers into the Web3 ecosystem. Key alliances with industry leaders like Complexity Gaming and GRID Esports’ Champion of Champions Tournament (CCT) further reinforce ARterra’s prominence. ARterra’s market strategy is twofold. Initially, it centers on activating Web3 fandom, using user-generated content effectively, and fostering unity in the gaming community. The second focus involves collaborating with premier Web3 gaming entities, offering gamer incentives, and constantly refining these tactics with data insights. Reshaping gaming for an open web Blending NEAR’s fast and scalable blockchain with ARterra’s innovative approach to gaming, the partnership is set to bring about radical improvements to the Web3 gaming experience. ARterra’s unique tools like the Discord-native tournament platform and the Battle Pass will foster enhanced interactions between gamers, developers, and brands. The alliance, cemented by a 12-month agreement that’s extendable indefinitely, emphasizes the faith NEAR Foundation is placing in ARterra’s potential. This cooperative venture bolsters NEAR’s position as the gaming fandom’s settlement layer across multiple chains while also ensuring priority access for NEAR ecosystem games to ARterra’s platform. It’s also a win-win for both players and builders. Gamers gain an immersive environment where rewards and exclusive content are the norm. Developers are offered a supportive platform, underpinned by the NEAR BOS and protocol, while brands can tap into a vibrant, engaged, and diverse audience. With ARterra Labs and NEAR Foundation’s shared vision, the focus will be on expanding and refining gaming platforms to attract more users, developers, and partners. The two will be dedicated to adding value within the gaming community, setting the stage for a significant growth spurt in the NEAR and Web3 gaming ecosystems alike. Amplifying the open web gaming journey with Battle Pass, metaverse realities, and the fan passport, ARterra Labs and NEAR Foundation don’t merely enhance the experience — they define a new standard. It’s a game-changing era in Web3 and fans are just barely unlocking the first level.
--- id: near-lake-state-changes-indexer title: NEAR Lake Indexer Tutorial --- :::note Source code for the tutorial [`near-examples/near-lake-accounts-watcher`](https://github.com/near-examples/near-lake-accounts-watcher/tree/0.2.0): source code for a video tutorial on how to use the NEAR Lake Framework ::: :::info Version 0.2.0 The video is based on the [`near-lake-framework`](/concepts/advanced/near-lake-framework) version 0.2.0 At the same time we're keeping the source code up to date with the latest version of the published crate. ::: We've created a video tutorial to empower the release announcement of [NEAR Lake Framework](/concepts/advanced/near-lake-framework). In this tutorial you will build an indexer application to watch for any `StateChange`s affecting the account or a list of account provided. <iframe width="560" height="315" src="https://www.youtube.com/embed/GsF7I93K-EQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe>
Aurora launches on NEAR Protocol COMMUNITY May 12, 2021 Aurora Provides an Ethereum Layer-2 Experience The explosive growth of DeFi and NFTs frequently causes surges in Ethereum gas prices––a problem that economically limits the participation of many users, and prevents dApp developers from scaling their businesses to their full potential. To address these challenges, we’re proud to announce the mainnet release of Aurora, a turnkey solution for developers seeking to extend their dApps to reach additional markets. Aurora runs on NEAR Protocol and takes advantage of its many unique features, including sharding and developer gas fee remuneration. Aurora consists of two core components: the Aurora Engine runtime, which allows for the seamless deployment of Solidity and Vyper smart contracts, and the Aurora Bridge (based on the Rainbow Bridge technology), providing for the permissionless transfer of tokens and data between Ethereum and Aurora. Aurora provides a number of enhancements for developers: Aurora fees are up to 1,000x lower than Ethereum’s. For example, the cost of transferring a ERC-20 token is below $0.01, while for Ethereum (at 50 Gwei and an ETH price of $3,000), it’s around $5.40. Aurora is able to host thousands of transactions per second, representing an increase of 50x compared to Ethereum 1.0. Aurora transaction finality inherits from the underlying NEAR Protocol, i.e. two NEAR blocks, or approximately two seconds—substantially lower even than a single block confirmation time of 13 seconds in Ethereum (which is not enough for transaction finality). Also, fast finality of NEAR blockchain reduces significantly the risk of frontrunning attacks. Ecosystem growth on Aurora is future-proof: the sharding approach of the underlying NEAR Protocol provides for horizontal EVM scaling, with asynchronous communication between multiple Aurora shards. Aurora offers a greener option for Ethereum users: full, uncompromising Ethereum compatibility on top of the decentralised and climate-neutral Proof-of-Stake L1 NEAR Protocol. Aurora solves the current and future computational challenges of the Ethereum ecosystem, while preserving the existing engineering investment in both smart contracts and front-end code. Aurora architecture Aurora is implemented as a smart contract on the NEAR blockchain. What does this mean? Aurora can benefit from all current and future advantages of NEAR blockchain Simplification of the early-stage maintenance, upgrade, and governance of Aurora, enabling rapid response times in case of emergency such as the discovery of security vulnerabilities. Soon after launch, the plan is to make use of SputnikDAO version 2, a customizable DAO-based governance framework on NEAR, to launch AuroraDAO for ecosystem governance. The current architecture of Aurora looks as follows: The Aurora smart contract implements two main interfaces: Execution and Token. The Execution interface allows users to send ordinary Ethereum transactions (for example, created with MetaMask, ethers.js or web3.py). Underneath, these transactions get decoded (RLP), verified (secp256k1), and executed in the EVM runtime (Sputnik VM). Some operations allowed in the EVM runtime may be moved to the NEAR Protocol level (and thus become precompiles) in case a smart contract does not deliver the target performance. For example, there is currently a scheduled NEAR Protocol upgrade, which will include an extended Math API. Aurora also allows for permissionless token bridging. It uses the Rainbow Bridge technology for transfers from Ethereum and internal NEAR token transfers to allow for NEAR-native assets to be transferred to Aurora. Thus Aurora becomes a point of connection for Ethereum and NEAR economies. In case of the need for additional precompiles, a protocol upgrade will be proposed to NEAR validators. The information on the required precompiles will be collected once sufficient load testing has been performed. As per the outcome of the discussion on the Aurora base token, the EVM runtime will maintain native balances in Ether (ETH). This means that a user should move their ETH over the Aurora Bridge before sending any other transactions. In order not to confuse users, the team decided that the Aurora contract will implement a fungible token interface, which will represent the user’s ETH balance in both the NEAR base runtime and the Aurora runtime. Users should be able to withdraw and deposit ETH to NEAR, and this will be implemented as a separate bridge connector interface, which underneath will speak to the core bridge contracts. This became possible due to the extensible and permissionless nature of the Rainbow Bridge protocol (see more on the bridge architecture here). The code for the Aurora contract and adjacent tools can be found in the Aurora organisation on Github. Using ETH to pay for gas fees on Aurora One of the most notable design decisions is the use of ETH as the base currency within Aurora, for the payment of transaction fees. While a lot of the Ethereum layer 2s require users and developers to acquire the L2’s native tokens, Aurora wants to offer a straightforward, seamless experience for users and developers from the Ethereum community. The approach is the following: To understand the ETH gas price in the Aurora runtime, a standard JSON-RPC endpoint `eth_gasPrice` is used. The returned value will be used for the future ETH payment to the RPC node (see step 6). A user signs an ordinary Ethereum transaction with their familiar tools (MetaMask, Wallet Connect compatible wallet, CLI, JS libraries, etc.) and sends it to the RPC. The RPC wraps the Ethereum transaction into a NEAR transaction and sends it to the Aurora contract. On the protocol level, the RPC signature is verified and the initial Ethereum transaction is passed to the Aurora Engine contract. The Aurora Engine contract parses the Ethereum transaction and executes it, calculating the EVM gas usage on the way. By the end of the Ethereum transaction execution, some NEAR gas is already burned (according to the rules of NEAR Protocol), while ETH gas is just a calculated number in the Aurora contract. In order to pay for the NEAR gas fee, ETH is used: the Aurora contract calculates the transaction fee and transfers it from the user account to the RPC account. This approach is viewed from the user side as just paying ETH to the protocol, while in fact it is the $NEAR token which is used for the fees, and RPC nodes acting as proxies/relayers between the user and the NEAR blockchain. As the first step, the RPC would be able to provide the ETH gas price that will be sufficient for paying for the relaying service. Moreover, based on the responses from the multiple RPC nodes, users would be able to decide which one to use. In the future, relaying services may be structured similarly to OpenGSN. Find more information on ETH as the base token in this governance forum discussion. Aurora Roadmap Besides hotfixing Aurora after its release, the team has the following major milestones in mind: Summer 2021: Uncompromising Ethereum compatibility. At the moment there are several minor updates to the NEAR Protocol that are going to be included in the next protocol upgrade, so as to enable Aurora to achieve 100% compatibility with Ethereum 1.0. DAO formation. We believe that the only way forward with projects like Aurora is to implement a truly decentralised governance and upgradability approach. Accordingly, we’re going to establish a DAO to govern Aurora. [Potential] token inception. Once the DAO forms, there will be a decision regarding the creation of an Aurora token. Discussions will happen over the summer. Autumn 2021: Fast token transfers. Because of the limitations of the Ethereum blockchain (high transaction fees, slow finality of transactions, and the absence of EIP-665), transfers over the Rainbow Bridge in the direction of Ethereum are currently slow: it can take up to 16 hours for a transfer from NEAR to Ethereum. We are going to solve this problem for fungible token transfers. Simplified “Hide the Blockchain” Experience. The advanced account model of NEAR Protocol enables seamless interaction with the blockchain even for users who aren’t familiar with crypto UX elements like wallets and additional software. In fact, there’s a way to completely hide the blockchain details from the end user. We plan to introduce a similar logic to Aurora. Gas fee denominated in ERC-20s. The way the Aurora RPC works gives us an ability to naturally propose to the user to pay the transaction fee with any ERC-20 token. In other words, users could pay their transaction fee in USDT or DAI. 2022: Horizontal scaling. The major feature of the NEAR Protocol is sharding and the ability to dynamically scale the blockchain. Our end goal is to deliver this functionality to the Ethereum ecosystem through enabling sharding for Aurora. Try Aurora Today With low costs, best-in-class transaction finality, and scalability, Aurora redefines what is possible in the Ethereum ecosystem while also expanding NEAR’s ecosystem to welcome and accommodate EVM-based applications. With Aurora, Ethereum users can work with familiar applications while benefiting from the efficiency of NEAR; as the transaction cost is several orders of magnitude cheaper than that of Ethereum, Aurora removes a steep financial barrier to entry for users and developers––especially newcomers to the ecosystem. Our goal is to create an interoperable future where the gaps between blockchains, developers, and users are bridged. Aurora does just that by allowing for a seamless user experience and allowing assets to pass uninterrupted between the Ethereum and NEAR blockchains. Merging crypto-economies can facilitate the development of creator communities that will bring this technology to the mainstream. Aurora is fully compatible with Ethereum 1.0, including base fees paid in ETH and out-of-the-box operability with all existing wallets and other tools. To start using Aurora, please visit https://aurora.dev. — Join the Aurora community via our official Telegram group, Developer Telegram group, Support Telegram group, and follow us on Twitter. Disclaimer: This article is provided for informational purposes only. It is not intended to be used as legal, tax, investment, financial, or other advice.
Case Study: Satori’s Jeff Bissinger Talks NEAR Tasks for the Gig Economy CASE STUDIES July 31, 2023 NEAR is a home to a number of amazing apps and projects. These developers, founders, and entrepreneurs are using NEAR to effortlessly create and distribute innovative decentralized apps, while helping build a more open web — free from centralized platforms. In these Case Study videos, NEAR Foundation showcases some of these projects. In the latest NEAR Foundation Case Study video, we hear from Jeff Bissinger, Product Manager at Satori. As a product team building innovative Web3 solutions, Satori is creating AI integrations that enable people to work with purpose. NEAR Tasks, which launched at Consensus 2023 in Austin, is one of Satori’s latest products. In this case study video, Jeff Bissinger takes viewers on a trip into NEAR Tasks — Satori’s effort to blend the gig economy with blockchain technology. With NEAR Tasks, users can earn $NEAR while completing simple, yet meaningful, AI related tasks
--- id: welcome title: Examples & Tutorials sidebar_label: Home hide_table_of_contents: true --- import {FeatureList, Column, Feature} from "@site/src/components/featurelist" Explore our collection of Examples and Tutorials <FeatureList> <Column title="Popular Examples"> <Feature url="/tutorials/examples/guest-book" title="Guest Book" subtitle="Create a simple guest book" image="guest-book.png" /> <Feature url="/tutorials/examples/donation" title="Donation" subtitle="Receive and send tokens" image="donation.png" /> <Feature url="/tutorials/examples/xcc" title="Basic Cross-Contract Call" subtitle="Learn how to call other contracts" image="cross-call.png" /> <Feature url="/tutorials/examples/coin-flip" title="Coin Flip Game" subtitle="Learn to create basic random numbers" image="random.png" /> <Feature url="/tutorials/examples/factory" title="Factory Contract" subtitle="Build a contract that deploys contracts" image="factory.png" /> <Feature url="/tutorials/examples/update-contract-migrate-state" title="Update & Migrate" subtitle="Programmatically update contracts" image="update.png" /> <Feature url="/tutorials/examples/frontend-multiple-contracts" title="Multi-Contract Frontend" subtitle="Interact with multiple contracts" image="multiple.png" /> </Column> <Column title="Popular Tutorials"> <Feature url="/tutorials/near-components/interaction" title="Components & Contracts" subtitle="Use a contract from your component" image="bos-contract.png" /> <Feature url="/tutorials/near-components/lido" title="ETH Component" subtitle="Build an Ethereum Component" image="bos-lido.png" /> <Feature url="/tutorials/nfts/minting-nfts" title="NFT Mint" subtitle="Mint an NFT without using code" image="frontend-bos.png" /> <Feature url="/tutorials/near-components/indexer-tutorials/nft-indexer" title="Events (NEAR Lake)" subtitle="Use our Data Lake to listen for events" image="monitor.png" /> </Column> <Column title="From Zero to Hero"> <Feature url="/tutorials/nfts/js/introduction" title="Master NFTs on NEAR (JS)" subtitle="Learn everything about NFT in JS" image="nft-marketplace-js.png" /> <Feature url="/tutorials/nfts/introduction" title="Master NFTs on NEAR (RS)" subtitle="Learn everything about NFT in Rust" image="nft-marketplace-rs.png" /> <Feature url="/tutorials/fts/introduction" title="Fungible Tokens 101" subtitle="Learn everything about fungible tokens" image="ft.png" /> <Feature url="/tutorials/crosswords/basics/overview" title="Crossword Game" subtitle="Build a Crossword Game from zero" image="crossword.png" /> </Column> </FeatureList>
--- id: primitives title: NEAR Lake Primitive Types sidebar_label: Lake Primitive Types --- # NEAR Lake Primitive Types This article contains the primitive types used by the [NEAR Lake Framework package](https://www.npmjs.com/package/@near-lake/framework). These types are used to define the data structures used by the framework as well as provide some popular helper functions. ## `Block` :::info Important Notes on `Block` - All the entities located on different shards were merged into one single list without differentiation. - `Block` is not the fairest name for this structure either. NEAR Protocol is a sharded blockchain, so its block is actually an ephemeral structure that represents a collection of real blocks called chunks in NEAR Protocol. ::: ### `Block` Structure Definition The `Block` type is used to represent a block in the NEAR Lake Framework. It is comprised by the following structure: ```ts export class Block { constructor( readonly streamerMessage: StreamerMessage, private executedReceipts: Receipt[], readonly postponedReceipts: Receipt[], readonly transactions: Transaction[], private _actions: Map<string, Action>, private _events: Map<string, Event[]>, private _stateChanges: StateChange[]) { } ... // helper methods and getters omitted for brevity } ``` #### `streamerMessage` Low-level structure for backward compatibility. As implemented in previous versions of [`near-lake-framework`](https://www.npmjs.com/package/near-lake-framework). #### `postponedReceipts` Receipts included on the chain but not executed yet marked as “postponed”: they are represented by the same structure `Receipt` (see the corresponding section in this doc for more details). #### `transactions` List of included `Transactions`, converted into `Receipts`. :::info Heads up! **Note:** You might want to know about `Transactions` to know where the action chain has begun. Unlike Ethereum, where a Transaction contains everything you may want to know about a particular interaction on the Ethereum blockchain, Near Protocol because of its asynchronous nature converts a `Transaction` into a `Receipt` before executing it. Thus, On NEAR, `Receipts` are more important for figuring out what happened on-chain as a result of a Transaction signed by a user. Read more about [Transactions on Near](https://nomicon.io/RuntimeSpec/Transactions) here. ::: ### `Block` Helper Methods ```ts export class Block { ... // constructor omitted for brevity get blockHash(): string {} get prevBlockHash(): string {} get blockHeight(): number {} header(): BlockHeader {} receipts(): Receipt[] {} actions(): Action[] {} events(): Event[] {} stateChanges(): StateChange[] {} actionByReceiptId(receipt_id: string): Action | undefined {} eventsByReceiptId(receipt_id: string): Event[] {} eventsByAccountId(account_id: string): Event[] {} private buildActionsHashmap() {} private buildEventsHashmap(): Map<string, Event[]> {} static fromStreamerMessage(streamerMessage: StreamerMessage): Block {} } ``` #### `blockHash` Returns the block hash. A shortcut to get the data from the block header. #### `prevBlockHash` Returns the previous block hash. A shortcut to get the data from the block header. #### `blockHeight` Returns the block height. A shortcut to get the data from the block header. #### `header(): BlockHeader` Returns a `BlockHeader` structure of the block See `BlockHeader` structure sections for details. #### `receipts(): Receipt[]` Returns a slice of `Receipts` executed in the block. Basically is a getter for the `executedReceipts` field. #### `actions(): Action[]` Returns an Array of `Actions` executed in the block. #### `events(): Event[]` Returns `Events` emitted in the block. #### `stateChanges(): StateChange[]` Returns an Array of `StateChange` occurred in the block. #### `actionByReceiptId(receipt_id: string): Action | undefined` Returns `Action`s of the provided `receipt_id` from the block if any. Returns `undefined` if there is no corresponding `Action`. This method uses the internal `Block` `action` field which is empty by default and will be filled with the block’s actions on the first call to optimize memory usage. The result is either `Action | undefined` since there might be a request for an `Action` by `receipt_id` from another block, in which case this method will be unable to find the `Action` in the current block. In the other case, the request might be for an `Action` for a `receipt_id` that belongs to a `DataReceipt` where an action does not exist. #### `eventsByReceiptId(receipt_id: string): Event[]` Returns an Array of Events emitted by `ExecutionOutcome` for the given `receipt_id`. There might be more than one `Event` for the `Receipt` or there might be none of them. In the latter case, this method returns an empty Array. #### `eventsByAccountId(account_id: string): Event[]` Returns an Array of Events emitted by `ExecutionOutcome` for the given `account_id`. There might be more than one `Event` for the `Receipt` or there might be none of them. In the latter case, this method returns an empty Array. --- ## `BlockHeader` Replacement for `BlockHeaderView` from `near-primitives`. Shrunken and simplified. :::note The original `BlockHeaderView` is still accessible via the `.streamerMessage` attribute. ::: ### `BlockHeader` Structure Definition ```ts export class BlockHeader { constructor( readonly height: number, readonly hash: string, readonly prevHash: string, readonly author: string, readonly timestampNanosec: string, readonly epochId: string, readonly nextEpochId: string, readonly gasPrice: string, readonly totalSupply: string, readonly latestProtocolVersion: number, readonly randomValue: string, readonly chunksIncluded: number, readonly validatorProposals: ValidatorStakeView[]) { } ... // helper method omitted for brevity } ``` --- ## `Receipt` This field is a simplified representation of the `ReceiptView` structure from `near-primitives`. ### `Receipt` Structure Definition ```ts export class Receipt implements Events { constructor( readonly receiptKind: ReceiptKind, readonly receiptId: string, readonly receiverId: string, readonly predecessorId: string, readonly status: ExecutionStatus, readonly executionOutcomeId?: string | undefined, readonly logs: string[] = []) { } ... // helper methods omitted for brevity } ``` ### `Receipt` Fields #### `receiptKind` Defined the type of the `Receipt`: `Action` or `Data` representing the `ActionReceipt` and `DataReceipt`. #### `receiptId` The ID of the `Receipt` of the `CryptoHash` type. #### `receiverId` The receiver account id of the `Receipt`. #### `predecessorId` The predecessor account id of the `Receipt`. #### `status` Represents the status of `ExecutionOutcome` of the `Receipt`. See the `ExecutionStatus` enum section for the details. #### `executionOutcomeId` The id of the `ExecutionOutcome` for the `Receipt`. Returns `null` if the `Receipt` isn’t executed yet and has a postponed status. #### `logs` The original logs of the corresponding `ExecutionOutcome` of the `Receipt`. Note: not all of the logs might be parsed as JSON Events (`Events`). ### `Receipt` Helper Methods ```ts export class Receipt { ... // constructor omitted for brevity get events(): Event[] {} static fromOutcomeWithReceipt(outcomeWithReceipt: OutcomeWithReceipt): Receipt {} } ``` #### `Receipt.events(): Events[]` Returns an Array of `Events` for the `Receipt`, if any. This might be empty if the `logs` field is empty or doesn’t contain JSON Events compatible log records. --- ## `Event` This structure is an ephemeral entity to provide access to the [Events Standard](https://github.com/near/NEPs/blob/master/neps/nep-0297.md) structure and keep data about the related `Receipt` for convenience. ### Interface for Capturing Data About an Event in `handleStreamerMessage()` The interface to capture data about an event has the following arguments: - `standard`: name of standard, e.g. nep171 - `version`: e.g. 1.0.0 - `event`: type of the event, e.g. nft_mint - `data`: associate event data. Strictly typed for each set `{standard, version, event}` inside corresponding NEP ### `Event` Structure Definition ```ts export class Event { constructor( readonly relatedReceiptId: string, readonly rawEvent: RawEvent) { } ... // helper methods omitted for brevity } ``` ### `Event` Methods ```ts export class Event { ... // constructor omitted for brevity static fromLog(log: string): Event {} } ``` --- ## `Transaction` A representation of the `IndexerTransactionWithOutcome` from `near-indexer-primitives` which is an ephemeral structure combining `SignedTransactionView` from `near-primitives` and `IndexerExecutionOutcomeWithOptionalReceipt` from `near-indexer-primitives`. This structure is very similar to `Receipt`. Unlike `Receipt`, a `Transaction` has a few additional fields like `signerId`, `signature`, and `operations`. ### `Transaction` Structure Definition ```ts export class Transaction { constructor( readonly transactionHash: string, readonly signerId: string, readonly signerPublicKey: string, readonly signature: string, readonly receiverId: string, readonly status: ExecutionStatus, readonly executionOutcomeId: string, readonly operations: Operation[]) { } } ``` #### `Transaction.transactionHash` Returns the hash of the `Transaction` in `CryptoHash`. #### `Transaction.signerId` Returns the signer account id of the `Transaction`. #### `Transaction.signerPublicKey` Returns the `PublicKey` of the signer of the `Transaction`. #### `Transaction.signature` Returns the `Signature` the `Transaction` was signed with. #### `Transaction.receiverId` Returns the receiver account id of the `Transaction`. #### `Transaction.status` Returns the status of the `Transaction` as `ExecutionStatus`. #### `Transaction.executionOutcomeId` Returns the id of the `ExecutionOutcome` for the `Transaction`. #### `Transaction.operations` Returns an Array of `Operation` for the `Transaction`. --- ## `StateChange` This structure is almost an identical copy of the `StateChangeWithCauseView` from `near-primitives` with a propagated additional field `affectedAccountId`. ### `StateChange` Structure Definition ```ts export class StateChange { constructor( readonly cause: StateChangeCause, readonly value: StateChangeValue ) {} get affectedAccountId(): string {} static fromStateChangeView(stateChangeView: StateChangeWithCauseView) {} } ``` #### `StateChange.cause` Returns the `cause` of the `StateChange`. #### `StateChange.value` Returns the `value` of the `StateChange`. #### `StateChange.affectedAccountId(): string` Returns the account id of the `StateChange`. #### `StateChange.fromStateChangeView(stateChangeView: StateChangeWithCauseView): StateChange` Returns the `StateChange` from the `StateChangeWithCauseView`. Created for backward compatibility.
Case Study: Sweat Economy’s Oleg Fomenko on Reshaping Fitness with Move-to-Earn NEAR FOUNDATION June 12, 2023 NEAR is a home to a number of amazing apps and projects. These developers, founders, and entrepreneurs are using NEAR to effortlessly create and distribute innovative decentralized apps, while helping build a more open web — free from centralized platforms. In recent installments, NEAR Foundation explored the BOS with Pagoda’s Chief Product Officer Alex Chiocchi, and heard from OnMachina co-founder Jonathan Bryce on building decentralized storage. In the latest case study, Sweat Economy founder Oleg Fomenko talks about revolutionizing fitness with blockchain technology. Aside from talking about Sweat Economy’s integration with NEAR, Fomenko also talks about integrating the Sweat Wallet app with the BOS. With over 6 million active users, the Sweat Wallet is the most active dApp on NEAR. Watch the Sweat Economy Case Study video below. Sweat Economy’s Learn & Earn program brings in over 200,000 users As part of its partnership with NEAR Foundation, Sweat Economy launched its Learn & Earn feature in the Sweat Wallet to educate users about Stablecoins and promote USDT on NEAR in the Sweat Wallet. In Sweat Economy’s Learn & Earn Program, which ran from May 23-31, Sweat Wallet users were rewarded with 1 USDT by completing the “What are Stablecoins?” lesson and an interactive quiz. In total, 100,000 USDT was given out as rewards in this initiative. In just 9 Days: 245,048+ users started the lesson 218,789 users completed the lesson: 218,789 130,068 users completed the lesson & quiz: 100,000+ users were rewarded with 1 USDT (by completing the lesson and passing the quiz within 6 attempts)
# Fungible Token Metadata ## [NEP-148](https://github.com/near/NEPs/blob/master/neps/nep-0148.md) Version `1.0.0` ## Summary [summary]: #summary An interface for a fungible token's metadata. The goal is to keep the metadata future-proof as well as lightweight. This will be important to dApps needing additional information about an FT's properties, and broadly compatible with other tokens standards such that the [NEAR Rainbow Bridge](https://near.org/blog/eth-near-rainbow-bridge/) can move tokens between chains. ## Motivation Custom fungible tokens play a major role in decentralized applications today. FTs can contain custom properties to differentiate themselves from other tokens or contracts in the ecosystem. In NEAR, many common properties can be stored right on-chain. Other properties are best stored off-chain or in a decentralized storage platform, in order to save on storage costs and allow rapid community experimentation. As blockchain technology advances, it becomes increasingly important to provide backwards compatibility and a concept of a spec. This standard encompasses all of these concerns. Prior art: - [EIP-1046](https://eips.ethereum.org/EIPS/eip-1046) - [OpenZeppelin's ERC-721 Metadata standard](https://docs.openzeppelin.com/contracts/2.x/api/token/erc721#ERC721Metadata) also helped, although it's for non-fungible tokens. ## Guide-level explanation A fungible token smart contract allows for discoverable properties. Some properties can be determined by other contracts on-chain, or return in view method calls. Others can only be determined by an oracle system to be used on-chain, or by a frontend with the ability to access a linked reference file. ### Examples scenario #### Token provides metadata upon deploy and initialization Alice deploys a wBTC fungible token contract. **Assumptions** - The wBTC token contract is `wbtc`. - Alice's account is `alice`. - The precision ("decimals" in this metadata standard) on wBTC contract is `10^8`. **High-level explanation** Alice issues a transaction to deploy and initialize the fungible token contract, providing arguments to the initialization function that set metadata fields. **Technical calls** 1. `alice` deploys a contract and calls `wbtc::new` with all metadata. If this deploy and initialization were done using [NEAR CLI](https://docs.near.org/tools/near-cli) the command would be: ```sh near deploy wbtc --wasmFile res/ft.wasm --initFunction new --initArgs '{ "owner_id": "wbtc", "total_supply": "100000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Wrapped Bitcoin", "symbol": "WBTC", "icon": "data:image/svg+xml,%3C…", "reference": "https://example.com/wbtc.json", "reference_hash": "AK3YRHqKhCJNmKfV6SrutnlWW/icN5J8NUPtKsNXR1M=", "decimals": 8 } }' --accountId alice ``` ## Reference-level explanation A fungible token contract implementing the metadata standard shall contain a function named `ft_metadata`. ```ts function ft_metadata(): FungibleTokenMetadata {} ``` **Interface**: ```ts type FungibleTokenMetadata = { spec: string; name: string; symbol: string; icon: string|null; reference: string|null; reference_hash: string|null; decimals: number; } ``` **An implementing contract MUST include the following fields on-chain** - `spec`: a string. Should be `ft-1.0.0` to indicate that a Fungible Token contract adheres to the current versions of this Metadata and the [Fungible Token Core](./Core.md) specs. This will allow consumers of the Fungible Token to know if they support the features of a given contract. - `name`: the human-readable name of the token. - `symbol`: the abbreviation, like wETH or AMPL. - `decimals`: used in frontends to show the proper significant digits of a token. This concept is explained well in this [OpenZeppelin post](https://docs.openzeppelin.com/contracts/3.x/erc20#a-note-on-decimals). **An implementing contract MAY include the following fields on-chain** - `icon`: a small image associated with this token. Must be a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs), to help consumers display it quickly while protecting user data. Recommendation: use [optimized SVG](https://codepen.io/tigt/post/optimizing-svgs-in-data-uris), which can result in high-resolution images with only 100s of bytes of [storage cost](https://docs.near.org/concepts/storage/storage-staking). (Note that these storage costs are incurred to the token owner/deployer, but that querying these icons is a very cheap & cacheable read operation for all consumers of the contract and the RPC nodes that serve the data.) Recommendation: create icons that will work well with both light-mode and dark-mode websites by either using middle-tone color schemes, or by [embedding `media` queries in the SVG](https://timkadlec.com/2013/04/media-queries-within-svg/). - `reference`: a link to a valid JSON file containing various keys offering supplementary details on the token. Example: `/ipfs/QmdmQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm`, `https://example.com/token.json`, etc. If the information given in this document conflicts with the on-chain attributes, the values in `reference` shall be considered the source of truth. - `reference_hash`: the base64-encoded sha256 hash of the JSON file contained in the `reference` field. This is to guard against off-chain tampering. ## Drawbacks - It could be argued that `symbol` and even `name` could belong as key/values in the `reference` JSON object. - Enforcement of `icon` to be a data URL rather than a link to an HTTP endpoint that could contain privacy-violating code cannot be done on deploy or update of contract metadata, and must be done on the consumer/app side when displaying token data. - If on-chain icon uses a data URL or is not set but the document given by `reference` contains a privacy-violating `icon` URL, consumers & apps of this data should not naïvely display the `reference` version, but should prefer the safe version. This is technically a violation of the "`reference` setting wins" policy described above. ## Future possibilities - Detailed conventions that may be enforced for versions. - A fleshed out schema for what the `reference` object should contain.
Shemaroo and NEAR Foundation Accelerate Web3 Adoption in Indian Media and Entertainment NEAR FOUNDATION May 2, 2023 Shemaroo Entertainment, a prominent Indian content powerhouse with a diverse library of over 3,700 movie titles, a subscriber userbase of over 200 million people, and a vast global distribution network, is forging a strategic partnership with the NEAR Foundation to foster Web3 innovation in the media and entertainment industry — across India and beyond. The partnership also paints an even brighter picture for NEAR and the entertainment sector. With six decades of experience in Indian cinema, Shemaroo is synonymous with the Indian entertainment picture, consistently staying at the forefront of technological advancements, and adapting to the ever-changing landscape of content consumption. Sheramoo’s latest foray into Web3 and the metaverse with NEAR Foundation is the latest example. Through this collaboration, Shemaroo aims to explore the potential applications of blockchain technology by establishing a dedicated Web3 innovation cell. The cell will focus on unlocking new opportunities for decentralization, transparency, and immutability in the media and entertainment sector. With over 600 employees in Delhi, Mumbai, and New Jersey, Sheramoo’s already global reach in the entertainment industry is rapidly growing. Sheramoo’s app is also available and used in over 150 countries and counting. This extensive and expanding global presence positions Shemaroo perfectly to explore and capitalize on the potential of Web3 in entertainment — powered by the NEAR Blockchain Operating System. Shemaroo expands Web3 into Indian media Together, Shemaroo and NEAR Foundation will develop pioneering products and services that leverage Web3 and Sheramoo’s vast content library. The Web 3 innovation cell will become a breeding ground for groundbreaking ideas in how blockchain technology can reshape multiple facets of the entertainment industry. Shemaroo will take advantage of the BOS to develop scalable blockchain and smart contract services in areas like content distribution, rights management, and audience engagement. Hiren Gada, CEO of Shemaroo Entertainment, expressed enthusiasm for the partnership and the potential it holds for the future of media. “As a forward-thinking company, we are always looking for new ways to innovate and enhance our offerings to better serve our users,” says Gada “We believe that blockchain technology has the potential to unlock new possibilities and create new revenue streams for the industry.” Gada also highlighted the benefits of NEAR becoming the Blockchain Operating System (BOS), which will ease and accelerate Sheramoo’s adoption of Web3, and reduce the time to market for projects. With NEAR, Shemaroo will provide Indian entertainment enthusiasts with enhanced security, faster transaction speeds, and lower costs for all forms of content engagement. Building Shemaroo’s next-gen content on NEAR The partnership is expected to produce numerous benefits for both ecosystems. Shemaroo stands to increase brand awareness, reach new audiences, and develop fresh revenue streams while integrating cutting-edge technologies into its content. By building on NEAR, Shemaroo will be able to integrate things like NFTs and immersive metaverse experiences into both its vast existing library and future content. Marieke Flament, CEO of the NEAR Foundation, shared her excitement about the partnership, saying, “We are thrilled to partner with Shemaroo Entertainment, a company with a rich history in Indian cinema and a vast market reach.” Flament added, “With a collection of over 3,700 movie titles and content distribution partners like Amazon Prime Video, Netflix, and YouTube, Shemaroo will expose NEAR to a completely new audience.” Shemaroo garners over 100 million views per day, with a massive cumulative subscriber base of over 200 million. This impressive audience reach will make NEAR more visible in an important market, contributing to its broader vision of bringing one billion people to Web3 through strategic partnerships. The partnership also helps increase the adoption of BOS, demonstrates the potential of blockchain technology in media and entertainment, and will attract new developers and partners in both the region and the entertainment industry. The partnership comes just shortly after the Foundation appointed Arpit Sharma to spearhead regional growth in India, ASEAN, and the Middle East. The partnership between Shemaroo Entertainment and NEAR Foundation is an important step towards unlocking the full potential of blockchain technology in the world of media and entertainment. Using the Indian region as a breeding ground for innovation via Sheramoo’s Web3 cell, they’ll be setting a new standard for new forms of content for existing libraries.