text
stringlengths
46
74.6k
# StorageUsageConfig Describes cost of storage per block ## account_cost _type: Gas_ Base storage usage for an account ## data_record_cost _type: Gas_ Base cost for a k/v record ## key_cost_per_byte: _type: Gas_ Cost per byte of key ## value_cost_per_byte: Gas _type: Gas_ Cost per byte of value ## code_cost_per_byte: Gas _type: Gas_ Cost per byte of contract code
--- id: glossary title: Glossary description: Helpful definitions for the wiki. sidebar_position: 8 --- --- ## Address A string of letters and numbers used to receive or send cryptocurrencies, tokens, or NFTs. ## Airdrop A marketing campaign used by crypto developers to distribute tokens to their early adopters and followers of their projects. ## Block An aggregation of chunks. ## Block Explorer A software for visualizing blocks, transactions, and blockchain network metrics (e.g., average transaction fees, hashrates, block size, block difficulty). ## Block Height The block height is a sequential number of the most recent block in the blockchain. In NEAR, there is not guaranteed to be a block for each sequential number, e.g. block 982 does not necessarily exist. ## Block Reward A reward (typically cryptocurrency) awarded to publishing nodes for successfully adding a block to the blockchain. ## Blockchain The technology underpinning cryptocurrency. Blockchain is a technology that can safely store transaction records on a peer-to-peer network instead of storing them in a single location. Independent servers around the world, called nodes, make up the network that operates the blockchain. ## Bounty A reward users receive from a project, or blockchain. Projects that give bounties can include dApps and DAOs. ## Centralized Network A network configuration where participants must communicate with a central authority to communicate with one another. Since all participants must go through a single centralized source, the loss of that source would prevent all participants from communicating. ## Chunk An aggregation of transactions which are executed within a particular shard. ## Cryptocurrency A cryptocurrency system can be understood as a system intended for the issuance of tokens which are intended to be used as a general or limited-purpose medium-of-exchange, and which are accounted for using an often collectively-maintained digital ledger making use of cryptography to replace trust in institutions to varying extents. Against such a backdrop, the singular term cryptocurrency can mean a token, intended to be used as a general or limited-purpose medium-of-exchange, issued via a cryptocurrency system. ## Custody Custody, in a crypto context, refers to who owns and secures the private key that proves you own the funds in your wallet. ## Decentralization [in the blockchain space] Decentralized and distributed modes of organization are well defined in computer science discourses and denote a particular network topology. Even there, they can be understood either as an engineering principle, a design aim, or an aspirational claim. In the decentralization discourse these three dimensions are often conflated without merit. A decentralized network design might not produce decentralizing effects and might not either necessarily be decentralized in its actual deployment. When the technical decentralization discourse starts to include social, political, or economic dimensions, the risk of confusion may be even larger, and the potential harms of mistaking a distributed system for something it is not, even more dangerous. Individual autonomy, the reduction of power asymmetries, the elimination of market monopolies, direct involvement in decision making, and solidarity among members of voluntary associations are eternal human ambitions. It is unclear whether such aims can now suddenly be achieved by particular engineering solutions. An uncritical view on decentralization as an omnipotent organizational template may crowd out alternative approaches to creating resilient, trustworthy, equitable, fault resistant technical, social, political or economic modes of organization. ## Decentralized Application (DApp) A Decentralized Application (DApp) is software that exists or runs on a blockchain. ## Decentralized Autonomous Organization (DAO) Is a blockchain-based system that enables people to coordinate and govern themselves mediated by a set of self-executing rules deployed on a public blockchain, and whose governance is decentralized (i.e., independent from central control). ## Decryption The process of changing ciphertext into plaintext using a cryptographic algorithm and key. ## Delegated Proof of Stake (DPoS) This is a consensus algorithm where a stakeholder (somebody who owns a token) can give their votes to a third-party who will validate new blocks for the stakeholder. The number of votes is proportional to the number of tokens. ## Digital Assets A digital asset (also known as a virtual asset) is a digital representation of value that can be digitally traded, or transferred, and can be used for payment or investment purposes. Virtual assets do not include digital representations of fiat currencies, securities and other financial assets that are already covered elsewhere in the FATF Recommendations. ## Double Spending An attack where a blockchain network user attempts to explicitly double spend a digital asset, or transacting with the same set of digital assets more than once. This is a problem which has plagued many digital money systems, and a problem that most blockchain networks are designed to prevent. ## Epoch A time bucket during which many blocks are produced. Certain calculations are performed only based on this time window. ## Formal Verification A systematic process that uses mathematical reasoning and mathematical proofs (i.e., formal methods in mathematics) to verify that the system satisfies its desired properties, behavior, or specification (i.e., the system implementation is a faithful representation of the design). ## Full Node A blockchain node that stores the blockchain data, passes along the data to other nodes, and ensures that newly added blocks are valid and authentic. ## Fungibility A fungible asset can be exchanged for an equal asset of the same type. For example, tokens are fungible, so 1 NEAR is equal to any other 1 NEAR. ## Gas Gas fees are payments made by users to compensate for the computing energy required to process and validate transactions on a blockchain. ## Genesis Block The first block of a blockchain network; it records the initial state of the system. ## GitHub GitHub is a version control system currently used by this Wiki to update content. ## Hash A cryptographic hash function, such as SHA-256, which maps strings of bits to fixed-length strings of bits, satisfying the following two properties: it is computationally infeasible to find for a given output an input which maps to this output; and it is computationally infeasible to find for a given input a second input which maps to the same output. The output of a hash function, is also known as a message digest, digest, hash digest, or hash value. ## Hash Rate The number of cryptographic hash functions a processor can calculate in a given time, usually denominated as hashes per second. ## Interoperability The ability of one entity to communicate with another entity. ## InterPlanetary File System (IPFS) The InterPlanetary File System (IPFS) is a protocol and peer-to-peer network for storing and sharing data in a distributed file system. ## Layer 1 A Layer 1 network can validate and finalize transactions without using another network. ## Layer 2 A Layer 2 network is built on top of a base network, and works as a secondary framework on top of an existing network. ## Liquidity This is how easy it is to swap a token on one network for a token on another network. ## Liquidity Providers (LP) A liquidity provider is a user who funds a liquidity pool with crypto assets they own to make trading on the platform possible. Liquidity Providers earn passive income on their deposit. ## Mainnet Mainnet is the term used to describe when a blockchain protocol is fully developed and deployed. This is a live blockchain, where real transactions are run. ## Metadata Information describing the characteristics of data including, for example, structural metadata describing data structures (e.g., data format, syntax, and semantics) and descriptive metadata describing data contents (e.g., information security labels). Sometimes called the key's attributes. ## NEAR Foundation (NF) A non-profit foundation headquartered in Switzerland that is responsible for contracting protocol maintainers, funding ecosystem development, and shepherding core governance of the NEAR protocol. ## NEAR Protocol (NEAR) Also referred to as NEAR Platform or NEAR Network, these terms are often used interchangeably to mean the software platform to which smart contracts can be deployed. Technically speaking, the “protocol” is the set of rules which define the “platform”, the “network” is just the networking layer or the grouping of nodes who make it up, and “NEAR” is just what that platform is called… but popular usage has caused their meanings to effectively merge so we use them synonymously in most cases. ## Node An individual system within the blockchain network. ## Non-Fungible Token (NFT) Non-Fungible Tokens (NFTs) are digital certificates of ownership for digital assets. These digital certificates are published into an [NEP-171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) token, and once written, they're secured on the blockchain. To create NFTs, the identifying information for these unique digital assets must be recorded on a smart contract. The information on the smart contract is what makes an NFT unique. Anything can be turned into an NFT, with the most popular being videos, media files, or images. Non-fungible means that they can't be exchanged for an "equal" asset because they are unique. They also can't be divided into smaller parts, so you can't trade part of an image, or part of a ticket. ## Off-Chain Refers to data that is stored or a process that is implemented and executed outside of any blockchain system. ## Open Web Sandbox (OWS) A community based organisation within the NEAR Protocol ecosystem. ## Oracle A tool which transfers off-chain data on-chain and vice versa. ## Paper Wallet A paper wallet is an offline method (written on a piece of paper) that includes a user’s private key, public key, and wallet address that are used to store and transact cryptocurrencies online with an exchange or blockchain node. ## Peer-to-Peer (P2P) A peer-to-peer blockchain network works by connecting different computers (or nodes) together so they are able to work in unison. This process creates a censorship resistant, open, public computing network that allows important data and other functionalities to be shared across the network. ## Private Key A private key is an extremely large number that is used in cryptography, similar to a password. They are used to create verifiable digital signatures while keeping the key private. They also indicate ownership of a blockchain address. ## Proof of Stake (PoS) A consensus model where the blockchain network is secured by users locking an amount of cryptocurrency into the blockchain network, a process called staking. Participants with more stake in the system are more likely to want it to succeed and to not be subverted, which gives them more weight during consensus. ## Proof of Work (PoW) Proof of work (PoW) is a form of adding new blocks of transactions to a cryptocurrency's blockchain. The work, in this case, is generating a hash (a long string of characters) that matches the target hash for the current block. ## Reputation In a blockchain-based system is a digital representation of an entity’s standing or status in a specific domain. Reputation is usually derived from aggregated peer-evaluation of the entity’s past actions. It can be leveraged both explicitly through functions in the code (voting power, economic rights) or implicitly as a means of signaling an entity’s trustworthiness. ## Seed Phrase A seed phrase, also referred to as a "recovery phrase" or "recovery seed phrase", is a 12, 18, or 24-word code that is used as a backup access mechanism when a user loses access to a cryptocurrency wallet or associated private key. You should keep your seed phrase safely so that you can regain access to a locked wallet. ## SHA-256 Abbreviation for Secure Hash Algorithm 256-bit, a hash algorithm that can be used to generate digests of messages. The digests are used to detect whether messages have been changed since the digests were generated. ## Smart Contracts Are code deployed in a blockchain environment, or the source code from which such code was compiled. It is executed in a distributed manner by the miners of the underlying blockchain network if and when the underlying conditions are met. Execution of a smart contract is triggered via a blockchain transaction and will produce a change in the blockchain state. ## Staking Protocol-defined token collateralization earning yields and/or providing privileges, either at the base layer (in proof-of-stake consensus models) or at the smart contract layer. ## Staking Pool A staking pool allows multiple stakeholders (or bagholders) to combine their computational resources as a way to increase their chances of being rewarded. ## Testnet This is a separate blockchain on a network where developers can put new features through their paces without worrying about jeopardizing the main network. ## Token Lockup This refers to a time period during which crypto tokens cannot be exchanged or traded. ## Transactions Per Second (TPS) This is the speed that a blockchain network processes transactions. ## Wallet A wallet, in the blockchain sense, stores your virtual assets. ## Web 3.0 This refers to an iteration of the web based on blockchain technology. Decentralization is an important aspect of Web 3. ## White Paper (WP) A white paper is an informational document from an organization the explains complex topics.
NEAR Recap: ETHDenver 2021 COMMUNITY February 25, 2021 Hackathons are always intense. Combine them with blockchain technology, and they’re next-level. ETHDenver is the largest Ethereum #BUIDLathon in the world and it went entirely virtual in 2021. But that didn’t make it lose any of its usual spark. The 7-day-event was a resounding success and saw thousands of hackers, designers, artists, and blockchain enthusiasts participate in the conference’s many events. The NEAR community, too, gathered en masse. This is the NEAR recap of ETHDenver 2021. BUIDLing on NEAR NEAR was present at ETHDenver because it is a big fan of the Ethereum community. The NEAR blockchain is fast, scalable, and interoperable with Ethereum through the ETH-NEAR Rainbow Bridge. Ethereum developers can use the Rainbow Bridge to tap into the unique advantages of the NEAR blockchain without losing their connection to the vibrant Ethereum community. If you’re curious, watch NEAR developer Chad Ostrowski explain how the Rainbow Bridge works here. NEAR puts the developer experience front and center, which makes BUIDLing on NEAR fun and easy. But you’ll never know that unless you try it out. That’s why NEAR had several bounties to encourage the ETHDenver participants to play with the NEAR blockchain and its ecosystem of dApps. Social Impact Bounty: create something that benefits the social good; NEAR & Ceramic Bounty: create something that uses both technologies; NEAR & Textile Bounty: create something that uses both technologies; Blue Sky Bounty: create something using the Rainbow Bridge; Global Citizens Bounty: to promote projects from other parts of the world; NFT Bounty: deploy an NFT store on Mintbase and do something creative; GRL Power Bounty: to promote teams where over half are women. A big hug and a thank you to all the hackers who submitted entries for these NEAR bounties. You could have built on any of the L1 and L2 blockchains present at ETHDenver, but you chose NEAR (and had great fun doing so). One of the NEAR bounty winners even won an ETHDenver Impact Bounty, only given to projects that address a UN Sustainable Development Goal. Congratulations to the team that built Token Meme, which intends to educate the next generation about blockchain and cryptocurrencies. A DAO in a Moon Crater ETHDenver is more than just a hackathon. Participants could watch talks and workshops live on Twitch, dance at the Decentralized Dance Party, play blockchain poker, explore Denver’s Sports Castle recreated in Minecraft, and much more. As it turned out, they could also interact with a working DAO on the NEAR mainnet. It wasn’t just a DAO either. It was a satellite that had crash-landed in a moon crater in the Cryptovoxels metaverse. Enter the SputnikDAO. The ETHDenver SputnikDAO The SputnikDAO is a framework of DAOs built on the NEAR blockchain that enables communities to build their own value systems and coordination mechanisms. An alien council governed this particular SputnikDAO at ETHDenver. The aliens sought advice from participants on what to do with their crash-landed satellite and were willing to pay up to 35 NEAR tokens in exchange for that advice. The ETHDenver SputnikDAO showed that a working DAO running on a mainnet is possible and that interacting with one doesn’t have to be hard. If anything, it’s great fun! All you needed to interact with the DAO was a NEAR wallet. Over a hundred unique NEAR accounts submitted proposals to the SputnikDAO. Together, they generated 131 (and counting) pieces of advice that you can still view here. Some of the ETHDenver SputnikDAO entries Thank you to everyone who interacted with the SputnikDAO. The proposals you submitted showcased how creative the NEAR community can be when given the right tools. Another thank you to Laura Camellini from Createbase for modeling the Sputnik satellite, Ilan Katin for modeling the moon crater, and Felipe Duarte and Guilherme Maueler of AgencyDAO for creating the alien council’s video message. See You in the NEAR Future Overall, thank you to the NEAR community for being so omnipresent and energized at ETHDenver 2021. Whether it was engaging with the SputnikDAO, submitting applications for NEAR bounties, giving talks on a wide variety of topics, or chatting to developers from other ecosystems, your presence was felt and appreciated. If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR documentation to get started. If you want to be part of the NEAR community, join our Discord or Telegram channels or follow NEAR on Twitter. The community is inclusive and is supportive of anyone who wants to build awesome dApps. As a final point, on the first day of ETHDenver, the NEAR Foundation announced the NEAR Grants Program (NGP). The NGP is meant to accelerate the world’s transition to open technologies and enable a community of developers and creators. Over the first half of 2021, the NGP will award the equivalent of $1 million to the teams who work on that goal. All developers who want to build something amazing on NEAR should strongly consider requesting a grant. See you in the NEAR future. Let’s build something epic.
--- id: bos-gateway title: Using components on WebApps --- In order to use the components you create in a WebApp you need to use what is known as the `NEAR VM`. This virtual machine helps you to easily fetch components from the blockchain and transform them into executable code. There are two possible scenarios: - You want to start a WebApp [**from scratch**](#starting-a-webapp-from-scratch). - You want to integrate components into an [**existing WebApp**](#integrating-components-into-your-webapp) --- ## Starting a WebApp from scratch If you want to start a WebApp from scratch, the simplest option is to use `create-near-app`. To use it, you only need to have [node.js](https://nodejs.org/en/) installed on your computer. Simply run the following command and follow the instructions: ```bash npx create-near-app@latest ``` :::tip Tutorial To learn more about the template created by `create-near-app` see our [Quickstart a WebApp](../../2.build/4.web3-apps/quickstart.md) tutorial. ::: --- ## Integrating Components into your WebApp In order to integrate components into your WebApp you will leverage two libraries: - **Wallet Selector**: Allows user to login using their preferred NEAR wallet. - **NEAR VM**: Simplifies fetching NEAR components from the blockchain and rendering them. The best way to learn how to integrate components into your WebApp is by following our tutorial: :::tip Tutorial To learn step-by-step how to integrate them, please visit our [integrating components into a WebApp](../../2.build/4.web3-apps/integrate-components.md) tutorial. :::
--- title: Building On NEAR description: A quick quide to building projects on NEAR. sidebar_position: 0 --- # Building on near :::info on this page * The guide is for those interested in building projects on NEAR, and provides tools and resources for a better experience. * Essential tools include the NEAR wallet, block explorer, and command-line interface (CLI), while AwesomeNEAR provides project inspiration. * Educational resources are available for both technical and non-technical builders, and can be found on the learning resources page. ::: Welcome to the building overview! This is a guide for project managers, founders, software developers, or anybody else interested in building projects on NEAR. It contains tools and resources that can improve your experience building projects on NEAR. ## Tools There are a wide variety of tools available to help you develop your project. You can start by looking at our [essential tools](overview/essential-tools.md), the NEAR wallet, the block explorer, and the command-line interface(CLI). These tools allow you to interface the NEAR protocol in different ways, the NEAR wallet makes it easy to store your NEAR and interact with the NEAR network with a convenient graphical user interface. The block explorer allows you to see what's happening on the NEAR network on a larger scale, including what transactions are happening, statistics about nodes and blocks, and a historical look at the NEAR network. For project inspiration, have a look at [AwesomeNEAR](https://awesomenear.com/), which has a large and growing directory of projects built on NEAR. This can help you understand what projects already exist, and help you determine what you should include in your project. For developers looking to dive right into a project, have a look at our [documentation](https://docs.near.org) for information about how to build your project. ## Learning About Building on NEAR Once you have the essential tools to interact with the NEAR network, you can use our educational resources to learn more about NEAR. We have a wide variety of resources for builders in both technical and non-technical roles, and are always adding more. You can find out what's available by on our [learning resources](tech-resources.md) page.
Near at ETHDenver: the Blockchain Operating System, Near Day, and More NEAR FOUNDATION March 8, 2023 Missed Near Day and ETHDenver 2023? We’ve got you covered with content from Near talks and panels. There were also a number of awesome announcements, including the big news out of ETHDenver — the Blockchain Operating System. Let’s take a look at all that was Near at ETHDenver. Near Day talks Near co-founder and Pagoda CEO Illia Polosukhin unveiling the Blockchain Operating System. Near Day, the 1-day mini summit on all things Near, was jam-packed with the latest technological and protocol updates. Chief among them was the announcement of the Blockchain Operating System. Things got started with a Regenerative Finance (ReFI) talk from Open Forest Protocol’s Frederic Fournier and Flow Carbon’s Phil Fogel. Later in the morning programme, OnMachina’s Polina Aladina and Mark Collier talked about building decentralized storage on Near. As a vital Near ecosystem project, it was great for the ETHDenver crowd to hear from OnMachina on Web3 storage. OnMachina’s Mark Collier talking decentralized storage on Near. Keypom, which also recently launched on Near, got some much needed visibility at Near Day. In “Instant Crypto Experiences with Keypom”, Ben Kurrek and Matt Lockyer took the audience on a tour of their Web3 onboarding solution, in which users are given a special type of access key that can be used to experience a crypto application and later be turned into a wallet. (Read more about Keypom here.) The morning programme also featured talks from Calimero Network’s Sandi Fatic on privacy and scaling with private sharding; Aurora Labs’ Alex Shevchenko on Containers, Aurora’s cloud computing solution for blockchains; Sweat Economy’s Oleg Fomenko on how to effectively onboard people from Web2 to Web3; and Near co-founder Alex Skidanov on how the future of AI will be decentralized. In the afternoon, there were a range of talks, starting with Pagoda’s Max Zavershynskyi presentation on creating “high velocity developer communities” via Near DevGov DAO. But the big news on Near Day was the Blockchain Operating System talk from Near co-founder Illia Polosukhin. After Illia primed the audience, Pagoda’s Chief Product Officer Alex Chiocchi elaborated on how Blockchain Operating System will help in onboarding millions of users to Near, while Pagoda’s Bowen Wang detailed the protocol innovations powering the Blockchain Operating System. Marieke Flament on the ETHDenver main stage for the ‘Crypto Winter, Bullish Builders’ panel. Near Foundation CEO Marieke Flament and Dragonfly Capital’s Haseeb Qureshi also talked about why the future remains bright for Web3 even during the crypto winter. There were also talks from Pagoda’s Pavel Kudinov on the Near data stack and Josh Ford on a fully decentralized Javascript. Other topics included the building of infrastructure to onboard 1 billion users on Near, NFT infrastructure, a “DeFi survival kit” for the bear market, and the regulatory landscape in Web3. Near speakers at ETHDenver Pagoda’s Bowen Wang discussing Near’s vision for Layer 1 infrastructure. A number of speakers represented the Near ecosystem at ETHDenver talks. Topics included the Blockchain Operating System, sustainability, UX design, and more. Aurora Labs’ Alex Shevchenko kicked things off with a presentation on Web3 infrastructure and scalability — specifically, how not to hack everything up in creating bridges. Alex also gave another talk on next generation user experience. Near Foundation CEO Marieke Flament delivered a talk on the three pillars of Web3 sustainability, while Proximity Labs’ Kendall Cole explored how Web3 can win in the DeFi battle against app stores. Aurora Labs CEO Alex Shevchenko delivering a talk at ETHDenver. In separate talks, Illia Polosukhin and Pagoda’s Bowen Wang spoke to the ETHDenver audience about the Blockchain Operating System. While Bowen mapped out Near’s vision for Layer 1 Infrastructure, Illia talked about reinventing Web3 development with decentralized frontends and social networking. Near Announcements While the Near is the Blockchain Operating System announcement was the talk of ETHDenver, there were plenty of other announcements. Find the full run-down of Near ecosystem announcements here. In other news, the Near ecosystem had two wins at ETHVC’s Startup Demo Day during ETHDenver — Niche Protocol, a Web3 social media platform, and Kino, a film financing platform.
--- id: posts-indexer title: Posts Indexer sidebar_label: Posts Indexer --- :::info NEAR QueryAPI is currently under development. Users who want to test-drive this solution need to be added to the allowlist before creating or forking QueryAPI indexers. You can request access through [this link](http://bit.ly/near-queryapi-beta). ::: ## Overview This indexer creates a new row in a pre-defined `posts` table created by the user in the GraphQL database for every new post found on the blockchain. This is a simple example that shows how to specify a single table, filter blockchain transaction data for a specific type of transaction, and save the data to the database. :::tip This indexer can be found by [following this link](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=bucanero.near/posts-example). ::: ## Defining the Database Schema The first step to creating an indexer is to define the database schema. This is done by editing the `schema.sql` file in the code editor. The schema for this indexer looks like this: ```sql CREATE TABLE "posts" ( "id" SERIAL NOT NULL, "account_id" VARCHAR NOT NULL, "block_height" DECIMAL(58, 0) NOT NULL, "receipt_id" VARCHAR NOT NULL, "content" TEXT NOT NULL, "block_timestamp" DECIMAL(20, 0) NOT NULL, CONSTRAINT "posts_pkey" PRIMARY KEY ("id") ); ``` This schema defines a table called `posts` with columns: - `id`: a unique identifier for each row in the table - `account_id`: the account ID of the user who created the post - `block_height`: the height of the block in which the post was created - `receipt_id`: the receipt ID of the transaction that created the post - `content`: the content of the post - `block_timestamp`: the timestamp of the block in which the post was created ## Defining the Indexing Logic The next step is to define the indexing logic. This is done by editing the `indexingLogic.js` file in the code editor. The logic for this indexer can be divided into two parts: 1. Filtering blockchain transactions for a specific type of transaction 2. Saving the data from the filtered transactions to the database ### Filtering Blockchain Transactions The first part of the logic is to filter blockchain transactions for a specific type of transaction. This is done by using the `getBlock` function. This function takes in a block and a context and returns a promise. The block is a Near Protocol block, and the context is a set of helper methods to retrieve and commit state. The `getBlock` function is called for every block on the blockchain. The `getBlock` function for this indexer looks like this: ```js import { Block } from "@near-lake/primitives"; async function getBlock(block: Block, context) { function base64decode(encodedValue) { let buff = Buffer.from(encodedValue, "base64"); return JSON.parse(buff.toString("utf-8")); } const SOCIAL_DB = "social.near"; const nearSocialPosts = block .actions() .filter((action) => action.receiverId === SOCIAL_DB) .flatMap((action) => action.operations .map((operation) => operation["FunctionCall"]) .filter((operation) => operation?.method_name === "set") .map((functionCallOperation) => ({ ...functionCallOperation, args: base64decode(functionCallOperation.args), receiptId: action.receiptId, })) .filter((functionCall) => { const accountId = Object.keys(functionCall.args.data)[0]; return ( Object.keys(functionCall.args.data[accountId]).includes("post") || Object.keys(functionCall.args.data[accountId]).includes("index") ); }) ); ... // Further logic for saving nearSocialPosts to the database } ``` This function first defines a helper function called `base64decode` that decodes base64 encoded data. It then defines a constant called `SOCIAL_DB` that is the name of the smart contract that stores the posts in NEAR. It then filters the blockchain transactions for a specific type of transaction. This is done by: 1. Filtering the blockchain transactions for transactions where the `receiverId` is the `SOCIAL_DB` database 2. Mapping the operations of the filtered transactions to the `FunctionCall` operation 3. Filtering the `FunctionCall` operations for operations where the `method_name` is `set` 4. Mapping the filtered `FunctionCall` operations to an object that contains the `FunctionCall` operation, the decoded `args` of the `FunctionCall` operation, and the `receiptId` of the transaction 5. Filtering the mapped objects for objects where the `args` contain a `post` or `index` key This function returns an array of objects that contain the `FunctionCall` operation, the decoded `args` of the `FunctionCall` operation, and the `receiptId` of the transaction. This array is called `nearSocialPosts`. ### Saving the Data to the Database The second part of the logic is to save the data from the filtered transactions to the database. This is done by using the [`context.db.Posts.insert()`](../../../2.build/6.data-infrastructure/query-api/context.md#insert) function. The `context.db.Posts.insert()` function will be called for every filtered transaction as defined by the `.map()` function called on the array of `nearSocialPosts`. The function for this indexer looks like this: ```js ... // Logic for filtering blockchain transactions, defining nearSocialPosts if (nearSocialPosts.length > 0) { const blockHeight = block.blockHeight; const blockTimestamp = Number(block.header().timestampNanosec); await Promise.all( nearSocialPosts.map(async (postAction) => { const accountId = Object.keys(postAction.args.data)[0]; console.log(`ACCOUNT_ID: ${accountId}`); // create a post if indeed a post if ( postAction.args.data[accountId].post && Object.keys(postAction.args.data[accountId].post).includes("main") ) { try { console.log("Creating a post..."); const postData = { account_id: accountId, block_height: blockHeight, block_timestamp: blockTimestamp, receipt_id: postAction.receiptId, content: postAction.args.data[accountId].post.main, }; await context.db.Posts.insert(postData); console.log(`Post by ${accountId} has been added to the database`); } catch (e) { console.error(`Error creating a post by ${accountId}: ${e}`); } } }) ); } ``` ## Querying data from the indexer The final step is querying the indexer using the public GraphQL API. This can be done by writing a GraphQL query using the GraphiQL tab in the code editor. For example, here's a query that fetches `posts` from the _Posts Indexer_, ordered by `block_height`: ```graphql query MyQuery { <user-name>_near_posts_indexer_posts(order_by: {block_height: desc}) { content block_height account_id } } ``` Once you have defined your query, you can use the GraphiQL Code Exporter to auto-generate a JavaScript or NEAR Widget code snippet. The exporter will create a helper method `fetchGraphQL` which will allow you to fetch data from the indexer's GraphQL API. It takes three parameters: - `operationsDoc`: A string containing the queries you would like to execute. - `operationName`: The specific query you want to run. - `variables`: Any variables to pass in that your query supports, such as `offset` and `limit` for pagination. Next, you can call the `fetchGraphQL` function with the appropriate parameters and process the results. Here's the complete code snippet for a NEAR component using the _Posts Indexer_: ```js const QUERYAPI_ENDPOINT = `https://near-queryapi.api.pagoda.co/v1/graphql/`; State.init({ data: [] }); const query = `query MyPostsQuery { <user-name>_near_posts_indexer_posts(order_by: {block_height: desc}) { content block_height account_id } }` function fetchGraphQL(operationsDoc, operationName, variables) { return asyncFetch( QUERYAPI_ENDPOINT, { method: "POST", headers: { "x-hasura-role": `<user-name>_near` }, body: JSON.stringify({ query: operationsDoc, variables: variables, operationName: operationName, }), } ); } fetchGraphQL(query, "MyPostsQuery", {}).then((result) => { if (result.status === 200) { if (result.body.data) { const data = result.body.data.<user-name>_near_posts_indexer_posts; State.update({ data }) console.log(data); } } }); const renderData = (a) => { return ( <div key={JSON.stringify(a)}> {JSON.stringify(a)} </div> ); }; const renderedData = state.data.map(renderData); return ( {renderedData} ); ``` :::tip To view a more complex example, see this widget which fetches posts with proper pagination: [Posts Widget powered By QueryAPI](https://near.org/edit/roshaan.near/widget/query-api-feed-infinite). :::
# Registers API Registers allow the host function to return the data into a buffer located inside the host oppose to the buffer located on the client. A special operation can be used to copy the content of the buffer into the host. Memory pointers can then be used to point either to the memory on the guest or the memory on the host, see below. Benefits: - We can have functions that return values that are not necessarily used, e.g. inserting key-value into a trie can also return the preempted old value, which might not be necessarily used. Previously, if we returned something we would have to pass the blob from host into the guest, even if it is not used; - We can pass blobs of data between host functions without going through the guest, e.g. we can remove the value from the storage and insert it into under a different key; - It makes API cleaner, because we don't need to pass `buffer_len` and `buffer_ptr` as arguments to other functions; - It allows merging certain functions together, see `storage_iter_next`; - This is consistent with other APIs that were created for high performance, e.g. allegedly Ewasm have implemented SNARK-like computations in Wasm by exposing a bignum library through stack-like interface to the guest. The guest can manipulate then with the stack of 256-bit numbers that is located on the host. #### Host → host blob passing The registers can be used to pass the blobs between host functions. For any function that takes a pair of arguments `*_len: u64, *_ptr: u64` this pair is pointing to a region of memory either on the guest or the host: - If `*_len != u64::MAX` it points to the memory on the guest; - If `*_len == u64::MAX` it points to the memory under the register `*_ptr` on the host. For example: `storage_write(u64::MAX, 0, u64::MAX, 1, 2)` -- insert key-value into storage, where key is read from register 0, value is read from register 1, and result is saved to register 2. Note, if some function takes `register_id` then it means this function can copy some data into this register. If `register_id == u64::MAX` then the copying does not happen. This allows some micro-optimizations in the future. Note, we allow multiple registers on the host, identified with `u64` number. The guest does not have to use them in order and can for instance save some blob in register `5000` and another value in register `1`. #### Specification ```rust read_register(register_id: u64, ptr: u64) ``` Writes the entire content from the register `register_id` into the memory of the guest starting with `ptr`. ###### Panics - If the content extends outside the memory allocated to the guest. In Wasmer, it returns `MemoryAccessViolation` error message; - If `register_id` is pointing to unused register returns `InvalidRegisterId` error message. ###### Undefined Behavior - If the content of register extends outside the preallocated memory on the host side, or the pointer points to a wrong location this function will overwrite memory that it is not supposed to overwrite causing an undefined behavior. --- ```rust register_len(register_id: u64) -> u64 ``` Returns the size of the blob stored in the given register. ###### Normal operation - If register is used, then returns the size, which can potentially be zero; - If register is not used, returns `u64::MAX`
--- sidebar_position: 1 title: "Public Methods" --- # Public Method Types Methods can be called externally by using the `view({})` or `call({})` decorators within the contract class which will expose the method in the compiled WASM bytecode to be called by any other NEAR Account. Whenever a method is declared in your contract class without these decorators and is called by another NEAR Account, a `MethodNotFound` error will be thrown. :::tip If you need a contract to call itself, you can mark the function with these decorators but add the [`({ privateFunction: true })` annotation in the decorator parameters](private-methods.md) so that it will panic if called from anything but the contract itself. ::: A basic usage of this would look like the following: ```js @NearBindgen({}) export class MyContractStructure { @call({}) // or @view({}) some_method({ parameter_a, parameter_b }) { // .. method logic here } } ``` :::note `snake_case` vs `camelCase` We recommend using `snake_case` for method names, contrary to the `camelCase` convention in JavaScript. This is because the method names for a majority of contracts in the NEAR ecosystem use `snake_case`, and it is easier to use the same convention for all contracts. ::: Where this would expose `some_method` from the WASM binary and allow it to be called externally. <!-- TODO: insert detail overview -->
--- id: fastauth-sdk title: FastAuth SDK sidebar_label: FastAuth (Email Login) --- FastAuth is a key management system that allows users to **recover or sign-up for** a NEAR account using their **email address**. Furthermore, it allows to subsidize gas for a certain smart contract, so users can interact with it without having to fund their account. --- ## FastAuth Components FastAuth is comprised of 3 main elements: 1. **FastAuth Signer App**: A module that allow FastAuth users to sign transactions. 2. **MPC Recovery Service**: A service to create and restore user accounts, as well as signing transactions on behalf of the user. 3. **Transaction Relayer**: A server that relays transactions to the NEAR network on behalf of the user. --- ### Setting up Firebase #### Create a project - Go to [Firebase](https://firebase.com) - Create or sign in to an account - Go to "Get started", then "Add project" - Call this project `my-fastauth-issuer` - Disable Google Analytics (recommended) - Click on "Create project" #### Set up passwordless authentication - Go to "Authentication", then "Get started", and "Add new provider" - Enable "Email/Password" and "Email link (passwordless sign-in)" - Hit "Save" #### Add user device information to Firestore - Return to "Project Overview" - Go to "Cloud Firestore", then "Create database" - Select "Start in production mode", then "Next" - Select your preferred location, then "Enable" - Go to the "Rules" tab - Change the rules to the following: ``` rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId}/{document=**} { allow create, read, update, delete: if request.auth != null && request.auth.uid == userId; } match /publicKeys/{publicKey} { allow create, delete: if request.auth != null; allow read : if true; allow update: if false; } } } ``` - Hit "Publish" - Go to the "Data" tab - Click on "Start collection" - Set the Collection ID to `users` and hit "Next" - Add a Document ID of `root` and press "Save" - Click on "Start collection" - Set the Collection ID to `publicKeys` and hit "Next" - Add a Document ID of `root` and press "Save" #### Get the application credentials - Press the gear button next to "Project Overview", and go to "Project settings" - Under "Your apps", click on the `</>` button - Set the app nickname as `issuer-gcp` and hit "Register app" - You should see the code needed for initilization and authentication of Firestore, such as: ```js // Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "apikey", authDomain: "my-fastauth-issuer-123.firebaseapp.com", projectId: "my-fastauth-issuer-123", storageBucket: "my-fastauth-issuer-123.appspot.com", messagingSenderId: "12345678910", appId: "1:12345678910:web:12345678910" }; // Initialize Firebase const app = initializeApp(firebaseConfig); ``` ### Setting up your relayer #### Setting up a NEAR account First ensure that `cargo` is installed on your local machine. Try [rustup](https://rustup.rs/) if you haven't already installed it. ```bash cargo install near-cli-rs NEAR_ENV=mainnet near account create-account fund-later use-auto-generation save-to-folder ~/.near-credentials/implicit ``` This should output something like: ```bash The file "~/.near-credentials/implicit/275f14eecb0afcb1f46f2b71b7933afd2de6d4ae8b08e9b11fc538a5a81406b7.json" was saved successfully ``` In this example. `275f14eecb0afcb1f46f2b71b7933afd2de6d4ae8b08e9b11fc538a5a81406b7` is your funded account. We'll refer to this as `$FUNDED_ACCOUNT` from now on. Send some NEAR to this address. #### Adding multiple keys (Recommended) This account has been created with one key. However, due to [this](https://near.zulipchat.com/#narrow/stream/295302-general/topic/.E2.9C.94.20The.20trouble.20with.20nonces/near/389649443), you should create an account with `N` keys where `N` is the number of requests you expect to get in a second, at peak load. To generate an additional key, run the following command: ```bash near account add-key $FUNDED_ACCOUNT grant-full-access autogenerate-new-keypair save-to-keychain network-config mainnet sign-with-access-key-file ~/.near-credentials/implicit/$FUNDED_ACCOUNT.json send ``` #### Deploying the relayer Run the following command: ```bash git clone https://github.com/near/pagoda-relayer-rs ``` Go to `config.toml` and change: ```toml network = "mainnet" num_keys = 3 # correlates to the number of keys in `keys_filenames`. Will be optional in the future. relayer_account_id = "$FUNDED_ACCOUNT" keys_filenames = [ # The original account "~/.near-credentials/mainnet/$FUNDED_ACCOUNT.json", # Other keys you've optionally created. This will allow rotating through each key as to avoid nonce races. "~/.near-credentials/mainnet/$FUNDED_ACCOUNT/ed25519_4ryLkp4AuzBD8yuyRJKb91hvHZ4zgqouWcJzu1gNEvLv.json", "~/.near-credentials/mainnet/$FUNDED_ACCOUNT/ed25519_7K3jF8Ft5dKFEPYRH1T4mncvsZGgSoGKsvsnnKEmqubT.json" ] ``` Optionally, if you need to generate additional access keys for the `$FUNDED_ACCOUNT`, run the following command N times. Note that this will create keys for implicit accounts, but we'll then tie them to `$FUNDED_ACCOUNT`. ```bash near generate-key near add-key $FUNDED_ACCOUNT exampleImplicitPublicKeyCxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` Then run: ```bash docker compose up ``` You should do this on a VM server of your choice. We will refer to the URL of this VM as `$RELAYER_URL` from now on. ### Setting up the frontend #### Deploying the signer app - Go to GCP's Cloud Run console and press "Create Service". - In the field "Container image URL", paste `nearprotocol/fast-auth-sdk-frontend:latest`. - Under **Container(s), Volumes, Networking, Security** set **Container port** to `80` - Go to the "Container, Networking, Security" fold out and then "Environment Variables" - Click on "Add Variable" - Set the following environment variables from the `firebaseConfig` you generated earlier. ```yaml NETWORK_ID: 'mainnet', RELAYER_URL: '$RELAYER_URL', FIREBASE_API_KEY: 'apikey', FIREBASE_AUTH_DOMAIN: 'my-fastauth-issuer-123.firebaseapp.com', FIREBASE_PROJECT_ID: 'my-fastauth-issuer-123', FIREBASE_STORAGE_BUCKET: 'my-fastauth-issuer-123.appspot.com', FIREBASE_MESSAGING_SENDER_ID: '12345678910', FIREBASE_APP_ID: '1:12345678910:web:12345678910', ``` Alternatively if you're doing a `testnet` deployment, do: ```yaml NETWORK_ID: 'testnet', RELAYER_URL_TESTNET: '$RELAYER_URL', FIREBASE_API_KEY_TESTNET: 'apikey', FIREBASE_AUTH_DOMAIN_TESTNET: 'my-fastauth-issuer-123.firebaseapp.com', FIREBASE_PROJECT_ID_TESTNET: 'my-fastauth-issuer-123', FIREBASE_STORAGE_BUCKET_TESTNET: 'my-fastauth-issuer-123.appspot.com', FIREBASE_MESSAGING_SENDER_ID_TESTNET: '12345678910', FIREBASE_APP_ID_TESTNET: '1:12345678910:web:12345678910', ``` - Click on "Create Application" - Then, inside your app's control panel copy the app's URL, such as `https://signer-app-123456-ab.a.run.app`. We will refer to the deploy URL as `$WALLET_URL`. #### Authorizing a domain on Firebase - Go back to the Firebase Console - Go to "Authentication" in the sidebar, and then the "Settings" tab - Click on the "Authorized domains" menu item - Add `$WALLET_URL` to the list #### Deploying your application frontend First, install the `@near-js/iframe-rpc` package from the NPM registry. ```js import { setupFastAuthWallet } from 'near-fastauth-wallet'; import { setupWalletSelector } from '@near-wallet-selector/core'; // Initialize wallet selector const selector = setupWalletSelector({ network: networkId, modules: [ setupFastAuthWallet({ relayerUrl: "$RELAYER_URL", walletUrl: "$WALLET_URL" }) ] }) // EITHER setup onClick function for login const onCLick = () => selector.then((selector: any) => selector.wallet('fast-auth-wallet')) .then((fastAuthWallet: any) => fastAuthWallet.signIn({ contractId: "$CONTRACT_ID", email: "<USERS_EMAIL_ADDRESS>", isRecovery: true, }),); // OR setup onClick function for login const onCLick = () => selector.then((selector: any) => selector.wallet('fast-auth-wallet')) .then((fastAuthWallet: any) => fastAuthWallet.signIn({ contractId: "$CONTRACT_ID", email: "<USERS_EMAIL_ADDRESS>", accountId: "<USERS_DESIRED_NEAR_ADDRESS>.near" isRecovery: false, }),); ``` Wehenever the user tries to login, call `onClick`. ### Getting added to the MPC recovery service As a last step, we'll need to add your app to our MPC recovery service. To get added, please send us your `$FIREBASE_PROJECT_ID`, `$RELAYER_API_KEY` and `$RELAYER_URL` through this [form](https://forms.gle/cDfXj2D5bm9sohBx6).
Music and Blockchain: Introducing the Future of Sound NEAR FOUNDATION April 11, 2022 After more than two years of a global pandemic, following what seemed to be a never-ending sequence of postponements, rescheduling, and cancellations, live music has returned in full force. From destination festivals to elaborate arena shows or even regional theaters and local clubs, venues are opening their doors to once again allow artists to perform and connect with their fans. At the same time, musical artists’ revenues have also been shrinking in the centralized streaming music model dominated by big tech firms. On the most popular streaming services, a single track needs to be streamed more than 300 times to generate $1 in royalties for the artist. To further complicate payouts, rates are rarely paid at a flat rate per stream, agreements are ever-changing, different tiers and subscriptions impact pay rates, and streams are more valuable in various areas worldwide. Just as musicians had to pivot during their absence from the stage and find new and meaningful ways to stay connected with their fans, the Web3 community has been incubating ideas in using blockchain to disrupt both the music industry’s physical release and streaming music models. The future of music is being written today, on NEAR, by a vibrant and diverse community of artists, developers, fans, and more. Various music projects, led by teams of Web3 developers and entrepreneurs, are working to give power back to music artists while breaking down the walls between them and their fans. This series will explore how artists, producers and musicians are taking control over their assets, and building music on NEAR. An industry saturated with problems Even with Web2 streaming music platforms, the recording industry’s model has remained essentially unchanged for nearly a century. Most record labels have one goal — maximizing profits. They hold on to as much of their earnings as possible and dictate unfavorable terms when establishing contracts with most artists, save for a handful of superstars able to negotiate more favorable agreements. As traditional album sales have given way to streaming services, musicians often receive only fractions of a penny per play on popular streaming services. A vast and perplexing network of labels, publishers, distributors, royalty collectors, and other middlemen make getting paid as an artist an inefficient and exceedingly lengthy process with little transparency. As a result, touring and merchandise sales have become necessary to earn as a musician in 2022. But as touring revenues fell over the last two years, musicians have more cause than ever to disrupt the traditional song and record publishing revenue. Faster, more efficient creative control Cutting-edge protocols for NFTs, fractional ownership, smart contracts, and real-time on-chain settlement of royalties make blockchain and the music industry a natural pairing. A blockchain boom in the music industry is imminent thanks to NEAR Protocol’s robust feature set already in use and hugely successful in areas like, non-fungible tokens (NFTs), and decentralized autonomous organizations (DAOs). With each of these technologies, the architects of music’s future envision more manageable, faster, and more accurate payments for artists’ work. Through smart contracts, the existing, painfully slow process of royalty payments could be reduced from multiple months to mere seconds. Each time a listener presses play on a song, musicians could be paid near instantaneously, primarily due to NEAR’s Nightshade being theoretically capable of millions of transactions per second. Smart contracts that settle royalty payments in real-time will obliterate the need for third-party middlemen, leaving more money in the hands of the artists and creators. Artists will be empowered to establish direct seller-consumer relationships with their fans, with blockchain technology as the foundation. Beyond being extremely fast and super secure, NEAR’s blockchain is global in scale and exceptionally transparent. Fractional ownership already implemented on NEAR will bring a new level of transparency in proving ownership over a specific piece of music and confirming every individual with a claim to its copyright. Artists can have access to all streaming and fan activity data instead of the limited access to watered-down data that they currently receive from their label, distributor, or streaming platforms. Writing the future of music on NEAR The future of music is one where a radical change to the way music publishing, royalties, launching and managing record labels, and even building music software will be achieved. NEAR Protocol’s amazingly reliable and consistent blockchain is home to several exciting projects, each shaping the evolution of Web3 technology that can power the multi-billion-dollar recording industry. Experimenting with audio NFTs, virtual events, and decentralized communities, the NEAR-based DAOrecords are building tools to enable musicians to “harness the power of the blockchain revolution.” Artists retain full ownership of everything they create and are not restricted by any contract. The label has now worked with over 100 artists, released over 350 NFTs, and produced over 50 virtual events for an ever-growing community. “At its core, a label is just a facilitator,” says Vandal. “The new Web3 record labels will most likely be DAOs, providing funding, support, resources and even minting and other services an artist might require.” “Their role will generally remain the same,” he adds. “But with shared ownership, transparency and a blockchain-inspired business model is what will make it appealing to artists.” DAOrecords’ vision of the future is a music industry where artists have control over their music and the relationship with their fans and community, all within their economy powered by the NEAR blockchain. Designed for the metaverse and the play-to-earn era, MODA DAO is a decentralized technology network and community spearheading the “Music3” movement, their term for the music industry’s Web3 adoption through NFTs, micro-licensing, DAO governance, and DeFi. With a suite of creator tools, underlying infrastructure, and a publishing ecosystem, they effectively remove middlemen, increasing value between creators and fans. MODA is being established as a not-for-profit foundation to push Web3 music forward and establish a more sustainable future for audio creators. Powered by a DAO, holders of the MODA Tokens are invited into various ecosystem layers. They can back specific artists to increase their exposure and ranking or even stake into new songs before they are released, increasing visibility within the MODA catalog. NFT.HipHop is a collaborative NFT art series featuring the work of illustrator André LeRoy Davis, established through a partnership between NEAR, the Universal Hip Hop Museum, and Ed Young, co-founder of The Source magazine. A celebration of the history of hip hop and its most iconic artists, the collection features NFTs of 47 legends – from Eazy-E to Lil Wayne – to honor the 47th year of the hip-hop era. A prime example of synergy between music merchandising and blockchain, the pop-up marketplace also highlighted some engineering innovations, including the advanced NFT developer and user experience on NEAR. Driven by fans and a thriving community NEAR’s roadmap includes an unwavering commitment to facilitating the decentralization of the network to the community. Just as power is placed into the hands of the developer and end-user community in blockchain, a shift of power from record executives and industry suits to the artists, creators, and fans will help realize the future of music. NEAR x Music (NxM) is a community focused on music, events, NFTs, and music-forward tools. This vibrant, accessible, and inclusive community of artists, creators, developers, and fans fosters a unique environment where opportunities for collaboration are endless; and where knowledge, gleaned through community contributions, knows no limits. “NxM is a hub for all artists, producers, and people who simply love music by generating values for all customers through different streams and activities,” says the NxM Council. “We expand the NxM community by connecting music lovers on Web3 space and nurture organic growth through activities such as funding musician’s projects, events, community campaigns, and media operations.” Specifically, NxM helps musicians produce music projects and events with web3 tools like DAOs, NFT galleries, and marketplaces, as well as offline and online events. “NFTs and the use of smart contracts is a way to split profits amongst collaborators,” the NxM Council says. “Music specifically tends to involve multiple participants to make a release come together. But by using smart contracts, especially with the tools built into Mintbase, artists are able to write splits into their contracts for both initial and secondary market sales.” Poised to shift the paradigm of the music industry as a whole, NEAR’s unique architecture serves as the foundation and natural home for platforms and tools aimed at improving music fans’ experience and guaranteeing artists’ control over their valuable work. In a truly decentralized fashion, a strong, engaged, and growing global community is at the helm of this movement. Paired with NEAR’s fast, secure, and scalable blockchain, this community of creators and consumers is becoming a formidable, rising force. Join NxM and the greater NEAR community as they prepare to usher in the future of music and write tomorrow’s verse. Growth off the charts From physical album releases to audio tracks in MP3 format available on digital storefronts, to entire catalogs being accessible within a streaming app, the recording industry has undergone several technological revolutions in even the last 20 years. Similar to how social music platforms have allowed artists to connect directly with fans and grow their influence, the advent of Web3 stands ready to once again change how artists and their fans create, manage, and interact with music. Today’s record industry isn’t working for the vast majority of artists. NEAR Protocol’s rich and robust underlying infrastructure is the perfect platform for the growing Web3 music industry to call home. A fast, secure, and scalable blockchain has allowed projects to demonstrate that blockchain-based music rights administration is feasible and has the potential to benefit creators and consumers in significant ways. As the global NEAR community places faith in indie artists, new companies, and industry figures, the momentum they’ve built will have no choice but to be recognized and adopted by the industry giants. Whether it’s the next symphony, chart-topping hit, or Indie B-side, the future of music is being written on NEAR, one note at a time.
# Multi Token Event :::caution This is part of the proposed spec [NEP-245](https://github.com/near/NEPs/blob/master/neps/nep-0245.md) and is subject to change. ::: Version `1.0.0` ## Summary Standard interfaces for Multi Token Contract actions. Extension of [NEP-297](../../EventsFormat.md) ## Motivation NEAR and third-party applications need to track `mint`, `burn`, `transfer` events for all MT-driven apps consistently. This exension addresses that. Note that applications, including NEAR Wallet, could require implementing additional methods to display tokens correctly such as [`mt_metadata`](Metadata.md) and [`mt_tokens_for_owner`](Enumeration.md). ## Interface Multi Token Events MUST have `standard` set to `"nep245"`, standard version set to `"1.0.0"`, `event` value is one of `mt_mint`, `mt_burn`, `mt_transfer`, and `data` must be of one of the following relavant types: `MtMintLog[] | MtBurnLog[] | MtTransferLog[]`: ```ts interface MtEventLogData { EVENT_JSON: { standard: "nep245", version: "1.0.0", event: MtEvent, data: MtMintLog[] | MtBurnLog[] | MtTransferLog[] } } ``` ```ts // Minting event log. Emitted when a token is minted/created. // Requirements // * Contract MUST emit event when minting a token // Fields // * Contract token_ids and amounts MUST be the same length // * `owner_id`: the account receiving the minted token // * `token_ids`: the tokens minted // * `amounts`: the number of tokens minted, wrapped in quotes and treated // like a string, although the numbers will be stored as an unsigned integer // array with 128 bits. // * `memo`: optional message interface MtMintLog { owner_id: string, token_ids: string[], amounts: string[], memo?: string } // Burning event log. Emitted when a token is burned. // Requirements // * Contract MUST emit event when minting a token // Fields // * Contract token_ids and amounts MUST be the same length // * `owner_id`: the account whose token(s) are being burned // * `authorized_id`: approved account_id to burn, if applicable // * `token_ids`: the tokens being burned // * `amounts`: the number of tokens burned, wrapped in quotes and treated // like a string, although the numbers will be stored as an unsigned integer // array with 128 bits. // * `memo`: optional message interface MtBurnLog { owner_id: string, authorized_id?: string, token_ids: string[], amounts: string[], memo?: string } // Transfer event log. Emitted when a token is transferred. // Requirements // * Contract MUST emit event when transferring a token // Fields // * `authorized_id`: approved account_id to transfer // * `old_owner_id`: the account sending the tokens "sender.near" // * `new_owner_id`: the account receiving the tokens "receiver.near" // * `token_ids`: the tokens to transfer // * `amounts`: the number of tokens to transfer, wrapped in quotes and treated // like a string, although the numbers will be stored as an unsigned integer // array with 128 bits. interface MtTransferLog { authorized_id?: string, old_owner_id: string, new_owner_id: string, token_ids: string[], amounts: string[], memo?: string } ``` ## Examples Single owner minting (pretty-formatted for readability purposes): ```js EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_mint", "data": [ {"owner_id": "foundation.near", "token_ids": ["aurora", "proximitylabs_ft"], "amounts":["1", "100"]} ] } ``` Different owners minting: ```js EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_mint", "data": [ {"owner_id": "foundation.near", "token_ids": ["aurora", "proximitylabs_ft"], "amounts":["1","100"]}, {"owner_id": "user1.near", "token_ids": ["meme"], "amounts": ["1"]} ] } ``` Different events (separate log entries): ```js EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_burn", "data": [ {"owner_id": "foundation.near", "token_ids": ["aurora", "proximitylabs_ft"], "amounts": ["1","100"]}, ] } ``` Authorized id: ```js EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_burn", "data": [ {"owner_id": "foundation.near", "token_ids": ["aurora_alpha", "proximitylabs_ft"], "amounts": ["1","100"], "authorized_id": "thirdparty.near" }, ] } ``` ```js EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_transfer", "data": [ {"old_owner_id": "user1.near", "new_owner_id": "user2.near", "token_ids": ["meme"], "amounts":["1"], "memo": "have fun!"} ] } EVENT_JSON:{ "standard": "nep245", "version": "1.0.0", "event": "mt_transfer", "data": [ {"old_owner_id": "user2.near", "new_owner_id": "user3.near", "token_ids": ["meme"], "amounts":["1"], "authorized_id": "thirdparty.near", "memo": "have fun!"} ] } ``` ## Further methods Note that the example events covered above cover two different kinds of events: 1. Events that are not specified in the MT Standard (`mt_mint`, `mt_burn`) 2. An event that is covered in the [Multi Token Core Standard](Core.md). (`mt_transfer`) This event standard also applies beyond the three events highlighted here, where future events follow the same convention of as the second type. For instance, if an MT contract uses the [approval management standard](ApprovalManagement.md), it may emit an event for `mt_approve` if that's deemed as important by the developer community. Please feel free to open pull requests for extending the events standard detailed here as needs arise. ## Drawbacks There is a known limitation of 16kb strings when capturing logs. This can be observed from `token_ids` that may vary in length for different apps so the amount of logs that can be executed may vary.
--- sidebar_position: 4 sidebar_label: "Add a puzzle" title: "Adding a new puzzle now that we're using a collection that can contain multiple crossword puzzles" --- import blankCrossword from '/docs/assets/crosswords/chapter-2-crossword-blank.png'; import teachingDeployment from '/docs/assets/crosswords/teaching-just-teacher--herogranada.near--GranadaHero.jpeg'; import recreatingSubaccount from '/docs/assets/crosswords/erase-recreate-subaccount--3one9.near--3one92.gif'; # Adding a puzzle We're going to make a new puzzle, which means we need to provide the smart contract with a set of clues and info about the answers. Of course, we'll not be sending the *answers* to the smart contract, otherwise everyone could see. We will, however, send details about each clue, including: - The clue number - Whether it's a down or across clue - The coordinates (x and y position) - The length of the clue. (How many letters) Essentially, we're going to tell the smart contract enough information for an empty puzzle like this: <img src={blankCrossword} alt="Blank crossword for chapter 2 of the crossword puzzle smart contract tutorial" width="600"/> <br/> (Note that we aren't showing the human-readable clues in the above screenshot, but we will provide that as well.) ## Building and deploying Let's use the same steps we learned from the first chapter: <figure> <img src={teachingDeployment} alt="Teacher shows chalkboard with instructions on how to properly deploy a smart contract. 1. Build smart contract. 2. Create a subaccount (or delete and recreate if it exists) 3. Deploy to subaccount. 4. Interact. Art created by herogranada.near" width="600"/> <figcaption>Art by <a href="https://twitter.com/GranadaHero" target="_blank">herogranada.near</a></figcaption> </figure> <br/> Navigate to the `contract` directory, then run the build script for your system: ./build.sh If following from the previous chapter, you'll likely have a subaccount already created. For the purpose of demonstration, we're calling the subaccount (where we deploy the contract) `crossword.friend.testnet` and the parent account is thus `friend.testnet`. Let's delete the subaccount and recreate it, to start from a blank slate. <figure> <img src={recreatingSubaccount} alt="Animation of an alien in space with a computer deleting and re-writing the account crossword.friend.testnet Art by 3one9.near" width="600"/> <figcaption>Art by <a href="https://twitter.com/3one92" target="_blank">3one9.near</a></figcaption> </figure> <br/> Here's how to delete and recreate the subaccount using NEAR CLI: ```bash # Delete the subaccount and send remaining balance to friend.testnet near delete crossword.friend.testnet friend.testnet # Create the subaccount again near create-account crossword.friend.testnet --masterAccount friend.testnet # Deploy, calling the "new" method with the parameter for owner_id near deploy crossword.friend.testnet --wasmFile res/crossword_tutorial_chapter_2.wasm --initFunction new --initArgs '{"owner_id": "crossword.friend.testnet"}' ``` Now we're ready to construct our new crossword puzzle and add it via the `new_puzzle` method. Let's start with the clues for this new puzzle. ## The clues We're going to use these clues below for our improved puzzle. The **Answer** column will not get sent to the smart contract when we call `new_puzzle`. | Number | Answer | Clue | (x, y) coords | length | | ----------- | ----------- | ----------- | ----------- | ----------- | | 1 | paras | NFT market on NEAR that specializes in cards and comics. | (1, 1) | 5 | | 2 | rainbowbridge | You can move assets between NEAR and different chains, including Ethereum, by visiting ______.app | (0, 2) | 13 | | 3 | mintbase | NFT market on NEAR with art, physical items, tickets, and more. | (9, 1) | 8 | | 4 | yoctonear | The smallest denomination of the native token on NEAR. | (3, 8) | 9 | | 5 | cli | You typically deploy a smart contract with the NEAR ___ tool. | (5, 8) | 3 | The x and y coordinates have their origin in the upper-left side of the puzzle grid, and each row and column start at 0. ## Solution hash Let's derive the sha256 hash using an [easy online tool](https://www.wolframalpha.com/input/?i=sha256+%22paras+rainbowbridge+mintbase+yoctonear+cli%22) (there are many other offline methods as well) to discover the solution hash: d1a5cf9ad1adefe0528f7d31866cf901e665745ff172b96892693769ad284010 ## Add the puzzle Add a new puzzle using NEAR CLI with this long command, replacing `crossword.friend.testnet` with your subaccount: ``` near call crossword.friend.testnet new_puzzle '{ "solution_hash": "d1a5cf9ad1adefe0528f7d31866cf901e665745ff172b96892693769ad284010", "answers": [ { "num": 1, "start": { "x": 1, "y": 1 }, "direction": "Down", "length": 5, "clue": "NFT market on NEAR that specializes in cards and comics." }, { "num": 2, "start": { "x": 0, "y": 2 }, "direction": "Across", "length": 13, "clue": "You can move assets between NEAR and different chains, including Ethereum, by visiting ______.app" }, { "num": 3, "start": { "x": 9, "y": 1 }, "direction": "Down", "length": 8, "clue": "NFT market on NEAR with art, physical items, tickets, and more." }, { "num": 4, "start": { "x": 3, "y": 8 }, "direction": "Across", "length": 9, "clue": "The smallest denomination of the native token on NEAR." }, { "num": 5, "start": { "x": 5, "y": 8 }, "direction": "Down", "length": 3, "clue": "You typically deploy a smart contract with the NEAR ___ tool." } ] }' --accountId crossword.friend.testnet ``` Note that our contract name and the account we're calling this from are both `crossword.friend.testnet`. That's because we added a check at the top of `new_puzzle` to make sure the predecessor is the `owner_id`. Now our smart contract has information about this second crossword puzzle. Let's explore how to make our frontend have a login button and truly turn this into a decentralized app (dApp)!
Call for Founders and Developers to Qualify Your B.O.S Apps Before NEARCON ‘23 NEAR FOUNDATION October 30, 2023 Dear NEAR B.O.S Developer Community, This week, the Pagoda product team launched the App Library to help B.O.S founders and developers showcase and promote their apps. With over 200 applications powered by B.O.S and more than 11,000 components now in the ecosystem, the App Library is a page on near.org designed to help users and community members find your applications and promote greater usage across the NEAR ecosystem. The App Upvoting Event: NCON Bounty To find the first group of featured apps on App Library, we are launching the App Upvoting Event as a NCON Bounty to invite all NEARCON attendees to upvote and decide who gets featured! “NCON Bounties” is a Web3 gamified event experience for attendees to engage throughout the event. Attendees will earn NCON by completing Bounties and have the option to redeem NCON for food, merchandise, and more. Participants who decide to complete this special NCON Bounties experience will also help select the first group of featured apps in the B.O.S. App Library. How to Qualify and Get Your App Featured? To ensure your dApp shines during this event, here’s what you need to do. The following steps can be be found in the B.O.S interface for those who want to participate — simply go to the Metadata page of your app and follow the instructions below: Create a Captivating Description Craft a compelling introduction to your dApp. Highlight its unique features and value proposition. Pro tip: Add screenshots to make your dApp visually appealing and easy to understand. (Description is required!) Tag Your App First, make sure to tag the component that holds the entry to your project experience as App. Then, choose the category that best represents your dApp—Earn, Play, Develop, Engage. (Choosing one of these four categories is required! If you applied more than one of these four tags, then we will only use the latest one you applied.) Add additional tags for improved discoverability. Make it easy for users to find and appreciate your work. (These categories are suggested from research around users’ needs, broken down by categories and industry app store benchmarks. Check near.org/applications on how these categories are currently being used) Spread the Word It’s time to promote! Rally your community, spread the news across your networks, and encourage users to like and engage with your dApp. The more upvotes your app gets, the greater your chances of securing a top spot. Why Participate? The App Library isn’t just a catalog — it’s an interactive platform that spotlights the capabilities of the NEAR B.O.S. It will become the most visited page on near.org and serves as a gateway to the NEAR Ecosystem. By participating, you have the chance to feature prominently on the App Library and the NEAR homepage for the next three months, gaining exposure and recognition across the NEAR ecosystem and beyond. What’s the Payoff? Your active participation can lead to significant rewards: Top 8 Featured dApps The dApps with the highest number of upvotes from this event will be showcased prominently on the landing page of the App Library for the next three months, putting your creation on the most visited page on near.org. Category Leaders The top 4 dApps in each category will be prominently featured on category pages, such as Earn, Play, Develop, and Engage. This targeted exposure aligns with the core needs and use cases of the diverse NEAR user base. What’s Next? Upvote Button Enabled 2 days Before NEARCON 2 days before NEARCON, you will see an upvote button appear on the details pages of your qualified Apps. Any users who have an account on near.org can now send their support by hitting that upvote button. This upvote button will be disabled two days after NEARCON, and the total number of upvotes you received in the event will be displayed for 6 months on your details page as your participation badge. NEARCON attendees will be incentivized to engage with App Upvoting by earning NCON QR code and event posters will be promoted at the NEARCON venues to encourage them to complete this Bounty. In addition, this Bounty will be part of the NCON product for NEARCON participants to earn more NCON, so we will make sure your dApps get plenty of exposure. Event Timeline Summary October 27th — Submit your App for Qualification. App Upvoting Bounty Event Page made available on near.org. Qualified Apps will be Fetched (Qualified Apps will be fetched continuously on one-hour intervals throughout the NEARCON event through November 13th). November 3rd — Upvote button enabled + counters started. November 13th — Upvote disabled + results calculated. November 17th — Results display + feature apps updated on main App Library page. The primary goal of the App Library is to celebrate the creativity and efforts of NEAR developers and founders. To increase visibility, boost engagement, and get valuable feedback from the whole NEAR community on your app, make sure to register your apps as qualified and participate in the App Upvoting NCON Bounty.
--- id: exposing-validators-metrics-to-pagoda title: Exposing Validators' Metrics to Pagoda sidebar_label: Exposing Validators' Metrics to Pagoda sidebar_position: 8 --- ## Exposing Validator Metrics[^1] The following instructions are applicable for mainnet validator nodes. We kindly asking you to expose port 3030 to our scrapper, which is running from following addresses: 35.204.219.60 34.90.9.220 It's highly recommended to deny traffic from other sources. The following instructions are applicable for mainnet validator nodes. > Note: We take security seriously, so we put a lot of effort into doing things right on this front. Also, as we appreciate your eventual concerns, we are happy to disclose architecture on our end, so you can put your mind at ease. Please make sure that metrics are working - by looking at localhost:3030/metrics - if it doesn’t work - please see the instructions below on configuring neard. ### How are we going to use the data? The collected data will be used to monitor the health and performance of the network in general. We will use the data to look into performance of low-level details of running details, both in aggregate and of individual nodes. However, note that we are not planning to investigate performance issues or missing blocks of individual nodes. We are only interested in the issues affecting the chain in general. ### Share you public IP with us Please fill-in this form Sharing Validator Metrics with Pagoda - https://forms.gle/rQwwe9q4PKuUmGAx9 ### Prerequisites - *Linux* node [running validator](https://near-nodes.io/validator/compile-and-run-a-node#mainnet) - Up to date distribution - Root access to box (to configure firewall) - Public IPv4 address If you haven't done it yet, please [install jq](https://stedolan.github.io/jq/download/). Debian based systems ```shell sudo apt install jq ``` [Redhat/Centos](https://www.cyberithub.com/how-to-install-jq-json-processor-on-rhel-centos-7-8/) ```shell sudo yum install jq -y ``` ### 1. Configure firewall We kindly asking you to expose port 3030 to our scrapper, which is running from following addresses: - **35.204.219.60** - **34.90.9.220** It's highly recommended to deny traffic from other sources. Based on your current setup, you can follow step for iptables or nftables configuration. Please don't forget to make this change persistent, though particular steps are not in scope of this short document. #### 1.1 iptables ```shell # Define chain to allow particular source addresses iptables -N trusted-pagoda-scrappers iptables -A trusted-pagoda-scrappers -s 35.204.219.60 -j ACCEPT iptables -A trusted-pagoda-scrappers -s 34.90.9.220 -j ACCEPT iptables -A trusted-pagoda-scrappers -j DROP # Accept incoming packets for neard only from trusted sources iptables -A INPUT ! -i lo -p tcp --dport 3030 -j trusted-pagoda-scrappers ``` #### 1.2 nftables ```shell # Define chain to allow particular source addresses nft 'add chain ip filter trusted-pagoda-scrappers' nft 'add rule ip filter trusted-pagoda-scrappers ip saddr 35.204.219.60 accept' nft 'add rule ip filter trusted-pagoda-scrappers ip saddr 34.90.9.220 accept' nft 'add rule ip filter trusted-pagoda-scrappers drop' # Accept incoming packets for neard only from trusted sources nft 'add rule ip filter INPUT iifname != "lo" tcp dport 3030 jump trusted-pagoda-scrappers' ``` ### 2. Configure neard Rpc needs to listen on port **3030**, and we also like the debug page to be enabled. ```shell T=$(mktemp) &&\ jq '.rpc.addr = "0.0.0.0:3030" | .rpc.enable_debug_rpc = true' \ ~/.near/config.json > $T &&\ cat $T > ~/.near/config.json && rm $T ``` If you don't have `jq`, you can always edit configuration file manually ### 3. Restart neard Perhaps you have systemd unit, then simply do ```shell sudo systemctl restart neard ``` If you started neard manually, you can use something like following (assuming bash) ```bash PID=$(pgrep neard) WORKDIR=$(readlink "/proc/$PID/cwd") mapfile -d '' -t COMMAND < "/proc/${PID}/cmdline" kill $PID && cd "$WORKDIR" && eval "${COMMAND[@]}" ``` ### 4. DNAT If your validator is not running on public IP, please configure DNAT to forward port 3030. ### 5. Share you public IP with us TBD ### 6. Enjoy aggregated metrics TBD ### 7. Can I volunteer to have my metrics scraped? Yes, ping us using TBD method and follow the same instructions in this doc. ## Overall architecture As promised, here's a description of the network layout at our end, including some security measures. ![](/images/network_layout.svg) First of all, there's a dedicated GCP project. That's where we have created VPC with a private subnet, and the instance running Prometheus scraper. This instance is based on Ubuntu 22.04.LTS and is kept up to date, including all security updates. On top of that, it is running in a very restricted environment. The firewall grants only egress HTTP to port 3030 on your end and denies all other incoming traffic. The only exception is the ssh port for maintenance. That is, however, allowed only through the GCP IAP tunnel. To allow populating the Grafana dashboard, we also allowed HTTPS egress to a specific Grafana host. On the Grafana side, all metrics are anonymized, the Dashboard is read-only, and it's accessible only to Authorized Users. Therefore there is no way to de-anonymise data and use them for anything nasty. [^1]: This document has [published version](https://pagodaplatform.atlassian.net/wiki/spaces/DOCS/pages/149979169/Exposing+validators+metrics+to+Pagoda) which lives by its own life now.
Hacking a New World with MetaBUILD III DEVELOPERS September 1, 2022 UPDATE: MetaBUILD III’s Pre-Accelerator Program has some new details. Scroll down to the “After the Hack” section for more information. Six months ago, NEAR wrapped up the MetaBUILD 2 hackathon just as the world shut down. New challenges emerged, both inside and outside the NEAR ecosystem. The crypto market itself was seemingly falling apart, and everyone was talking about the looming “Crypto winter”. It was clear that in order to continue, a new, creative approach would be necessary. NEAR was founded during some of the gloomiest times of the previous “Crypto winter”, so at least some of this was already familiar territory. In fact, NEAR’s resilient design was informed by the uncertainty in the markets surrounding its release. This resilience is not just evident in the technology, but it can also be seen throughout the ecosystem. To maintain the health of its vibrant community, NEAR focused the aim of its hackathons towards a broader, more ambitious journey for participants—what if these hackathons could foster each team from ideation all the way to forming a Web3 start-up with a market-ready product? MetaBUILD III: A Bigger, Better Impact MetaBUILD is considered one of the biggest hackathons in the blockchain community. With a $1 million in prizes pool, nearly 4,000 participants, and more than 350 submissions from across the world, it has helped realize ideas from streaming tokens to metaverse worlds. In fact, some of these winners will be featured at NEARCON in September, so the community can listen to their stories and learn from their challenges. This year, MetaBUILD III returns with its $1 million in prizes, with registrations opening today and submissions starting September 23rd. But participants should expect to see the hackathon’s format evolve. It’s shaping it up to become an 8-week product-oriented incubation program, hosted by Pagoda, focused on supporting teams beyond the prize money, towards securing funding, and producing a market-ready prototype. Here’s what else is new: Instead of the Welcome track (for newly created projects), a Web2 track will be established to help existing teams integrate NEAR blockchain into their current products. Only newly created or substantively modified projects are allowed to enter the Native track to ensure that participants are committed to remaining in the ecosystem even after they win. Proofs of concept projects built during NEARCON’s 48hs IRL hackathon are welcome to join MetaBUILD. Challenges instead of bounties: MetaBUILD III is looking for sustained product teams who understand their market and are committed to building solutions addressing some of the most pressing challenges of today: rising unemployment, the energy crisis, refugee crises, climate change, access to education and other resources, media censorship, etc. This shift in perspective centers on an understanding of how impactful $1 million could be in the right hands. It is not only about proving great ideas, but growing them as products that can make a long-term impact in the ecosystem and beyond! Ways to MetaBUILD Whether you are a solo hacker or an ecosystem partner, there are several ways to participate in MetaBUILD III: As a developer Incubate your project from idea to an MVP in 8 weeks. Find some talented teammates, and win $20-60k to continue building. Learn more > As a non-technical person Pivot your career into Web3, and join one of the teams as a designer, bizdev expert, product manager, or copywriter to build a winning project together. As a NEAR community member Host a workshop, share your success story, or provide mentorship to participants. Learn more > As a Web3 company or VC Spread the word about MetaBUILD in your community, apply to become a mentor or a judge, or host an IRL event to inspire and support the MetaBUILD community. Learn more > To help fuel the ideas for the next big wave in Web3, a whole educational program will be added to the incubation process: The Education team behind NEAR University will provide self-paced NEAR workshops. Team Docs will present their Zero to Hero tutorialsto make sure the onboarding process is streamlined for everyone. The Pagoda team is already hosting monthly Developer Tooling meetings to demonstrate the features and capabilities of their latest releases. After the Hack: Pre-Accelerator Program from Pagoda and Startup Wise Guys This time, MetaBUILD is not just about building a quick project for competition. The new challenge is for developers to join and build a new product that can hit the market and make a long-term impact on the NEAR ecosystem. From MVP in the hack, to a first market release in the pre-accelerator program, MetaBUILD III is designed to get devs the resources they need to get there with a solid foundation. Of the winning submissions, 30 MetaBUILD projects will be welcomed to a pre-accelerator program hosted by Pagoda and Startup Wise Guys. Projects will have access to a roster of talented NEAR ecosystem mentors, who will support them in their early stages as projects focus on the key components of their business and idea. NEAR mentors will also help winning submissions develop go-to-market strategies with clear goals and propositions, acquire their first customers, operate sustainably for the long term, and attract investment with our roster of talented NEAR ecosystem partners, amongst other things. Ultimately, the pre-accelerator program will help projects prepare to successfully apply for full-time accelerator programs or first-round investment opportunities. The “We” in Web3 Navigating a bear market is a sobering experience, but it is also an inspiring one, because Web3 is ready to face new challenges, new audiences, and new use cases. All it needs are open minds, ambitious ideas, and a willingness to work together to change the world—one decentralized project at a time. Ready to hack the ever changing world? Build your next project on NEAR. MetaBUILD III is here to guide you from idea to market, and beyond. We have the expertise, the funds, and the drive to face new challenges together.
--- id: nft-chain-keys title: NFT Chain Keys Smart Contract sidebar_label: NFT Chain Keys Contract --- The NFT Chain Keys smart contract makes the ownership of remote accounts both provable and transferrable. This new paradigm allows you to create new end-user experiences that leverage provable and transferrable remote accounts as a core primitive. ## Contract overview The [MPC Account Recovery smart contract](https://github.com/near/mpc-recovery) provides a [`sign`](https://github.com/near/mpc-recovery#sign) method that accepts a `path` parameter. This allows one predecessor account to have access to an effectively unlimited number of MPC keys. The NFT Chain Keys contract takes advantage of this property and allows secure transfers of MPC keys between users, using the [NEP-171 NFT contract standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core). The contract also implements new functionality to enable chain key management features. :::info The essence of Multi-Party Computation (MPC) is to enable independent parties to perform shared computations on private information without revealing secrets to each other. ::: ### Standards Besides the NEP-171 contract standard, the NFT Chain Keys contract complies with a full suite of NEP standards: - [NEP-145: Storage Management](https://nomicon.io/Standards/StorageManagement) - [NEP-171: NFT Core](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) - [NEP-177: Metadata](https://nomicon.io/Standards/Tokens/NonFungibleToken/Metadata) - [NEP-178: Approval Management](https://nomicon.io/Standards/Tokens/NonFungibleToken/ApprovalManagement) - [NEP-181: Enumeration](https://nomicon.io/Standards/Tokens/NonFungibleToken/Enumeration) ## Usage Please refer to the smart contract [GitHub documentation](https://github.com/near/multichain-gas-station-contract/blob/master/nft_key/README.md) for usage information: - [Creating new key tokens](https://github.com/near/multichain-gas-station-contract/tree/master/nft_key#creating-new-key-tokens): mint unlimited new NFT chain keys, as long as the account has sufficient storage. - [Issuing signatures](https://github.com/near/multichain-gas-station-contract/tree/master/nft_key#issuing-signatures): generate new signatures based on a submitted payload. - [Approvals](https://github.com/near/multichain-gas-station-contract/tree/master/nft_key#approvals): implement a separate set of approval management functions for using NFTs, which operate similarly to NEP-178. :::tip testnet contract If you want to try things out, this smart contract is available on `nft.kagi.testnet`. ::: --- ## Use Cases for NFT Keys :::info Disclaimer The ideas presented in this section are just initial concepts, and shouldn’t be considered as fully fledged solutions. ::: ### Remote Account Marketplace NFT Keys enable users to buy, sell, and trade remote accounts within a marketplace-style application. For instance, _Alice_, possessing a set of remote accounts with value and history, can mint an NFT key and list these accounts for sale on the marketplace. Potential buyers, like _Bob_, can browse the value of _Alice’s_ accounts and choose to make a purchase. If _Bob_ decides to proceed, they would simply need to acquire ownership of the original NFT key from _Alice_ in exchange for payment, such as in `$NEAR`. Once the transaction is completed, ownership of the accounts transfers to _Bob_. ### Bridgeless Multi-Chain DEX You can create a Multi-chain DEX without bridging by combining Chain Signatures with NFT Keys. Users wishing to swap asset `$A` for asset `$B` would initiate the swap on the bridgeless DEX. Supported by liquidity providers (Automated Market Makers) across multiple chains, the DEX facilitates these swaps. Here's how it works: - A user proposes the swap, specifying asset `$A` in remote `account X` for asset `$B` in remote `account Y`. - The liquidity provider receives asset `$A` from the user and sends the equivalent amount of asset `$B` to a newly created remote `account Y`, along with a minted NFT key. - The NFT key is then sent to the user to complete the swap. Although liquidity providers still need to leverage bridging to settle assets between different pools, users of this exchange type are exposed to reduced bridge risk.
--- id: providers title: RPC Providers --- There are multiple RPC providers from which you can choose from. These providers will work as intermediaries to help you interact with the NEAR network. You'll experience different latency levels depending on the provider's location. You can potentially use multiple providers for redundancy and balancing. :::tip If you want to use a custom RPC provider with NEAR Wallet Selector, [check this example](../../2.build/4.web3-apps/integrate-contracts.md#setting-customs-rpc-endpoints). ::: | Provider | Endpoint Root | | -------------------------------------------------------------------------- | ------------------------------------------------------------ | | [NEAR](setup.md) | `https://rpc.mainnet.near.org` | | [Pagoda](https://www.pagoda.co/console) | `https://near-mainnet.api.pagoda.co/rpc/v1` | | [1RPC](https://docs.1rpc.io/overview/about-1rpc) | `https://1rpc.io/near` | | [All That Node](https://docs.allthatnode.com/protocols/near/) | `https://near-mainnet-rpc.allthatnode.com:3030` | | [ankr.com](https://www.ankr.com/docs/rpc-service/chains/chains-list/#near) | `https://rpc.ankr.com/near` | | [BlockPi](https://chains.blockpi.io/#/near) | `https://public-rpc.blockpi.io/http/near` | | [dRPC](https://drpc.org/) | `https://near.drpc.org` | | [fast-near web4](https://github.com/vgrichina/fast-near) | `https://rpc.web4.near.page` | | [FASTNEAR Free](https://twitter.com/fast_near/status/1779578631318368269) | `https://free.rpc.fastnear.com` | | [Gateway.fm](https://gateway.fm/) | `https://rpc.near.gateway.fm/` | | [GetBlock](https://getblock.io/nodes/near/) | `https://getblock.io/nodes/near/` | | [Lava Network](https://www.lavanet.xyz/get-started/near) | `https://near.lava.build` | | [Lavender.Five Nodes](https://lavenderfive.com/) | `https://near.lavenderfive.com/` | | [NodeReal](https://nodereal.io) | `https://nodereal.io/api-marketplace/near-rpc` | | [NOWNodes](https://nownodes.io/) | `https://near.nownodes.io/` | | [OMNIA](https://omniatech.io) | `https://endpoints.omniatech.io/v1/near/mainnet/public` | | [QuickNode](https://www.quicknode.com/chains/near) | - | | [Seracle](https://docs.seracle.com/) | `https://api.seracle.com/saas/baas/rpc/near/mainnet/public/` | | [Zeeve](https://www.zeeve.io/) | - |
--- id: collections title: Data Structures --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs" Each contract has its own state (storage), which **only they can modify** but [anyone can see](../../../4.tools/cli.md#near-view-state-near-view-state). A contract stores all its data in a `key-value` storage. This however is abstracted from you by the SDK through [serialization](./serialization.md). :::info Contracts [pay for their storage](#storage-cost) by locking part of their balance. Currently it costs **~1 Ⓝ** to store **100KB** ::: --- ## Data Structures The NEAR SDK exposes a series of structures ([Vectors](#vector), [Sets](#set), [Maps](#map) and [Trees](#tree)) to simplify storing data in an efficient way. :::info Instantiation All structures need to be initialized using a **unique `prefix`**, which will be used to identify the structure's keys in the [serialized state](./serialization.md#borsh-state-serialization) <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/docs-examples/blob/main/storage-js/src/index.ts" start="8" end="11" /> </Language> <Language value="rust" language="rust"> <Github url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/lib.rs" fname="lib.rs" start="33" end="38"/> </Language> </CodeTabs> ::: <hr className="subsection" /> ### Vector Implements a [vector/array](https://en.wikipedia.org/wiki/Array_data_structure) which persists in the contract's storage. Please refer to the Rust and AS SDK's for a full reference on their interfaces. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/docs-examples/blob/main/storage-js/src/index.ts" start="25" end="28" /> </Language> <Language value="rust" language="rust"> <Github fname="vector.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/vector.rs" start="12" end="30"/> <Github fname="lib.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/lib.rs" start="7" end="24"/> </Language> </CodeTabs> <hr className="subsection" /> ### Map Implements a [map/dictionary](https://en.wikipedia.org/wiki/Associative_array) which persists in the contract's storage. Please refer to the Rust and AS SDK's for a full reference on their interfaces. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/docs-examples/blob/main/storage-js/src/index.ts" start="33" end="37" /> </Language> <Language value="rust" language="rust"> <Github fname="map.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/map.rs" start="9" end="24"/> <Github fname="lib.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/lib.rs" start="7" end="24"/> </Language> </CodeTabs> <details> <summary>Nesting of Objects - Temporary Solution</summary> In the JS SDK, you can store and retrieve elements from a nested map or object, but first you need to construct or deconstruct the structure from state. This is a temporary solution until the improvements have been implemented to the SDK. Here is an example of how to do this: ```ts import { NearBindgen, call, view, near, UnorderedMap } from "near-sdk-js"; @NearBindgen({}) class StatusMessage { records: UnorderedMap; constructor() { this.records = new UnorderedMap("a"); } @call({}) set_status({ message, prefix }: { message: string; prefix: string }) { let account_id = near.signerAccountId(); const inner: any = this.records.get("b" + prefix); const inner_map: UnorderedMap = inner ? UnorderedMap.deserialize(inner) : new UnorderedMap("b" + prefix); inner_map.set(account_id, message); this.records.set("b" + prefix, inner_map); } @view({}) get_status({ account_id, prefix }: { account_id: string; prefix: string }) { const inner: any = this.records.get("b" + prefix); const inner_map: UnorderedMap = inner ? UnorderedMap.deserialize(inner) : new UnorderedMap("b" + prefix); return inner_map.get(account_id); } } ``` </details> <hr className="subsection" /> ### Set Implements a [set](https://en.wikipedia.org/wiki/Set_(abstract_data_type)) which persists in the contract's storage. Please refer to the Rust and AS SDK's for a full reference on their interfaces. <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/docs-examples/blob/main/storage-js/src/index.ts" start="42" end="46" /> </Language> <Language value="rust" language="rust"> <Github fname="set.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/set.rs" start="9" end="16"/> <Github fname="lib.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/lib.rs" start="7" end="24"/> </Language> </CodeTabs> <hr className="subsection" /> ### Tree An ordered equivalent of Map. The underlying implementation is based on an [AVL](https://en.wikipedia.org/wiki/AVL_tree). You should use this structure when you need to: have a consistent order, or access the min/max keys. <CodeTabs> <Language value="rust" language="rust"> <Github fname="tree.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/tree.rs" start="9" end="24"/> <Github fname="lib.rs" url="https://github.com/near-examples/docs-examples/blob/main/storage-rs/contract/src/lib.rs" start="7" end="24"/> </Language> </CodeTabs> --- ## Storage Cost Your contract needs to lock a portion of their balance proportional to the amount of data they stored in the blockchain. This means that: - If more data is added and the **storage increases ↑**, then your contract's **balance decreases ↓**. - If data is deleted and the **storage decreases ↓**, then your contract's **balance increases ↑**. Currently, it cost approximately **1 Ⓝ** to store **100kb** of data. :::info You can save on smart contract storage if using NEAR Account IDs by encoding them using base32. Since they consist of `[a-z.-_]` characters with a maximum length of 64 characters, they can be encoded using 5 bits per character, with terminal `\0`. Going to a size of 65 * 5 = 325 bits from the original (64 + 4) * 8 = 544 bits. This is a 40% reduction in storage costs. ::: :::caution An error will raise if your contract tries to increase its state while not having NEAR to cover for storage. ::: :::warning Be mindful of potential [small deposit attacks](../security/storage.md) :::
--- id: checklist title: ✅ Checklist --- Once you finished developing your smart contract please go through the following list in order to ensure everything is safe for the end user. :::info Check our [security articles](./welcome.md) to understand how to improve the security of your contract. ::: --- ## Anatomy 1. All private methods are decorated as `private`. ## Environment 2. `predecessor` and `signer` are used correctly through the entire contract. ## Storage 3. Each time the state grows it is ensured that there is enough balance to cover it 4. All collections (i.e. Vector, Map, Tree, etc) have an unique id 5. Check for underflow and overflow!. In rust, you can do this by simply adding the `overflow-checks = true` flag in your `Cargo.toml`. ## Actions 6. When sending money, you leave enough in the contract to cover the storage cost 7. If you are tracking user's fund, you **deduct them before** sending them back to the user. ## Callbacks 8. All private callbacks are marked as `private` 9. All cross-contract calls have a callback 10. All callbacks check for errors and roll back the state if necessary 11. All callbacks return money to the `predecessor` if necessary 12. Callbacks are free of `panic!` 13. All the callbacks are given enough GAS to execute entirely 14. The contract is not left in an exploitable state between a cross-contract call and its callback
--- id: run-rpc-node-with-nearup title: Run an RPC Node (with nearup) sidebar_label: Run a Node (with nearup) sidebar_position: 3 description: How to run an RPC Node with nearup --- *We encourage you to set up your node with Neard instead of Nearup as Nearup is not used on Mainnet. Please head to [Run a Node](/rpc/run-rpc-node-without-nearup) for instructions on how to setup a RPC node with Neard.* <blockquote class="info"> <strong>Heads up</strong><br /><br /> The README for `nearup` (linked above) may be **all you need to get a node up and running** in `testnet` and `localnet`. `nearup` is exclusively used to launch NEAR `testnet` and `localnet` nodes. `nearup` is not used to launch `mainnet` nodes. </blockquote> ## Prerequisites - [Git](https://git-scm.com/) - [Nearup](https://github.com/near-guildnet/nearup): Make sure [`nearup`](https://github.com/near-guildnet/nearup) is installed. You can install `nearup` by following the instructions at https://github.com/near-guildnet/nearup. --- ### Steps to Run an RPC Node using `nearup` Running a RPC node is very similar to running a [validator node](/validator/running-a-node) as both types of node use the same `nearcore` release. The main difference for running a validator node is requiring `validator_key.json` to be used by the validator node to support its work of validating blocks and chunks on the network. First, clone the `nearcore` repo: ```text git clone https://github.com/near/nearcore.git cd nearcore ``` Checkout the version you wish to build: ```bash git checkout <version> ``` You can then run: ```bash make neard ``` This will compile the `neard` binary for the version you have checked out, it will be available under `target/release/neard`. Note that compilation will need over 1 GB of memory per virtual core the machine has. If the build fails with processes being killed, you might want to try reducing number of parallel jobs, for example: `CARGO_BUILD_JOBS=8 make neard`. NB. Please ensure you build releases through `make` rather than `cargo build --release`. The latter skips some optimizations (most notably link-time optimisation) and thus produces a less efficient executable. ```bash nearup run testnet --binary-path path/to/nearcore/target/release ``` You will then be prompted for an Account ID below. You should leave this empty as you are running an RPC node, not a validator node. ```text Enter your account ID (leave empty if not going to be a validator): ``` Wait until initialization finishes, use the following command to follow logs: ```bash $ nearup logs --follow ``` Then run: ```bash $ nearup stop ``` Retrieve a copy of the latest RPC snapshot from S3: ```bash $ aws s3 --no-sign-request cp s3://near-protocol-public/backups/testnet/rpc/latest . $ LATEST=$(cat latest) $ aws s3 --no-sign-request cp --no-sign-request --recursive s3://near-protocol-public/backups/testnet/rpc/$LATEST ~/.near/data ``` Finally, run the following command and the node should start syncing headers: ```bash $ nearup run testnet ``` >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
NEAR and Popp Partner on Customer Engagement for Small Businesses NEAR FOUNDATION March 24, 2023 NEAR Foundation is excited to announce a new partnership with Popp, a company helping small businesses generate better customer engagement using Web3 technology. As part of the partnership, Popp — a solution-as-a-service (SaaS) for small-to-medium consumer brands — will launch its white-labeled tools and products exclusively on NEAR. How Popp works for small businesses Popp helps consumer brands launch micro community spaces for customers, which are embedded in their online stores. Milestone-based customer rewards then drive more engagement for brands. The NEAR partnership will, for instance, allow Popp’s customers to issue NFTs when certain milestones are met. On Popp, brands can build deeper, more meaningful connections with customers by rewarding them across multiple touch points. Through these bespoke projects, Popp has already generated over £57k in revenue ($69k USD) in six months via six pilot partners. Popp has two interfaces. On the business side, each brand gets its own custom dashboard, where they control its loyalty and rewards program and see customer data. On the customer side, users can see all of the user activity in one place, like new members and the number of “Popps” that are live or completed. Customers can also create and interact with content — the more they interact with the community, the more coins they can earn. Popp’s customer brands include Batch LDN, perl Cosmetics, Acid Running, Jenki Matcha, and Ocean Bottle. What’s a Popp? A Popp is a small task set by a brand for customers. If customers complete the task, they earn coins that can be used to redeem rewards or unlock experiences. Each brand can set a variety of Popps for their customers, which are micro-tasks that generate value for the brand. This can include creating content, leaving reviews, or referring friends. Completing various Popps give users things like discounts and vouchers, but brands can also set up popps for charity, sustainability, and much more. Through Popp’s “Partnerships” feature, brands can make coins redeemable for rewards from partnering bands. This feature even allows companies to “invite” brands to partner with them for these rewards. Each customer gets their own user profile, through which they can see the number of coins they’ve collected, and explore where to redeem rewards. Head over to Popp to explore the company’s customer rewards ecosystem. Popp’s closed beta is now live and e-commerce brands should head over to the website now to join the waitlist!
Goodbye San Francisco | November 1st, 2019 COMMUNITY November 1, 2019 We had an amazing time at San Francisco Blockchain Week (SFBW), hosting events, attending panels, and meeting so many amazing people! Highlights included a discussion on App Chains vs. dApps with Cosmos, an event on blockchain gaming, and a panel on blockchain adoption with some of our beta program projects. Sounds amazing but you could not make it? Don’t freak out, we will release the recordings soon! Prior to SFBW, we joined StakeZero Ventures at their introductory events of the Future of Blockchain Competition in Oxford, Cambridge, and London. You can find more information about the event here. (Late applications may still be accepted.) Lastly, we are continuing our lunch series on the NEAR Protocol. Check out the previous videos and let us know what aspects of the protocol you would like to learn more about. To shard or not to shard that is the question! (Source) COMMUNITY UPDATE We have over 250 sign-ups for Stake Wars, NEAR Protocol’s incentivized testnet program. You can still join us and practice your powers. To learn more jump over to our latest announcement. This month’s ambassador challenge was to record a video stating why they support NEAR and help to grow the community; we received some great content! Check out Buster’s & Cristian’s video for example. UPCOMING EVENTS *Please stand by. This section will be updated soon* Now for real, events take a lot of time to prepare and organise. While we love to meet everyone, talk to the community (YOU) and have discussions, we are, after all, building a blockchain. We will let you know ASAP about upcoming events. The Future of Blockchain Competition Introduction Event in London (Source) WRITING AND CONTENT If you are thinking about building on NEAR or want to get an extra push to get started, check out the Future of Blockchain Competition, organised by StakeZero Ventures. If you are wondering how we get things done, check out unicorn Alex live coding core features of the NEAR Protocol. We now have two (one, two) Chinese versions of our Economics paper; translated by our ambassadors. Here is the original version. Unicorn Alex doing his magic ENGINEERING UPDATES 167 PRs across 26 repos by 20 authors. Featured repos:nearcore,nearlib,near-shell,near-wallet,near-bindgen, near-fiddle-api, NEARStudio, assemblyscript, borsh, create-near-app, stakewars and near-explorer; Check out Alex live coding core features of the NEAR Protocol A massive refactoring of Nightshade that significantly reduces the number of messages exchanged and also addresses issues with chunk producers going offline. Finality gadget routine that computes the last finalized block and implementation of the fork choice rule that respects the finality gadget. The second part of the whiteboard lunch series is live Adding genesis tools for stakewars into dockerfile in nearcore Speeding up / less network for block sync in nearcore Cleanup and usability improvements in near-bindgen Seed phrase recovery support in near-wallet Implemented multinet support in near-explorer Added a cross-contract call example in nomicon 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/
Why Chain Abstraction Is the Next Frontier for Web3 A POST FROM ILLIA POLOSUKHIN January 24, 2024 Most of today’s dapps are not actually dapps, i.e. decentralized applications. If you need to leave the app in order to start using it, it’s not really an app––it’s just a frontend. If users have to manually onboard themselves through exchanges and manage multiple accounts and gas fees and bridges, did you even build an app? I think not––which may explain why only a few million people in the world are using dapps. If we want to see mainstream adoption of Web3 because we believe a more open, decentralized internet that supports self-sovereignty for all people is better for the world, then we will need to do better. The prevailing narrative in Web3 today is modularity, or separating out the different functional layers of a blockchain, i.e. settlement, data availability, and execution, for the sake of scalability. Layer-twos, optimistic and ZK rollups, data availability layers, sidechains, and state channels are all examples of modularity solutions. This proliferation of blockchains & rollups has led to a degraded experience for users and developers. Modularity and a world of many chains leads to more fragmentation of liquidity, apps, and users––a significant degree of complexity in the user experience that no mainstream user could ever be expected to navigate. This also applies to developers, who feel pressure to commit to a specific tech stack while limiting the audience for their application. Now when you build a dapp, you’re enshrining yourself into a small addressable market by choosing a single chain. I want to propose a better vision for the entire Ethereum ecosystem and all of Web3: let’s work together on advancing mainstream adoption via chain abstraction. The idea is that blockchains must be abstracted away from the user so they are not barriers to entry or participation. NEAR has been focusing on this vision since 2018 and today has achieved the most users of any network in Web3: 12.4 million monthly active accounts and 34 million accounts overall. Here’s how we can defragment Web3 and onboard billions of users via dapps. What does this look like for the user? Let’s imagine how using a dapp should actually work: transacting across networks and navigating between experiences with ease, all within a single interface. As one example, Alice picks up her phone and opens KAIKAI from her lockscreen. She orders a smoothie from a local place and sees in the app that there’s a discount offer from her favorite clothing store, Maison, and orders a pair of shoes for the spring. Alice sees she has earned enough KAICHING rewards to get a badge from Maison, not knowing it’s an NFT on Polygon, and redeems it in her account. When she browses Maison on the KAIKAI app later that day, she notices that her new badge reveals an offer to buy tickets for an exclusive event at their store with a DJ she likes. She buys the ticket with KAICHING and receives 2 tickets, still not knowing it’s an NFT on Arbitrum. Since she gets a +1, Alice invites her friend Bob to come with her and pings him for his address. Bob sends his NEAR address to Alice and opens his app to check out the ticket. He sends Alice some ETH to say thanks for the invite and looks at the different cryptos he has in his account. Since he’s on the metro and has some time, he decides to buy some BTC and borrow against it with USDC so he can mint a Fighting Dragon NFT on Magic Eden. His friend Charles texted him earlier to get one so they could play each other in Year of the Dragon, a new game on NEAR where their dragons can battle each other for coins they can stake. All of these interactions and transactions can take place in a single interface and in a completely private way. There are no wallets, no switching networks, and no transaction fees to deal with; those are embedded directly in the swap or the buy and handled on behalf of the user. Alice didn’t need to worry about which network the ticket is on and Bob can send her funds for the ticket in whichever crypto he wants, moving seamlessly into buying a different one the next second. All inside of an app. This is the level of seamlessness we should be striving for as an ecosystem. How do we achieve Chain Abstraction? Everyone building an app in Web3 will benefit from being able to access such a broad market of potential users as in this example––i.e. anyone who uses apps. Whereas today, developers choose a network based on access to liquidity or the users of a specific rollup or chain, in a chain abstraction future they can just build with the best tech. The users will show up for the best experiences. Imagine if a Gmail user couldn’t just send a message to an Outlook address––it doesn’t make sense. The same is true for Web3 addresses. The core assumption of chain abstraction is: end users don’t care about the underlying blockchain. They just want apps to work. In reality, blockchains are simply infrastructure to receive value out of Web3: security of assets from seizure, economic opportunity, removing middlemen for transactions, global permissionless identity, data provenance, entertaining experiences, and more. The core goal of chain abstraction is to defragment the increasingly fractured modular landscape of Web3. While this will be most visible at the user experience layer, this defragmentation of liquidity and accounts is possible thanks to innovation at the security layer. Zero knowledge (ZK) introduces a principally new approach to ledger security. Whereas before one needed to trust a decentralized set of validators, now even a single computer can prove that rules were followed with a simple proof. This means that where before, developers would be forced to either build on a shared chain or spend immense resources to launch a new one, now they can just spin one up on their single server. This new paradigm introduces the idea of cross settlement: as more chains become fully ZK provable, if some proof is published on other chains, there is no way to revert this chain without also needing to revert other chains. Transactions from one chain can also settle on multiple others via ZK proofs. This provides mesh security as all proofs continuously get aggregated, allowing the safe movement of assets between such chains. In order to achieve unified security, two things are needed at the bottom of the stack: Data availability, which provides a way for everyone to sync even if the operator is offline, and a decentralized sequencer for applications that don’t have a central operator. The next layer is identity with that security unified. Users can have an address on all possible chains and move assets between them freely. From a user perspective, this should be a single account where they interact with apps on different chains, and assets either get bridged or swapped automatically. I call this “account aggregation” and will share more details about it in another post soon. NEAR will launch the next version of FastAuth in March 2024, which has mapping for NEAR addresses to EVM, Bitcoin, and other addresses. NEAR accounts can request to sign a transaction for another chain. This allows them to build multichain apps directly as smart contracts on NEAR. The final layer is unifying the experience layer, or the application layer (e.g. DapDap)––providing a way to interact with apps on various chains without users switching or needing to leave a single interface. A decentralized frontend can provide easy components to build in a chain-abstracted way. NEAR can achieve this through NearJS, combining data indexing and decentralized frontends––V2 also coming in March 2024. How is NEAR enabling Chain Abstraction? The NEAR ecosystem has been building towards the chain abstraction vision since its beginnings in 2018, focusing on usability, a flexible account model, and a highly scalable blockchain that could support mainstream apps with billions of users. Today, the stack has expanded to support full chain abstraction across chains and all kinds of apps. Scalable, integrated blockchain that can grow to 1B+ daily active accounts. Security aggregation stack consisting of NEAR DA, zkWASM (collaboration with Polygon Labs), and EigenLayer-powered Fast Finality. Account aggregation on top of this to enable transacting on all chains using a single account Data layer that supports everything from monolithic, integrated, modular, private and permissioned chains to query data in a predictable protocol. Intent relayers that can execute complex intents across chains using this infra. Decentralized frontends that provide discoverability and composability for multiple apps across chains into one experience. Super (app) wallets that are user friendly and offer a way to navigate all of Web3 without having to switch networks or deal with gas tokens and bridges. Importantly, each of these layers supports builders from across Web3, including Ethereum, rollups & L2s, and beyond––the multichain future is becoming the chain abstraction future. Call to Action 2024 is the year of hiding the complexity of multichain infrastructure to deliver the Web3 experiences we’re striving for. Improving usability and discoverability should be a priority for all Web3 builders, as well as solving for liquidity fragmentation and security tradeoffs. Let’s make chain abstraction a movement. The NEAR ecosystem invites builders from across Web3 to take advantage of the solutions we’re offering and to collaborate with us to build more chain abstraction solutions together. Stay tuned for more news on collaborations as well as details on an exciting event that NEAR Foundation will co-host at ETHDenver 2024. Special thanks to Zaki Manian for conversations that led to this post as well as for his review.
NEAR Foundation Funding Team Report: October 2022 NEAR FOUNDATION November 23, 2022 Welcome to our Funding Team Report that captures and highlights data for the month of October 2022. The purpose of this document is to provide transparency regarding our Funding Team’s activities last month, and is to be shared publicly to the NEAR ecosystem and our investor network. Summary 1. Grant data 1.1. Approved Grant program data 1.2. Grant highlights 1.3 Completed projects & Milestone data 1.4 Effectiveness of the funding program 2. External funding in the NEAR Ecosystem 3. Ecosystem highlights 1. Grant data 1.1. Approved Grant Program data Data reflects projects that have applied for a Grant via the Grants Program and that have been signed by the NEAR Foundation during the month of October (01.10.2022 to 31.10.2022). *Note: all applications have been processed. General Grant data Applications received* 📥 Grant Agreements signed ✅ Conversion rate Average Grant Amount Committed amount in dollars 💵 141 14 8.5% $40 K $564 K Grant tracks** Activation (up to $10 K) 3 Builder (up to $50 K) 8 Advanced Builder (up to $100 K) 3 ** For more information please have a look at our grant tracks. Grants per category NFTs 5 Infrastructure / Wallets 3 Social Impact 1 Institutional / Financial 1 Gaming / Metaverse 1 DAOs 1 Other 2 Grants per country (Top 5) United States 3 United Kingdom 3 Switzerland 1 Singapore 1 Thailand 1 1.2. Grant highlights This section provides highlights of grants that have been signed during the month. NFT projects KINO website Advanced Builder United States Disrupting Hollywood by allowing retail to invest in film making, create experiences for token holders and collectives. Founded by an Executive Producer who has sold shows with Matt Damon and Jimmy Kimmel, and a 3x Tech Founder (USC Law/London School of Economics) whose last web3 startup reached over 500k holders and $500m mcap. KwikTrust website Builder United Kingdom The Platform allows for easy, self-certified and third-party validation of files, with the results stored securely on a blockchain, creating an irrefutable record of activity. This will increase trust and transparency in the NEAR NFT space and be a platform for existing and upcoming NFTs. Endless website Builder Thailand Web3 gaming launchpad and building SDKs for gaming developers. The team has plenty of experience building web3 gaming platforms with their current company called Playfix Haus Passport website Builder United Kingdom Data base on the NEAR blockchain that acts as a repository for information relating to a property, like a passport for a house. The goal is to provide a transparent platform to make buying and selling houses simpler, safer and quicker. NFT.HipHop website Builder United States NFT.HipHop is being developed to be the primary destination for all Hip Hop-centric NFT/Web3 projects. The founder is deeply rooted within the NEAR Ecosystem and aims to bring his existing large web2 community in the Hip Hop space to NEAR. Infrastructure / Wallets projects Blockversekit website Advanced Builder Spain NFT Analytics tool that allows tracking of held NFTs and provides updates for upcoming mints and collections, with the focus on approaching the communities and people about NEAR. Strong connection with the TENK Bay and drives NFT growth within NEAR. MAP Protocol website Builder Singapore MAP Protocol is an omnichain layer of Web3 with highly secure cross-chain communication built upon light-client and zk-SNARK technology. MAP Protocol connects both EVM & non-EVM chains, extending the EVM layer with pre-compiled smart contracts of destination chains seamlessly. NEARBlocks website Builder Indonesia NEARBlocks features optimisations being provided by Invoker Labs. Institutional / Financial projects Datality website Activation United States Datality brings trust and safety to connect researchers with research data providers. A two-sided data marketplace with blockchain as the transparent layer of trust. Social Impact projects Aidonic website Builder Switzerland AIDONIC offers digital cash and voucher assistance, powered by NEAR and by ensuring end-to-end transparency, cost- and speed efficiency and accountability for social fundraising and last-mile aid distribution. DAO’s Community Health Analytics website Builder United Kingdom Provide insights for the Near Ecosystem that improves its ability to collaborate effectively and operate thriving communities thanks to predictive indicators of viability as well as diagnostic tools for DAO Communities. Gaming / Metaverse projects Pixudi website Builder Montenegro Pixudi is an NFT based blockchain project where a traditional race board game meets Heroes of Magic mechanics. It is more than a game, it’s bridge from the real world of board games to the blockchain world of NFT based on DAO mechanics. Other projects Decent.land website Activation Netherlands Modular collection of social and identity protocols. Developers can use part of all of the stack for anything from adding social features to deploying a fully decentralized, token-aware web3 social network. decent.land is built using Arweave for permanent storage and NEAR for user-facing contracts. EV Initiative website Activation Canada EV charging network in the Americas with a web3 value creation mechanism for the drivers. Team has installed over 100 charging slots in the last six months and plans to integrate NEAR for settlements while increasing the installation of charging stations. 1.3 Completed projects & Milestone data Grant agreements are structured with milestones. Depending on the selected grant track, a grant can have from 1 to 5 milestones. For more information the funding team invites you to explore our milestone guide. Projects having completed a milestone ☑️ 53 Projects having completed final milestone ✅ 9 Projects completed per category Infrastructure / Wallets 3 Gaming / Metaverse 3 DAOs 1 Other 2 Infrastructure / Wallets projects MyNearWallet website Advanced Builder Switzerland An inheritor of the official NEAR wallet. The most well-known and feature filled web wallet for the NEAR Ecosystem. BytePay website Builder China Coding to earn, sell open-source product as NFT. BytePay is a platform that supports paid tasks to complete open-source projects on Github. Not only can you code to earn but also sell open-source product as NFT. NEAR Blockchain Event Webhooks website Builder United Kingdom The development of an MVP for a NEAR blockchain event push notification service. DApp developers would be able to subscribe to their contract events in their backend without having to implement their own indexer, instead implementing webhook endpoints to which this service would push updates. Gaming / Metaverse projects Reality NEAR / Advanced Builder United States Reality Near is a multi-metaverse that will combine Virtual Reality and Augmented Reality technologies so that users can experience their different enhanced realities like never before. MeowRush website Builder / MeowRush is a PVP multiplayer game on the NEAR blockchain with different tournament modes: Race, Battle Royale, Obstacles, and Arcade. MeowRush is going to be integrated into the Meowverse metaverse with a Multi-chain ecosystem. Glory Games Worlds website Builder Singapore GameFi for the masses, built on their own native Unreal game engine with Augmented Reality/Virtual Reality engine. DAO’s Mute DAO website Builder United Kingdom Mute is building a safe and secure community that focuses on protecting members of the crypto community by providing accurate and up-to-date information on projects, risk assessments, and education. Other projects SharpShark website Builder Netherland SharpShark is a WEB3 copyright protection service that helps businesses protect and monetize their textual, visual, and other copyrightable content. Double website Builder United States A decentralized co-op platform for AMM liquidity providing that will double LP investors’ return on invested capital while at the same time boost liquidity for projects’ tokens. 1.4 Effectiveness of the funding program Total external funding (overall amount) came from projects that have received a grant (around 40%). 2. External funding in the NEAR Ecosystem This section provides information about external funding in the NEAR ecosystem 2 closed projects in Q4 ‘22 – ($6.2M) 2 finalizing rounds 20 new fundraising processes kicked off 22 VC intros made Closed Rounds (Quarter-to-Date) EmpireDAO – Raised a $2.8m seed round with participation from NEAR Foundation to build a global community starting with a flagship location in NYC. Please stop by the NEAR space at EmpireDAO if you are ever in NYC! t2.world – Raised a $3.4m seed round led by Inflection and Archetype to empower readers and writers to grow their communities in the Web3 space. 3. Ecosystem highlights NEARWEEK is the one-stop-shop for all NEAR related news. Each weekly newsletter and edition is made possible via news contributions from the NEARWEEK community to the NEWS DAO. Subscribe or visit NEARWEEK.com to get your weekly dose of news from the NEARverse! For the month of October we invite you to read through the following newsletters : Newsletter 78 Newsletter 79 Newsletter 80 Newsletter 81
--- id: run-archival-node-without-nearup title: Run an Archival Node sidebar_label: Run a Node 🚀 sidebar_position: 2 description: How to run an Archival Node without nearup --- The following instructions are applicable across localnet, testnet, and mainnet. If you are looking to learn how to compile and run a NEAR Archival node natively for one of the following networks, this guide is for you. - [`testnet`](/archival/run-archival-node-without-nearup#testnet) - [`mainnet`](/archival/run-archival-node-without-nearup#mainnet) <blockquote class="info"> <strong>Heads up</strong><br /><br /> Running an archival node is very similar to running a [validator node](/validator/running-a-node) as both types of node use the same `nearcore` release. The main difference for running an archival node is a modification to the `config.json` by changing `archive` to `true`. See below for more details. </blockquote> ## Prerequisites {#prerequisites} - [Rust](https://www.rust-lang.org/). If not already installed, please [follow these instructions](https://docs.near.org/sdk/rust/introduction#install-rust-and-wasm-toolchain). - [Git](https://git-scm.com/) - Installed developer tools: - MacOS ```bash $ brew install cmake protobuf clang llvm awscli ``` - Linux ```bash $ apt update $ apt install -y git binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev cmake gcc g++ python docker.io protobuf-compiler libssl-dev pkg-config clang llvm cargo awscli ``` --- ### Choosing your `nearcore` version {#choosing-your-nearcore-version} When building your NEAR node you will have two branch options to choose from depending on your desired use: - `master` : _(**Experimental**)_ - Use this if you want to play around with the latest code and experiment. This branch is not guaranteed to be in a fully working state and there is absolutely no guarantee it will be compatible with the current state of *mainnet* or *testnet*. - [`Latest stable release`](https://github.com/near/nearcore/tags) : _(**Stable**)_ - Use this if you want to run a NEAR node for *mainnet*. For *mainnet*, please use the latest stable release. This version is used by mainnet validators and other nodes and is fully compatible with the current state of *mainnet*. - [`Latest release candidates`](https://github.com/near/nearcore/tags) : _(**Release Candidates**)_ - Use this if you want to run a NEAR node for *tesnet*. For *testnet*, we first release a RC version and then later make that release stable. For testnet, please run the latest RC version. ## `testnet` {#testnet} ### 1. Clone `nearcore` project from GitHub {#1-clone-nearcore-project-from-github} First, clone the [`nearcore` repository](https://github.com/near/nearcore). ```bash $ git clone https://github.com/near/nearcore $ cd nearcore $ git fetch origin --tags ``` Checkout to the branch you need if not `master` (default). Latest release is recommended. Please check the [releases page on GitHub](https://github.com/near/nearcore/releases). ```bash $ git checkout tags/1.28.0 -b mynode ``` ### 2. Compile `nearcore` binary {#2-compile-nearcore-binary} In the `nearcore` folder run the following commands: ```bash $ make release ``` This will start the compilation process. It will take some time depending on your machine power (e.g. i9 8-core CPU, 32 GB RAM, SSD takes approximately 25 minutes). Note that compilation will need over 1 GB of memory per virtual core the machine has. If the build fails with processes being killed, you might want to try reducing number of parallel jobs, for example: `CARGO_BUILD_JOBS=8 make release`. By the way, if you’re familiar with Cargo, you could wonder why not run `cargo build -p neard --release` instead. While this will produce a binary, the result will be a less optimized version. On technical level, this is because building via `make neard` enables link-time optimisation which is disabled by default. The binary path is `target/release/neard` ### 3. Initialize working directory {#3-initialize-working-directory} The NEAR node requires a working directory with a couple of configuration files. Generate the initial required working directory by running: ```bash $ ./target/release/neard --home ~/.near init --chain-id testnet --download-genesis --download-config ``` > You can specify trusted boot nodes that you'd like to use by pass in a flag during init: `--boot-nodes ed25519:4k9csx6zMiXy4waUvRMPTkEtAS2RFKLVScocR5HwN53P@34.73.25.182:24567,ed25519:4keFArc3M4SE1debUQWi3F1jiuFZSWThgVuA2Ja2p3Jv@34.94.158.10:24567,ed25519:D2t1KTLJuwKDhbcD9tMXcXaydMNykA99Cedz7SkJkdj2@35.234.138.23:24567,ed25519:CAzhtaUPrxCuwJoFzceebiThD9wBofzqqEMCiupZ4M3E@34.94.177.51:24567` > You can skip the `--home` argument if you are fine with the default working directory in `~/.near`. If not, pass your preferred location. This command will create the required directory structure and will generate `config.json`, `node_key.json`, and `genesis.json` for `testnet` network. - `config.json` - Configuration parameters which are responsive for how the node will work. - `genesis.json` - A file with all the data the network started with at genesis. This contains initial accounts, contracts, access keys, and other records which represents the initial state of the blockchain. - `node_key.json` - A file which contains a public and private key for the node. Also includes an optional `account_id` parameter which is required to run a validator node (not covered in this doc). - `data/` - A folder in which a NEAR node will write it's state. > **Heads up** > The genesis file for `testnet` is big (8GB +) so this command will be running for a while and no progress will be shown. ### 4. Replacing the `config.json` {#4-replacing-the-configjson} From the generated `config.json`, there two parameters to modify: - `boot_nodes`: If you had not specify the boot nodes to use during init in Step 3, the generated `config.json` shows an empty array, so we will need to replace it with a full one specifying the boot nodes. - `tracked_shards`: In the generated `config.json`, this field is an empty empty. You will have to replace it to `"tracked_shards": [0]` To replace the `config.json`, run the following commands: ```bash $ rm ~/.near/config.json $ wget https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/testnet/config.json -P ~/.near/ ``` ### Configuration Update {#configuration-update} The `config.json` should contain the following fields. Currently, NEAR testnet and mainnet have 4 shards. To track all 4 shards, use `"tracked_shards": [0]`. In the future, there will be the possibility to track different or multiple shards. ``` { ... "archive": true, "tracked_shards": [0], ... } ``` Please make sure that the node is not running while changing the `config.json`. Once the config has been changed, you can restart the node and the node will start syncing new archival data. In the case where you want the full archival history, you can delete the data dir and start the node from scratch syncing full history or use one of the latest backups containing the data directory snapshot which can be copied under the near home dir (default: ~/.near/data). ### 5. Get data backup {#5-get-data-backup} The node is ready to be started. However, you must first sync up with the network. This means your node needs to download all the headers and blocks that other nodes in the network already have. ```bash $ aws s3 --no-sign-request cp s3://near-protocol-public/backups/testnet/archive/latest . $ LATEST=$(cat latest) $ aws s3 --no-sign-request cp --no-sign-request --recursive s3://near-protocol-public/backups/testnet/archive/$LATEST ~/.near/data ``` ### 6. Run the node {#6-run-the-node} To start your node simply run the following command: ```bash $ ./target/release/neard --home ~/.near run ``` That's all. The node is running you can see log outputs in your console. It will download a bit of missing data since the last backup was performed but it shouldn't take much time. ## `mainnet` {#mainnet} ### 1. Clone `nearcore` project from GitHub {#1-clone-nearcore-project-from-github-1} First, clone the [`nearcore` repository](https://github.com/near/nearcore). ```bash $ git clone https://github.com/near/nearcore $ cd nearcore $ git fetch origin --tags ``` Next, checkout the release branch you need (recommended) if you will not be using the default `master` branch. Please check the [releases page on GitHub](https://github.com/near/nearcore/releases) for the latest release. For more information on choosing between `master` and latest release branch [ [click here](/validator/compile-and-run-a-node#choosing-your-nearcore-version) ]. ```bash $ git checkout tags/1.26.1 -b mynode ``` ### 2. Compile `nearcore` binary {#2-compile-nearcore-binary-1} In the `nearcore` folder run the following commands: ```bash $ make release ``` This will start the compilation process. It will take some time depending on your machine power (e.g. i9 8-core CPU, 32 GB RAM, SSD takes approximately 25 minutes). Note that compilation will need over 1 GB of memory per virtual core the machine has. If the build fails with processes being killed, you might want to try reducing number of parallel jobs, for example: `CARGO_BUILD_JOBS=8 make release`. By the way, if you’re familiar with Cargo, you could wonder why not run `cargo build -p neard --release` instead. While this will produce a binary, the result will be a less optimized version. On technical level, this is because building via `make neard` enables link-time optimisation which is disabled by default. The binary path is `target/release/neard` ### 3. Initialize working directory {#3-initialize-working-directory-1} The NEAR node requires a working directory with a couple of configuration files. Generate the initial required working directory by running: ```bash $ ./target/release/neard --home ~/.near init --chain-id mainnet --download-genesis --download-config ``` > You can specify trusted boot nodes that you'd like to use by pass in a flag during init: `--boot-nodes ed25519:86EtEy7epneKyrcJwSWP7zsisTkfDRH5CFVszt4qiQYw@35.195.32.249:24567,ed25519:BFB78VTDBBfCY4jCP99zWxhXUcFAZqR22oSx2KEr8UM1@35.229.222.235:24567,ed25519:Cw1YyiX9cybvz3yZcbYdG7oDV6D7Eihdfc8eM1e1KKoh@35.195.27.104:24567,ed25519:33g3PZRdDvzdRpRpFRZLyscJdbMxUA3j3Rf2ktSYwwF8@34.94.132.112:24567,ed25519:CDQFcD9bHUWdc31rDfRi4ZrJczxg8derCzybcac142tK@35.196.209.192:24567` > You can skip the `--home` argument if you are fine with the default working directory in `~/.near`. If not, pass your preferred location. This command will create the required directory structure by generating a `config.json`, `node_key.json`, and downloads a `genesis.json` for `mainnet`. - `config.json` - Configuration parameters which are responsive for how the node will work. - `genesis.json` - A file with all the data the network started with at genesis. This contains initial accounts, contracts, access keys, and other records which represents the initial state of the blockchain. - `node_key.json` - A file which contains a public and private key for the node. Also includes an optional `account_id` parameter which is required to run a validator node (not covered in this doc). - `data/` - A folder in which a NEAR node will write it's state. ### 4. Replacing the `config.json` {#4-replacing-the-configjson-1} From the generated `config.json`, there two parameters to modify: - `boot_nodes`: If you had not specify the boot nodes to use during init in Step 3, the generated `config.json` shows an empty array, so we will need to replace it with a full one specifying the boot nodes. - `tracked_shards`: In the generated `config.json`, this field is an empty empty. You will have to replace it to `"tracked_shards": [0]` To replace the `config.json`, run the following commands: ```bash $ rm ~/.near/config.json $ wget https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/mainnet/config.json -P ~/.near/ ``` ### Configuration Update {#configuration-update-1} The `config.json` should contain the following fields. Currently, NEAR testnet and mainnet have 4 shards. To track all 4 shards, use `"tracked_shards": [0]`. In the future, there will be the possibility to track different or multiple shards. ``` { ... "archive": true, "tracked_shards": [0], ... } ``` Please make sure that the node is not running while changing the `config.json`. Once the config has been changed, you can restart the node and the node will start syncing new archival data. In the case where you want the full archival history, you can delete the data dir and start the node from scratch syncing full history or use one of the latest backups containing the data directory snapshot which can be copied under the near home dir (default: ~/.near/data). ### 5. Get data backup {#5-get-data-backup-1} The node is ready to be started. However, you must first sync up with the network. This means your node needs to download all the headers and blocks that other nodes in the network already have. ```bash $ aws s3 --no-sign-request cp s3://near-protocol-public/backups/mainnet/archive/latest . $ LATEST=$(cat latest) $ aws s3 --no-sign-request cp --no-sign-request --recursive s3://near-protocol-public/backups/mainnet/archive/$LATEST ~/.near/data ``` ### 6. Run the node {#6-run-the-node-1} To start your node simply run the following command: ```bash $ ./target/release/neard --home ~/.near run ``` That's all. The node is running and you can see log outputs in your console. It will download a bit of missing data since the last backup was performed but it shouldn't take much time. >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
--- title: NFTs on NEAR description: A guide to non-fungible tokens on NEAR. sidebar_position: 4 --- --- ## What's an NFT? Non-Fungible Tokens (NFTs) are digital certificates of ownership for digital assets. These digital certificates are published into an [NEP-171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) token, and once written, they're secured on the blockchain. To create NFTs, the identifying information for these unique digital assets must be recorded on a smart contract. The information on the smart contract is what makes an NFT unique. Anything can be turned into an NFT, with the most popular being videos, media files, or images. NFTs are inherently different from fungible assets like Bitcoin because bitcoins can be exchanged, meaning you can send or receive coins without any hitches. Fungible assets are also divisible, allowing you to send smaller amounts. Non-fungible assets are indivisible. For example, you can’t send someone a part of a painting or a ticket. > A non-fungible asset has a distinct property or properties that set it apart from other assets. Non-fungible tokens are based on non-fungible assets and are unique digital assets that use blockchain technology. An example of a non-fungible asset can be a unique painting or limited edition collectibles. ## NFTs on NEAR Minting NFTs on NEAR is fast, and costs a negligible fee. If you'd like to build NFTs on NEAR, check out this [contract example](https://examples.near.org/NFT) to help you get started. Our develper documentation contains a more detailed minting [tutorial](https://docs.near.org/tutorials/nfts/minting-nfts), if you'd like more information about developing an NFT minting contract on NEAR. NFT projects on NEAR allow you to mint NFTs, exchange NFTs, or use NFTs in dApps. You can store the NFTs that you mint, or receive in your NEAR wallet. The number of NFT projects on NEAR is rapidly growing because of the many different use-cases for NFTs. Have a look at the community-run resource [AwesomeNEAR](https://awesomenear.com/) to find exciting NFT projects on NEAR.
# Network Network layer constitutes the lower level of the NEAR protocol and is ultimately responsible of transporting messages between peers. To provide an efficient routing it maintains a routing table between all peers actively connected to the network, and sends messages between them using best paths. There is a mechanism in place that allows new peers joining the network to discover other peers, and rebalance network connections in such a way that latency is minimized. Cryptographic signatures are used to check identities from peers participating in the protocol since it is non-permissioned system. This document should serve as reference for all the clients to implement networking layer. ## Messages Data structures used for messages between peers are enumerated in [Message](Messages.md). ## Discovering the network When a node starts for the first time it tries to connect to a list of bootstrap nodes specified via a config file. The address for each node It is expected that a node periodically requests a list of peers from its neighboring nodes to learn about other nodes in the network. This will allow every node to discover each other, and have relevant information to try to establish a new connection with it. When a node receives a message of type [`PeersRequest`](Messages.md#peermessage) it is expected to answer with a message of type [`PeersResponse`](Messages.md#peermessage) with information from healthy peers known to this node. ### Handshakes To establish a new connections between pair of nodes, they will follow the following protocol. Node A open a connection with node B and sends a [Handshake](Messages.md#Handshake) to it. If handshake is valid (see reasons to [decline the handshake](#Decline-handshake)) then node B will proceed to send [Handshake](Messages.md#Handshake) to node A. After each node accept a handshake it will mark the other node as an active connection, until one of them stop the connection. [Handshake](Messages.md#Handshake) contains relevant information about the node, the current chain and information to create a new edge between both nodes. #### Decline handshake When a node receives a handshake from other node it will decline this connection if one of the following situations happens: 1. Other node has different genesis. 2. Edge nonce is too low #### Edge Edges are used to let other nodes in the network know that there is currently an active connection between a pair of nodes. See the definition of [this data structure](Messages.md#Edge). If the nonce of the edge is odd, it denotes an `Added` edge, otherwise it denotes a `Removed` edge. Each node should keep track of the nonce used for edges between every pair of nodes. Peer C believes that the peers A and B are currently connected if and only if the edge with the highest nonce known to C for them has an odd nonce. When two nodes successfully connect to each other, they broadcast the new edge to let other peers know about this connection. When a node is disconnected from other node, it should bump the nonce by 1, sign the new edge and broadcast it to let other nodes know that the connection was removed. A removed connection will be valid, if it contains valid information from the added edge it is invalidating. This prevents peers bump nonce by more than one when deleting an edge. When node A proposes an edge to B with nonce X, it will only accept it and sign it iff: - X = 1 and B doesn't know about any previous edge between A and B - X is odd and X > Y where Y is the nonce of the edge with the highest nonce between A and B known to B. <!-- TODO: What is a valid edge: pseudo code --> ## Routing Table Every node maintains a routing table with all existing connections and relevant information to route messages. The explicit graph with all active connection is stored at all times. ```rust struct RoutingTable { /// PeerId associated for every known account id. account_peers: HashMap<AccountId, AnnounceAccount>, /// Active PeerId that are part of the shortest path to each PeerId. peer_forwarding: HashMap<PeerId, HashSet<PeerId>>, /// Store last update for known edges. edges_info: HashMap<(PeerId, PeerId), Edge>, /// Hash of messages that requires routing back to respective previous hop. route_back: HashMap<CryptoHash, PeerId>, /// Current view of the network. Nodes are Peers and edges are active connections. raw_graph: Graph, } ``` - `account_peers` is a mapping from each known account to the correspondent [announcement](Messages.md#announceaccount). Given that validators are known by its [AccountId](Messages.md#accountid) when a node needs to send a message to a validator it finds the [PeerId](Messages.md#peerid) associated with the [AccountId](Messages.md#accountid) in this table. - `peer_forwarding`: For node `S`, `peer_forwarding` constitutes a mapping from each [PeerId](Messages.md#peerid) `T`, to the set of peers that are directly connected to `S` and belong to the shortest route, in terms of number of edges, between `S` and `T`. When node `S` needs to send a message to node `T` and they are not directly connected, `S` choose one peer among the set `peer_forwarding[S]` and sends a routed message to it with destination `T`. <!-- TODO: Add example. Draw a graph. Show routing table for each node. --> <!-- TODO: Notice when two nodes are totally disconnected, and when two nodes are directly connected --> - `edges_info` is a mapping between each unordered pair of peers `A` and `B` to the edge with highest nonce known between those peers. It might be - `route_back` used to compute the route for certain messages. Read more about it on [Routing back section](#routing-back) - `raw_graph` is the explicit [graph](https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)) representation of the network. Each vertex of this graph is a peer, and each edge is an active connection between a pair of peers, i.e. the edge with highest nonce between this pair of peers is of type `Added`. It is used to compute the shortest path from the source to all other peers. ### Updates `RoutingTable` should be update accordingly when the node receives updates from the network: - New edges: `edges_info` map is updated with new edges if their nonce is higher. This is relevant to know whether a new connection was created, or some connection stopped. ```python def on_edges_received(self, edges): for edge in edges: # Check the edge is valid if edge.is_valid(): peer0 = edge.peer0 peer1 = edge.peer1 # Find edge with higher nonce known up to this point. current_edge = self.routing_table.edges_info.get((peer0, peer1)) # If there is no known edge, or the known edge has smaller nonce if current_edge is None or current_edge.nonce < edge.nonce: # Update with the new edge self.routing_table.edges_info[(peer0, peer1)] = edge ``` - Announce account: `account_peers` map is updated with announcements from more recent epochs. ```python def on_announce_accounts_received(self, announcements): for announce_account in announcements: # Check the announcement is valid if announce_account.is_valid(): account_id = announce_account.account_id # Find most recent announcement for account_id being announced current_announce_account = self.routing_table.account_peers.get(account_id) # If new epoch is happens after current epoch. if announce_account.epoch > current_announce_account.epoch: # Update with the new announcement self.routing_table.account_peers[announce_id] = announce_account ``` - Route back messages: Read about it on [Routing back section](#routing-back) ### Routing When a node needs to send a message to another peer, it checks in the routing table if it is connected to that peer, possibly not directly but through several hops. Then it select one of the shortest path to the target peer and sends a [`RoutedMessage`](Messages.md#routedmessage) to the first peer in the path. When it receives a [`RoutedMessage`](Messages.md#routedmessage), it check if it is the target, in that case consume the body of the message, otherwise it finds a route to the target following described approach and sends the message again. Is is important that before routing a message each peer check signature from original author of the message, passing a message with invalid signature can result in ban for the sender. It is not required however checking the content of the message itself. Each [`RoutedMessage`](Messages.md#routedmessage) is equipped with a time-to-live integer. If this message is not for the node processing it, it decrement the field by one before routing it; if the value is 0, the node drops the message instead of routing it. #### Routing back It is possible that node `A` is known to `B` but not the other way around. In case node `A` sends a request that requires a response to `B`, the response is routed back through the same path used to send the message from `A` to `B`. When a node receives a [RoutedMessage](Messages.md#routedmessage) that requires a response it stores in the map `route_back` the hash of the message mapped to the [PeerId](Messages.md#peerid) of the sender. After the message reaches the final destination and response is computed it is routed back using as target the hash of the original message. When a node receives a Routed Message such that the target is a hash, the node checks for the previous sender in the `route_back` map, and sends the message to it if it exists, otherwise it drops the message. The hash of a `RoutedMessage` to be stored on the map `route_back` is computed as: ```python def route_back_hash(routed_message): return sha256(concat( borsh(routed_message.target), borsh(routed_message.author), borsh(routed_message.body) )) ``` ```python def send_routed_message(self, routed_message, sender): """ sender: PeerId of the node through which the message was received. Don't confuse sender with routed_message.author: routed_message.author is the PeerId from the original creator of the message The only situation in which sender == routed_message.author is when the message was not received from the network, but was created by the node and should be routed. """ if routed_message.requires_response(): crypto_hash = route_back_hash(routed_message) self.routing_table.route_back[crypto_hash] = sender next_peer = self.find_closest_peer_to(routed_message.target) self.send_message(next_peer, routed_message) def on_routed_message_received(self, routed_message, sender): # routed_message.target is of type CryptoHash or PeerId if isinstance(routed_message.target, CryptoHash): # This is the response for a routed message. # `target` is the PeerId that sent this message. target = self.routing_table.route_back.get(routed_message.target) if target is None: # Drop message if there is no known route back for it return else: del self.routing_table.route_back[routed_message.target] else: target = routed_message.target if target == self.peer_id: self.handle_message(routed_message.body) else: self.send_routed_message(routed_message, sender) ``` ### Synchronization When two node connect to each other they exchange all known edges (from `RoutingTable::edges_info`) and account announcements (from `RoutingTable::account_peers`). Also they broadcast the newly created edge to all nodes directly connected to them. After a node learns about a new `AnnounceAccount` or a new `Edge` they automatically broadcast this information to the rest of the nodes, so everyone is kept up to date. ## Security Messages exchanged between peers (both direct or routed) are cryptographically signed with sender private key. Nodes ID contains public key of each node that allow other peer to verify this messages. To keep secure communication most of this message requires some nonce/timestamp that forbid a malicious actor reuse a signed message out of context. In the case of routing messages each intermediate hop should verify that message hash and signatures are valid before routing to next hop. ### Abusive behavior When a node A sends more than `MAX_PEER_MSG_PER_MIN` messages per minute to node B, it will be banned and unable to keep sending messages to it. This a protection mechanism against abusive node to avoid being spammed by some peers. ## Implementation Details There are some issues that should be handled by the network layer but details about how to implement them are not enforced by the protocol, however we propose here how to address them. ### Balancing network [Github comment](https://github.com/nearprotocol/nearcore/issues/2395#issuecomment-610077017)
--- id: style-guide title: Writing Style Guide sidebar_label: Writing Style Guide sidebar_position: 5 --- This style guide provides a set of editorial guidelines for anyone writing developer documentation for NEAR related projects. ## Goals and audience {#goals-and-audience} This guide codifies and records style decisions so that you can write wiki articles that is consistent with existing documentation, and ensure that what you write is as easy as possible to understand. We hope that you'll join us in striving for high-quality documentation. > **Note**: Everything in this guide is a guideline, not a draconian rule. Therefore, > there might be contexts where it makes sense to diverge from our guidelines to make > your documentation better. ## Tone and content {#tone-and-content} ### Be conversational and friendly {#be-conversational-and-friendly} Aim for a voice and tone that's conversational, friendly, and respectful without being overly colloquial or frivolous; a voice that's casual and natural and approachable, not pedantic or pushy. Try to sound like a knowledgeable friend who understands what the developer wants to do. Remember that many readers are not native English speakers, many of them come from cultures different from yours, and your document may be translated into other languages (see [Language and grammar](#language-and-grammar) for more on this). ### Don't pre-announce in the documentation {#dont-pre-announce-in-the-documentation} Avoid documenting future features or products, even in innocuous ways (i.e, "we're currently considering _\<possible feature enhancement\>_..."). ### Use descriptive link text {#use-descriptive-link-text} When you're writing link text, use a phrase that describes what the reader will see after following the link. Links should make sense without the surrounding text. That can take either of two forms: - The exact text of the title or heading you're referencing. - A description of the destination page capitalized as ordinary paragraph text. ### Page titles and headings {#page-titles-and-headings} Page titles should use title case (for example, "Deploy your App in Production"). Headings within a page should use sentence case (for example "Test your app with a simple UI"). ### Typography {#typography} Please use the following conventions, which are derived from Google's style guide and from developer documentation published by O'Rielly media group: - `code font` is used for command-line input and output, and for references to code entity names (variables, types, etc). - *`italic code font`* is used to show where a reader should swap in the name of a server or other implementation-specific detail in a syntax example or command example. - *italic font* is used when introducing a term for the first time - **Bold font** is used for file and directory names, UI names, error message text, and for emphasis ### Write accessibly {#write-accessibly} General guidelines to improve reading accessibility: - Place a paragraph's key information in the first sentence to aid in *scannability*. To learn more about scannability, see [How Users Read on the Web](https://www.nngroup.com/articles/how-users-read-on-the-web/). - Break up walls of text (large paragraphs) to aid in scannability. You can do this by separating paragraphs, adding headings, and using lists. - Use shorter sentences, and avoid complex-compound sentences. Try to use fewer than 26 words per sentence. - Define acronyms and abbreviations on first use, and repeat acronym definitions as necessary to avoid confusing readers. - Use parallel writing structures for similar things. For example, items in a list should be similar. ### Write for a global audience {#write-for-a-global-audience} We write our documentation in US English, but it should be as accessible as possible to the worldwide developer community. The rules below help developers who use machine translation to read NEAR docs, or who speak English as a secondary language: - Use the present tense. - Write dates and times in unambiguous and clear ways. - Provide context. Don't assume the reader already knows what you're talking about. - Avoid negative constructions when possible. Consider whether it’s necessary to tell the user what they can’t do instead of what they can. - Use the active voice. The subject of the sentence is the person or thing performing the action. With passive voice, it's often hard for readers to figure out who's supposed to do something. - Address the reader directly. Use *you*, instead of *the user* or *they*. - Define abbreviations. Abbreviations can be confusing out of context, and they don't translate well. Spell things out whenever possible, at least the first time you use a given term. - Don't use the same word to mean different things. ## Language and grammar {#language-and-grammar} Following the guidelines below ensures that our documentation is as approachable as possible for as many readers as possible. In fact, all of these language and grammar guidelines improve the results of machine translating documentation into other languages. ### Use the second person {#use-the-second-person} > Use "you" rather than "we." In general, use the second person to refer to the reader in your docs rather than the first person— *you* instead of *we*. It's also important to figure out who the *you* is that you're addressing (a developer? a sysadmin? someone else?), and to be consistent about that. Make it clear to the reader who you expect them to be (sometimes with an explicit *audience* sentence near the beginning of the document). Finally, always use the third person when describing NEAR's actions or features (avoid "this lets us" in favor of "this lets NEAR"). ### Use active voice {#use-active-voice} > Make clear who's performing the action. In general, use the active voice (in which the grammatical subject of the sentence is the person or thing performing the action) instead of passive voice (in which the grammatical subject of the sentence is the person or thing being acted upon), though there are exceptions. For example: Recommended: * “Send a query to the service. The server sends an acknowledgment.“ Not recommended: * ”The service is queried, and an acknowledgment is sent.” * “The service is queried by you, and an acknowledgment is sent by the server.” ### Use standard American spelling and punctuation {#use-standard-american-spelling-and-punctuation} In general, in cases where American spelling differs from Commonwealth/"British" spelling, use the American spelling. ### Put conditional clauses before instructions, not after {#put-conditional-clauses-before-instructions-not-after} Say you want to tell the audience to do something in a particular circumstance. If possible, mention the circumstance before you provide the instruction; that way, the reader can skip the instruction if the circumstance doesn't apply. ## Formatting, punctuation, and organization {#formatting-punctuation-and-organization} * Use numbered lists for sequences. * Use bulleted lists for most other lists. * Use description lists for pairs of related pieces of data. > Use numbered lists for sequences, bulleted lists in most other contexts, and description > lists for pairs of related pieces of data. * Use serial commas. > Use commas to separate items in series, and use commas to separate certain kinds of clauses. > In a series of three or more items, use a comma before the final *and* or *or*. * Put code-related text in `code font`. > In ordinary text sentences (as opposed to, say, code samples), use code font to mark up most > things that have anything to do with code (example variables, product keywords, etc). > In Markdown, use backticks (`). * Put UI elements in **bold**. > If you do document elements of the UI, put UI element names in **bold**, and use appropriate > nouns and verbs to describe how to interact with them. * Use unambiguous date formatting. > Expressing dates and times in a clear and unambiguous way helps support writing for a global > audience and reduces confusion. We recommend using the `YYYY-MM-DD` format for dates. ## Credits and more style guidance {#credits-and-more-style-guidance} This style guide is inspired by and borrows from [Googles developer documentation style guide](https://developers.google.com/style/), which you can use for anything not covered here. For anything not found in Google's style guide, see [Microsoft's Style Guide](https://docs.microsoft.com/en-us/style-guide/welcome/).
NEAR’s Road to Decentralization: Empowering the Guild Community NEAR FOUNDATION March 11, 2022 The NEAR network is reimagining how decentralized applications and platforms are built, playing a major role in transforming the internet from the centralized Web2 to an open-source, community-driven Web3. Amidst the NEAR community’s growth and continued decentralization, its guild system has emerged as a significant contributor to building more open, interconnected, and collaborative projects within the NEAR ecosystem. Let’s take a look at what NEAR Guilds are up to in 2022, and why the Guild system is so vital to NEAR’s continued success. Decentralizing NEAR’s development and growth Within the NEAR ecosystem, Guilds are communities that work towards common, specific goals, from the core protocol development to the projects being built atop it. The current roster of Guilds spans multiple continents and numerous industries. The Guild system’s growing capability, size, and diversity is crucial to the NEAR blockchain and ecosystem future development. Guilds are already helping decentralize NEAR’s operations and growth by enabling smaller teams of developers to work together to improve different aspects of the protocol. In other words, many small groups of NEAR community members, enthusiasts and entrepreneurs with a variety 0f professional experiences and skill sets, are collaborating on specific goals to build, maintain, and improve the NEAR ecosystem. Introducing the NEAR Guilds community The NEAR Guilds community consists of more than 73 projects, each with its own vision and mission. Let’s take a look at four Guilds that are working across different industries to further develop the NEAR ecosystem. Data Guild Data Guild is on a mission to increase visibility of the NEAR protocol and ecosystem by creating tools and products that NEAR community members can easily use. The Data Guild essentially works to expand the accessibility of NEAR data infrastructure, tools, and resources for all contributors. It does this by bringing together open web contributors who can create resources that provide trustworthy data. Some of the team’s biggest achievements include gathering leaders of NEAR data projects to coordinate collaborations with other guilds. The Data Guild is doing this through subgraph tutorials; contributing directly to several data products, including nearstats.com and DAOstats.io; and successfully onboarding and promoting leading developers and data projects, including Dapplooker, stats.gallery, soda.com, finear.xyz, and Metrics Dao. James Waugh, Coordinator of NEAR Data Guild, explains that the community could use more clarity on governance of the Guilds program as well as NEAR Foundation’s involvement with DAOs. “Guilds are coordinating to support the NEAR ecosystem via better community governance,” says Waugh. ‘We are looking forward to more guilds and DAOs using NEAR data.” Legal Guild Legal Guild is an independent, multi-disciplinary global network of lawyers bringing legal advice to the crypto world. The guild’s expertise spans different fields and focuses on giving recommendations to entrepreneurs, developers, projects, and communities. It does this by providing expertise on legal matters pertaining to DAOs, smart contracts, blockchain, tokenization, privacy, cyber security, intellectual property for digital assets, and more. The Legal Guild’s ultimate goal? Reshape how legal services are provided in the crypto industry. “We believe that the empowerment of the community is key for building in a decentralized world,” the Legal Guild’s mission reads. “Our playbooks, use cases, and expertise are a manifestation of our mission: to help blockchain-based projects navigate complex legal issues.” CuraDAO CuraDAO is an art studio that aims to launch and develop in-house creative projects in collaboration with creatives and partners. CuraDAO’s goal is to be an engineering-driven guild—one that explores and experiments with smart contracts for creative purposes. The guild has an emphasis on design and is exploring ways to creatively use NFTs. In terms of challenges, the team is competing for creative talent with both Web2 platforms and other Web3 blockchains. This will get better with time, as developers from both domains realize how easy, fast, and cheap it is to build on NEAR. “NEAR has a strong vision for community and culture [and] guilds are a great representation,” said Yassine Sania, a founding member at CuraDAO. “We see a guild as an organized community that can leverage crypto tools for decision-making and value creation.” CleanNFTs CleanNFTs is a collective within the NEAR ecosystem whose mission is to educate and raise awareness about energy-efficient blockchains and environmentally-friendly NFT (non-fungible token) platforms. After assembling on Discord in 2021 to discuss issues with Ethereum’s Proof-of-Work (PoW) energy usage, this guild of artists and NFT aficionados ramping up its community education efforts at minimizing the environmental impacts of NFT minting. The guild does this by curating information and reading resources on its website. The CleanNFTs guild operates under a general consensus: that NFTs themselves do not produce carbon emissions but some cryptocurrencies use energy-intensive resources for mining. CleanNFTs members also agree that the NFT art platforms running on more energy-efficient Proof-of-Stake (PoS) networks are, at present, the most environmentally-sustainable option for creating NFTs. A brief look at NEAR Hub, NEAR’s virtual world Beyond the NEAR Guilds ecosystem, community contributors also created NEAR Hub, a metaverse (or, NEARverse) that allows users to log into a virtual experience using just their NEAR wallets, with a clear focus on user control and ownership over their data and assets. The idea for NEAR Hub came from the Human Guild, a guild started in 2021 that is focused on supporting Web3 games building on NEAR. According to their website, the Human Guild is dedicated to establishing strongly-knit crypto communities, onboarding newcomers, and ushering in what it calls the “gaming revolution.” “Everybody should be able to earn by doing what they love. The mission is to help people getting paid in crypto and getting involved in the online economy,” said Aliaksandr (Sasha) Hudzilin, co-founder of the guild. NEAR Hub received funding from the Human Guild and launched in December 2021. The platform offers its metaverse experience through its product, “Rooms”, which users can enter with their avatar. Each Room experience is themed and built around a certain idea or collaboration with a partner project or guild in the NEAR ecosystem. NEAR Hub’s goal is to onboard new users and make it “a portal to everything in the NEAR ecosystem,” according to co-founders @chronear and Jeff G. The platform is meant to be a space for users to learn about all aspects of NEAR from education, gaming, NFTs, decentralized finance, and infrastructure projects. The Hub is significant because it is trying to make decentralized application interactions more meaningful for users by giving them the chance to hang out with other community members, build networks, and express themselves creatively in the process. NEAR Guilds moving forward NEAR’s guild system is playing a vital role in the growth and further decentralization of the NEAR ecosystem. Each of the current guilds has a unique mission and purpose, doing what it can to develop different aspects of NEAR. The number of guilds also continues to grow on a regular basis, as more teams of passionate NEAR enthusiasts band together to join NEAR’s road to decentralization. Over time, Guilds may evolve to adapt to new developments on the NEAR protocol and the wider Web3 network. To stay current on the NEAR Guilds popping up on the ecosystem, check out Guild News. Want to build your own? Learn how at the Start a Guild page.
```bash near view v2.ref-finance.near get_pools '{"from_index": 0, "limit": 1000}' ``` <details> <summary>Example response</summary> <p> ```bash [ { pool_kind: 'SIMPLE_POOL', token_account_ids: [ 'token.skyward.near', 'wrap.near' ], amounts: [ '51865812079751349630100', '6254162663147994789053210138' ], total_fee: 30, shares_total_supply: '1305338644973934698612124055', amp: 0 }, { pool_kind: 'SIMPLE_POOL', token_account_ids: [ 'c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2.factory.bridge.near', 'wrap.near' ], amounts: [ '783621938569399817', '1100232280852443291118200599' ], total_fee: 30, shares_total_supply: '33923015415693335344747628', amp: 0 } ] ``` </p> </details>
--- id: quickstart title: Hello Contract sidebar_label: Quickstart ✨ --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" [NEAR accounts](../../1.concepts/protocol/account-model.md) can host programs known as smart contracts. Smart contracts can **store data**, and **expose methods** so other users and contracts interact with them. In this quickstart tutorial, we will guide you in creating your first smart contract in the NEAR **testnet** that stores and retrieves a greeting. --- ## Prerequisites <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> Before starting, make sure you have the following installed: 1. [Node.js](https://nodejs.org/en/download), to use our scaffolding tool. 2. [NEAR CLI](/tools/near-cli#installation), to deploy and interact with the contract. :::tip Easy Install - **NEAR-CLI:** Install `near-cli` tools using ``` npm i -g near-cli ``` ::: </TabItem> <TabItem value="rust" label="🦀 Rust"> Before starting, make sure you have the following installed: 1. [NEAR CLI-RS](/tools/near-cli-rs), to deploy and interact with the contract. 2. [cargo-near](https://github.com/near/cargo-near), to easily create testnet accounts. 3. [Rust](https://www.Rust-lang.org/tools/install), to create Rust contracts. 4. [Node.js](https://nodejs.org/en/download)(Optional), to install the tools. :::tip Easy Install - **NEAR-CLI-RS:** Install both `near-cli-rs` and `cargo-near` tools using ```bash # Using node npm i -g near-cli-rs cargo-near # Using macOS, Linux, WSL curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh ``` ::: </TabItem> </Tabs> :::info Testnet Account There is no need to have a `testnet` account to follow this tutorial. However, if you want to create one, you can do so through [a wallet](https://testnet.mynearwallet.com), and use it from the `near-cli` by invoking `near login`. ::: --- ## Creating the Contract <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> Create a smart contract by running our `create-near-app` scaffolding tool and following the interactive menu. - What do you want to build? › `A Near Smart Contract` - Select a smart contract template for your project › `JS/TS Contract` - Name your project › `hello-near` ```bash npx create-near-app@latest ``` ![img](@site/static/docs/hello-near-ts.gif) _create-near-app in action_ The resulting folder structure will change slightly depending on the chosen language. Here is the general structure you can expect to see: ```bash ├── sandbox-ts # sanbox testing │ ├── src │ ├── └── main.ava.ts │ ├── ava.config.cjs │ └── package.json ├── src │ └── contract.ts # contract's code ├── package.json # package manager ├── README.md └── tsconfig.json ``` </TabItem> <TabItem value="rust" label="🦀 Rust"> Create a smart contract by running our `near` Rust CLI tool and following the interactive menu. ```bash cargo near new <project_name> ``` ![img](@site/static/docs/hello-near-rs.gif) _create-near-app in action_ The resulting folder structure will change slightly depending on the chosen language. Here is the general structure you can expect to see: ```bash ├── src │ └── lib.rs # contract's code ├── test │ └── test_basics.rs # testing code ├── Cargo.toml # package manager ├── README.md └── rust-toolchain.toml ``` </TabItem> </Tabs> --- ## The Contract Your new smart contract stores a `greeting: string` attribute in their state, and exposes two methods to interact with it (`set_greeting`, `get_greeting`). <CodeTabs> <Language value="js" language="js"> <Github fname="index.js" url="https://github.com/near-examples/hello-near-examples/blob/main/contract-ts/src/contract.ts" start="4" end="18" /> </Language> <Language value="rs" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/hello-near-examples/blob/main/contract-rs/src/lib.rs" start="4" end="32" /> </Language> </CodeTabs> There are 3 important things to notice: 1. The `get_greeting` method is a [`view`](./anatomy/anatomy.md#public-methods) method, meaning it only reads from the contract and can be called for free by anyone. 2. By default, the contract is initialized with the `greeting` attribute set to `"Hello"`. 3. The `set_greeting` method is a [`change`](./anatomy/anatomy.md#public-methods) method, meaning it modifies the contract's state and requires a user to sign a transaction in order to be executed. ## Build and Test Building and testing the contract is as simple as running two commands. <CodeTabs> <Language value="js" language="js"> ```bash npm run build npm run test # Expected: # returns the default greeting ✅ # changes the greeting ✅ ```` </Language> <Language value="rust" language="rust"> ```bash cargo build cargo test # Expected: # Passed ✅ gets default greeting # Passed ✅ changes the greeting ``` </Language> </CodeTabs> <details> <summary> Failing tests? </summary> If the tests are failing, make sure that you are using `node v16` and the `toolchain v1.69` in `rust`. You can always use - `nvm use 16` to switch to `node v16` - `rustup default 1.68` to switch to `toolchain v1.69` </details> In the background, these commands are calling the build tools for each language and invoking the [Sandbox](./testing/integration-test.md) tests from the `sandbox-ts/rs` directory. :::tip Sandbox Testing the contracts within a Sandbox allows you to understand how the contract will behave once deployed to the network while having total control over the testing environment. ::: --- ## Create a Testnet Account Now that we know the contract is passing the tests, let's create a testnet account in which to deploy the contract. While there are different ways to create accounts in NEAR, in this quickstart we will use the `cargo-near` tool to create a new random [`named account`](/concepts/protocol/account-id). <Tabs groupId="code-tabs"> <TabItem value="js" label="🌐 JavaScript"> ```bash # Create a new testnet account # Replace <created-account> with a custom name near create-account <created-account> --useFaucet ``` <details> <summary> Example Result </summary> ```bash > near create-account lovely-event.testnet --useFaucet # Console response New account "lovely-event.testnet" created successfully. # Response ``` </details> </TabItem> <TabItem value="rust" label="🦀 Rust"> ```bash # Create a new testnet account with a random name cargo-near near create-dev-account use-random-account-id autogenerate-new-keypair save-to-legacy-keychain network-config testnet create # Create a new testnet account # Replace <lovely-event.testnet> with a custom name cargo-near near create-dev-account use-specific-account-id lovely-event.testnet autogenerate-new-keypair save-to-keychain network-config testnet create ```` <details> <summary> Example Result </summary> ```bash # If you want to create account with a random name > cargo-near near create-dev-account use-random-account-id autogenerate-new-keypair save-to-legacy-keychain network-config testnet create New account "lovely-event.testnet" created successfully. # Response # If you want to create account with a custom name > cargo-near near create-dev-account use-specific-account-id lovely-event.testnet autogenerate-new-keypair save-to-keychain network-config testnet create New account "lovely-event.testnet" created successfully. # Response ``` </details> </TabItem> </Tabs> :::tip Here we are creating a random account since we do not care about the account's name. Remember that you can create a named account through any wallet (i.e. [MyNearWallet](https://testnet.mynearwallet.com)) and then use it from the `near-cli` by invoking `near login`. ::: --- ## Deploy the Contract Having our account created, we can now deploy the contract into it: <Tabs> <TabItem value="near-cli"> ```bash near deploy <created-account> build/release/hello.wasm ``` </TabItem> <TabItem value="near-cli-rs"> ```bash near contract deploy <created-account> use-file ./target/wasm32-unknown-unknown/release/contract_rs.wasm without-init-call network-config testnet sign-with-keychain send ``` </TabItem> </Tabs> **Congrats**! your contract now lives in the NEAR testnet network. --- ## Interacting with the Contract To interact with your deployed smart contract, you can call its methods using the `near-cli` or `near-cli-rs` tools. ### Get Greeting The `get_greeting` method is a [`view`](./anatomy/anatomy.md#public-methods) method, meaning it only reads from the contract's state, and can thus be called for **free**. <Tabs> <TabItem value="near-cli"> ```bash > near view <created-account> get_greeting "Hello" # Response ``` </TabItem> <TabItem value="near-cli-rs"> ```bash > near contract call-function as-read-only <created-account> get_greeting json-args {} network-config testnet now "Hello" # Response ``` </TabItem> </Tabs> ### Set Greeting The `set_greeting` method is a [`change`](./anatomy/anatomy.md#public-methods) method, meaning it modifies the contract's state, and thus requires a user to sign a transaction in order to be executed. <Tabs> <TabItem value="near-cli"> ```bash > near call <created-account> set_greeting '{"greeting": "Hola"}' --accountId <created-account> Log: Saving greeting "Hola" # Response ``` In this case we are asking the account that stores the contract to call its own contract's method (`--accountId <created-account>`). </TabItem> <TabItem value="near-cli-rs"> ```bash > near contract call-function as-transaction <created-account> set_greeting json-args '{"greeting": "Hola"}' prepaid-gas '100.0 Tgas' attached-deposit '0 NEAR' sign-as <created-account> network-config testnet sign-with-keychain send Log: Saving greeting "Hola" # Response ``` In this case, we are asking the account that stores the contract to call its own contract's method (`sign-as <created-account>`). </TabItem> </Tabs> --- ## Moving Forward That's it for the quickstart tutorial. You have now seen a fully functional contract with a minimal user interface and testing. Go ahead and check other [examples](/tutorials/examples/guest-book) or proceed straight to the [Develop section](./anatomy/anatomy.md) to know how to write your own contract. If you have any questions, do not hesitate to join us on [Discord](https://near.chat). We regularly host Office Hours, in which you can join our voice channel and ask questions. Happy coding! 🚀 :::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-cli-rs: `0.8.1` - cargo-near: `0.6.1` :::
Catch Us If You Can | October 4th, 2019 COMMUNITY October 5, 2019 Devcon is here and we hope to meet as many of you as possible! If you did not get a chance to connect with us in Shanghai or Seoul blockchain week, we are going to be in Tokyo, Osaka for Devcon, and right after in London for more hackathons, presentations and panels. Check out our events page for more information on how to find us. Ambassadors to the next challenge! Our ambassador network is growing and doubled throughout September to over 60 ambassadors and counting. We had some great events organised, including in Prague and Shanghai. Get in touch with us to connect to ambassadors and start your own community. Illia introducing NEAR in Shanghai. Meetup organised by one of our ambassadors Yuan Jun COMMUNITY AND EVENTS Ambassadors are crushing it with translating, creating and sharing content. More to follow soon! Yuan Jun, Buster and Jan hosted the first Ambassador meetups. New ambassador competitions coming up, make sure to sign-up if you are interested in becoming an ambassador. Upcoming events We are at Devcon! If you see us, come and chat. We are looking forward to meeting you in person; Illia is going to represent NEAR at Wasm Chains (NEAR, Polkadot, Spacemesh); NEAR is hosting a Panel on Cross-app communication (Ethereum Serenity, NEAR, Polkadot, Cosmos). Sasha, participating in a panel discussion on blockchain gaming solutions WRITING AND CONTENT Have you ever looked into ways to establish decentralised identities? Check out our latest blog post on decentralised identities. We provide an overview on the work that is currently done by governments, businesses, and the decentralised web to make identity documentation more accessible. Use case: Distributed Identity Solutions https://pages.near.org/blog/use-case-distributed-identity-solutions/ Peter’s overview of Swarmwise — ideas that we model our community after https://sophonaut.com/2019/09/25/swarmwise/ Canaan from Stardust on what is it like to build a blockchain startup https://medium.com/stardustplatform/part-4-life-of-a-blockchain-entrepreneur-money-on-my-mind-5bd0461bcc2f ENGINEERING UPDATE We’ve had some fun creating a few crypto projects; check-out our pitch-deck-generator and the bearprotocol. Here are the highlights of what’s been added in the last two weeks: 93 PRs across 19 repos by 17 authors. Featured repos:nearcore,nearlib,near-shell,near-wallet,near-bindgen, near-runtime-ts, crypto-corgis, borsh, and near-explorer. Genesis block design; NEP-4 Market-integrated Token Standard; Adapt nearlib staging to support master branch from nearcore with legacy tx result in nearlib; Account Detail Page added to explorer; Link account names (sender/receiver) to /accounts/<name> in list of transactions; Move away from compiler and create new near compiler frontend in near-runtime-ts; Several UI and storage changes in crypto corgis; Replace env_test feature with wasm target conditional compilation in near-bindgen; Manual Recovery w/ Seed Phrase in near-wallet. 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/
```js const result = Near.view("sputnik-dao.near", "get_dao_list"); ``` <details> <summary>Example response</summary> <p> ```js [ 'ref-finance.sputnik-dao.near' 'gaming-dao.sputnik-dao.near', ... ] ``` </p> </details>
--- id: post-processing title: "Post Processing Tools" --- # Post Processing Tools The size of the contract is a critical characteristic. The best way to keep it small is a well-designed minimalistic code with a reduced number of dependencies. It is especially important for large contracts and huge multi-contract dApps that can take a fortune to deploy. When you have done your best with the code optimization it is worth reducing the size of the contract by minifying it. ## Ready to use script We have prepared a simple `bash` script that can be used to minify `.wasm` contract file. You can find it [here](https://github.com/near/near-sdk-rs/blob/master/minifier/minify.sh). The current approach to minification is the following: 1. Snip (i.e. just replace with unreachable instruction) few known fat functions from the standard library (such as float formatting and panic-related) with `wasm-snip`. 2. Run `wasm-gc` to eliminate all functions reachable from the snipped functions. 3. Strip unneeded sections, such as names with `wasm-strip`. 4. Run `binaryen wasm-opt`, which cleans up the rest. ### Requirements to run the script: - install [wasm-snip](https://docs.rs/wasm-snip/0.4.0/wasm_snip/) and [wasm-gc](https://docs.rs/crate/wasm-gc/0.1.6) with Cargo: ```bash cargo install wasm-snip wasm-gc ``` - install [binaryen](https://github.com/WebAssembly/binaryen) and [wabt](https://github.com/WebAssembly/wabt) on your system. For Ubuntu and other Debian based Linux distributions run: ```bash apt install binaryen wabt ``` ## WARNING Minification could be rather aggressive, so you must test the contract after minification. Standalone NEAR runtime could be helpful [here](https://github.com/nearprotocol/nearcore/tree/master/runtime/near-vm-runner).
import {LeadershipResources, CommunicationResources, ResilienceResources} from '@site/src/components/LeadershipCards'; :::info on this page * Resources to improve you and your team's leadership skills * Resources to improve you and your team's communication skills * Resources to improve you and your team's resilience ::: # Leadership Toolkit This collection of resources provided by [Abensur Consulting](http://www.abensurconsulting.com/) will help you cultivate better **Leadership** through understanding the roles and responsibilities of everyone on your team, how to foster **Effective Communication**, and how to build **Resilience**. These resources are PDFs, artiles, and videos to help you be the best leader you can be. Revisit them often to refresh your memory and to learn new skills. ## Leadership <!-- - DAC: role of a leader (see attached) - DAC: assess your team (see attached) - Picture of Success (see attached) - A great boss according to Google (see attached) - Five dysfunctions of a team: https://youtu.be/GCxct4CR-To --> Discover the factors that can make or break an effective leader. <LeadershipResources /> ## Effective communication <!-- - Active Listening https://www.ccl.org/articles/leading-effectively-articles/coaching-others-use-active-listening-skills/?utm_source=pdf&utm_medium=print&utm_campaign=virtual-communication-quiz&utm_content=active-listening&utm_term=resource# - Feedback (COIN model) (see attached) - Preparing difficult conversations (see attached) - List of powerful questions for 1o1s (see attached) - To Win Over an Audience, Focus on Building Trust https://hbr.org/2022/03/to-win-over-an-audience-focus-on-building-trust?utm_medium=email&utm_source=circ_newbusiness&utm_campaign=contentmarketingseries_nonsubs&hide_intromercial=true&tpcc=email.circ_newbusiness.content.SEGB&deliveryName=DM181852 - Influencing: The Skill of Persuasion (see attached) --> Understand your organizational dynamics, and what it takes to build a cohesive team. <CommunicationResources /> ## Resilience <!-- Resilience - Practice resilience (see attached) - Resilience When Staring in the Face of Fear http://insights.hudsoninstitute.com/resilience-when-staring-in-the-face-of-fear?utm_source=hs_email&utm_medium=email&utm_content=88596425&_hsenc=p2ANqtz-8jccr1KBJY6xqavz8xP8ZlazeYhVMbEah8e6GwErbbb5aw31YtY4XIgEk2EEHQscfYsgwS63O5tJIJcbjls9o5ai0tYg&_hsmi=88597051 --> Grit is the ability to bounce back from adversity and keep going. Learn how to build resilience in yourself and your team. <ResilienceResources /> ## Further Reading - **Conscious Business** - Fred Kofman - **Reinventing Organizations** - Frederic Laloux - **Crucial conversations** - Kerry Patterson
--- id: backend-login title: Authenticate NEAR Users --- Recently NEAR has approved a new standard that, among other things, enables users to authenticate into a backend service. The basic idea is that the user will sign a challenge with their NEAR wallet, and the backend will verify the signature. If the signature is valid, then the user is authenticated. --- ## Backend Auth with a NEAR Wallet Authenticating users is a common use-case for backends and web applications. This enables services to provide a personalized experience to users, and to protect sensitive data. To authenticate a user, the backend must verify that the user is who they say they are. To do so, the backend must verify that the user has access to a full-access key that is associated with their account. For this three basic steps are needed: 1. Create a challenge for the user to sign. 2. Ask the user to sign the challenge with the wallet. 3. Verify the signature corresponds to the user. ### 1. Create a Challenge Assume we want to login the user into our application named `application-name`. We first need to create a challenge that the user will sign with their wallet. For this, it is recommended to use a cryptographically secure random number generator to create the challenge. ```js import { randomBytes } from 'crypto' const challenge = randomBytes(32) const message = 'Login with NEAR' ``` :::note Here we use [crypto.randomBytes](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) to generate a 32 byte random buffer. ::: ### 2. Ask the User to Sign the Challenge The `signMessage` method needed to sign the challenge is supported by these wallets: - Meteor Wallet - Here Wallet - Near Snap - Nightly Wallet - WELLDONE Wallet - NearMobileWallet - MyNearWallet - Sender The message that the user needs to sign contains 4 fields: - Message: The message that the user is signing. - Recipient: The recipient of the message. - Nonce: The challenge that the user is signing. - Callback URL: The URL that the wallet will call with the signature. ```js // Assuming you setup a wallet selector so far const signature = wallet.signMessage({ message, recipient, nonce: challenge, callbackUrl: <server-auth-url> }) ``` ### 3. Verify the Signature Once the user has signed the challenge, the wallet will call the `callbackUrl` with the signature. The backend can then verify the signature. ```js const naj = require('near-api-js') const js_sha256 = require("js-sha256") export async function authenticate({ accountId, publicKey, signature }) { // A user is correctly authenticated if: // - The key used to sign belongs to the user and is a Full Access Key // - The object signed contains the right message and domain const full_key_of_user = await verifyFullKeyBelongsToUser({ accountId, publicKey }) const valid_signature = verifySignature({ publicKey, signature }) return valid_signature && full_key_of_user } export function verifySignature({ publicKey, signature }) { // Reconstruct the payload that was **actually signed** const payload = new Payload({ message: MESSAGE, nonce: CHALLENGE, recipient: APP, callbackUrl: cURL }); const borsh_payload = borsh.serialize(payloadSchema, payload); const to_sign = Uint8Array.from(js_sha256.sha256.array(borsh_payload)) // Reconstruct the signature from the parameter given in the URL let real_signature = Buffer.from(signature, 'base64') // Use the public Key to verify that the private-counterpart signed the message const myPK = naj.utils.PublicKey.from(publicKey) return myPK.verify(to_sign, real_signature) } export async function verifyFullKeyBelongsToUser({ publicKey, accountId }) { // Call the public RPC asking for all the users' keys let data = await fetch_all_user_keys({ accountId }) // if there are no keys, then the user could not sign it! if (!data || !data.result || !data.result.keys) return false // check all the keys to see if we find the used_key there for (const k in data.result.keys) { if (data.result.keys[k].public_key === publicKey) { // Ensure the key is full access, meaning the user had to sign // the transaction through the wallet return data.result.keys[k].access_key.permission == "FullAccess" } } return false // didn't find it } // Aux method async function fetch_all_user_keys({ accountId }) { const keys = await fetch( "https://rpc.testnet.near.org", { method: 'post', headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: `{"jsonrpc":"2.0", "method":"query", "params":["access_key/${accountId}", ""], "id":1}` }).then(data => data.json()).then(result => result) return keys } module.exports = { authenticate, verifyFullKeyBelongsToUser, verifySignature }; ```
--- id: communities title: Communities sidebar_label: Communities --- # Communities :::info on this page The NEAR ecosystem is made up of many different communities, each with its own vision and mission to promote an open and interconnected world. These communities include ones focused on gaming, marketing, music, art, and social good, among others. Among the communities listed are Afro Star, Codame Guild, NEAR Gaming guild, NEAR Marketing, NxM - NEAR x Music Guild, and The Merchants of NEAR. ::: The NEAR ecosystem is formed by many different communities. Each community shares a specific vision and mission related to driving a more open, interconnected, and consumer-empowered world. Get involved in the various communities in the ecosystem: * [Afro Star](https://t.me/afrostarguild): We care for ARTISTS INDEPENDENCE, make stars shine digitally, physically, build YOUNG TALENTS and give power to FEMALE creatives. * [Arroz Criativo](https://t.me/arrozcriativo): Creative space in Lisbon * [Aurora Labs](https://discord.gg/y6dN9ETTVG): Official Discord of Aurora * [Clean NFT guild](https://discord.gg/DpF4g2eWha): A group working towards educating, raising awareness and looking at ways to improve the environmental impacts of releasing NFTs. * [Codame Guild](https://t.me/codame_art_tech): CODAME sparks visionaries with playful workshops and an inclusive ART+TECH Festival, running since 2010. * [Community Groups](https://docs.nearbuilders.com/community-groups/): Developer centric interest groups on specific NEAR ecosystem verticals dedicated to support projects & developer governance from the ground up * [Createbase](https://t.me/creatorsNEAR): Createbase is a community that works to support creative projects that are building within the Mintbase/NEAR ecosystem * [Harmonic Guild](https://www.harmonicguild.io/): Harmonic Technology Guild lets you make your own NFT economy without worrying about the technical infrastructure * [Human Guild](https://t.me/HumanGuildNear): With a primary focus around incubating & supporting web3 gaming projects, the Human Guild is an open group of founders and creators who believe everyone should be able to earn what they need in order to do what they love. * [HypeDAO](https://t.me/hypedao): Marketing hype * [INC4](https://inc4.net/near-guild-team/): Entrepreneurs and development teams looking for additional support, and any project looking to get started in the NEAR Ecosystem now have a reliable and consistent place to go for their technical needs. * [IncubadoraPT DAO](https://t.me/joinchat/0eMzpguax6c2Yjc0): Português creatives * [Marma J Foundation](https://t.me/marmajdao): The Marma J Foundation leverages Web3 technology to support social good initiatives. * [MutiDAO](https://t.me/joinchat/T7ZyEUtQ0EQzNDA0): A collective using blockchain technology & community building to nurture creativity. * [NEAR Data center guild](https://t.me/joinchat/VF7l9wGIS3UzZDcx): Discussion around projects involving data & analytics. * [NEAR Gaming guild](https://t.me/NearGamesChat): Community & discussion around gaming projects on NEAR. * [Near GameFi Group](https://t.me/+JGpzQIiKnTtlYzg0): This group is all about gaming projects on Near, growing the econosystem, and support. * [NEAR Insider](https://t.me/nearinsider_chat): Helping with promotion, feedback, marketing * [NEAR Marketing](https://t.me/DiscoverNEAR): A guild focused around marketing initiatives. * [NEAR Meme Daily](https://discord.gg/vByU5q224g): Empowering the open community of crypto/blockchain meme content creators through NEAR * [NEAR Stars guild](https://t.me/nearstarsguild): A community focused on getting near promoted by content creators like bloggers, etc. * [NEARWEEK](https://t.me/nearweek): Discuss exciting news in the NEAR ecosystem. * [NEAR is NOW](https://t.me/NEARisNOW): The focus of this group is to help drive the mass adoption of NEAR Protocol through a consolidation of efforts to educate new users and spread awareness about ecosystem developments, updates, partnerships, etc. * [NxM - NEAR x Music Guild](https://t.me/joinchat/H7iKol-2HgZXNEl9): NxM is a grassroots movement and a community of creatives around Music and NFTs in the NEAR ecosystem * [Octopus Guild](https://t.me/octopusnetwork): Octopus Guild is a community of developers, enthusiasts, appchains, and appchain candidates within the * [Open Shard Alliance](https://discord.gg/uvVhKxbCaz): The OSA is a guild of NEAR enthusiasts comprised of professional validators and StakeWars participants that are dedicated to contribute back to the NEAR ecosystem.NEAR Community validator guild * [The Merchants of NEAR](https://t.me/joinchat/9p64iHVo1e41ZjBh): Trading and technical analysis * [NFT Infinity](https://t.me/nftinfinity): NFT Infinity aims to redefine the NFT ecosystem so that everyone can participate, create, and make profit. * [Shitzu Apes](https://t.me/ShitzuApes): A strong and vibrant community, built around a meme coin, is focused on driving growth and awareness of NEAR & Aurora. ## Regional Communities * [NEAR Argentina](https://t.me/NEARargentina): A community focused on getting cryptocurrency and blockchain technology adopted in Argentina through NEAR. * [NEAR Canada](https://nearcanada.com): To empower Canadians with the knowledge of Web 3.0 and NEAR technology. * [NEAR China](https://t.me/NEAR_China): NEAR China community * NEAR Español (https://t.me/NEARSpanish): Near Spanish speaker community * [NEAR Francais](https://t.me/NearFrancais): NEAR French community * [NEAR India](https://t.me/cryptonear_IN): NEAR INDIA community * [NEAR Malaysia](https://t.me/NEAR_Malaysia): NEAR Malaysia community * [NEAR Protocol Persian](https://t.me/NEARProtocol_persian): A community focusing on promoting NEAR to Persian speakers * [NEAR Protocol Thai](https://t.me/nearthaicommunity): NEAR Thai community * [NEAR Russia](https://t.me/near_protocol): A guild focused on the NEAR protocol russian speaking community * [NEAR Turkey](https://t.me/near_tr): Language and content support for Turkish speakers * [NEAR Ukraine](https://t.me/nearprotocolua): With its current home in Lisbon, NEAR Ukraine is hub within a hub. The community is keenly aware of this. So NEAR Ukraine is creating an inclusive atmosphere in Lisbon, where local citizens, refugees, and expats from around the world can gather. * [NEAR Venezuela](https://t.me/NearVenezuela): primary goal is to educate the Venezuelan community about the potential of the NEAR protocol and channel grants from the foundation to projects or members that contribute to the growth and / or adoption of NEAR in their locality / region. * [NEAR Vietnam](https://t.me/nearvietnamofficial): NEAR Vietnam community * [NEAR Developer Vietnam](https://t.me/neardev_vncommuity): To help Vietnamese developers learn and better understand the ecosystem and application development on NEAR Protocol * [Sankore 2.0](https://t.me/sankore2): Kenya hub, incubating & supporting projects
NEAR Launches Kenya Regional Hub to Support Blockchain Projects and Talent in Africa COMMUNITY May 9, 2022 NEAR Foundation is thrilled to announce the launch of Kenya Regional Hub in partnership with Sankore, a Kenya-based NEAR Guild. The Kenya Regional Hub will accelerate blockchain innovation, education, and talent development across the African continent. The hub, led by Sankore founder Kevin Imani and a core team of four members, will organize events, launch an academy and incubator, and be part of the Sankore Bounty ecosystem. “We are thrilled to be working with NEAR to educate and nurture talented individuals to become world-class blockchain developers,” says Kevin Imani. “Our dream is to lead the way in blockchain innovations in providing solutions to Africa’s biggest problems. The NEAR Protocol allows tomorrow’s brightest developers to build custom solutions with scalability, security, and transparency and this hub is the next step in turning our shared vision into reality.” How NEAR Meets kickstarted the Kenya Regional Hub Sankore founder Kevin Imani speaking at a Kenya Regional Hub event. Crucially, the new Kenya Regional Hub didn’t come out of nowhere. The Sankore-led NEAR Meets had overwhelming attendance, and were already hubs for locals gathering for blockchain and NEAR protocol education. The NEAR Meets a space to share ideas and create new Open Web opportunities. As such, these events created networking opportunities amongst both locals and the larger NEAR community. At the recent “Harnessing Opportunities in Web3” in Nakuru, a NEAR-Certified Developer helped local Kenyan developers become certified NEAR developers. The hub’s education arm already has strong connections with local universities, and registered 77 students in the NEAR Certified Developer Workshops. Seven other students are currently in NEAR Certified Analysts Workshops, while six students are already certified NEAR developers. Incubating blockchain projects in Africa Attendees at a Kenya Regional Hub event. With Sankore’s track record as a Kenyan project incubator, the Kenya Regional Hub will hit the ground running. Sankore created local traction by supporting several forward-thinking blockchain projects. Kilimo Shwari, for instance, helps local farmers hedge against agricultural uncertainties, like bad weather and Kenya’s recent locust invasion. Kilimo Shwari’s smart contract-based insurance gathers data on these and other uncertainties, and then automatically compensates farmers in advance. Another Sankore-backed project, Ledja, tackles document fraud throughout Africa. In partnership with local universities, Ledja is using the NEAR protocol to digitize and verify qualifications and legal documents. Africa’s rapid cryptocurrency adoption Attendees at a Kenya Regional Hub event. Over the past decade, African countries have been undergoing a rapid digital revolution. The continent’s cryptocurrency adoption jumped 1,200% from July 2020 to June 2021, the fastest adoption rate in the world. “We are excited by the potential avenues throughout Africa for blockchain solutions, which come from innovation in development, education and talent,” says Marieke Flament, CEO of the NEAR Foundation. “This hub represents a unique opportunity to partner with local talent not only for the opportunities that we know exist today but also for the opportunities yet to be created in the future.” The Kenya Regional Hub will demonstrate just how how easy it is to onboard into NEAR’s fast, low-cost, and safe ecosystem. They will find a host of DeFi projects, DAOs, NFT marketplaces, and more on NEAR. By showcasing these vibrant NEAR ecosystem projects, the Kenya hub will help unleash the next wave of Web3 innovation. NEAR Foundation is investing heavily in regional hubs around the world. Kenya joins a growing list of hubs in China, the Balkans, and Ukraine, with many more in the works. Led by great local entrepreneurs, NEAR Hubs operate as independent legal entities in full alignment with the foundation’s mission and objectives. All regional hubs are vital to onboarding users into the NEAR ecosystem to help build a multi-chain, open web future.
NEAR Launches Infrastructure Committee with $4 Million in Funding COMMUNITY April 8, 2024 NEAR has seen a massive surge in users and transactions over the last few months. It’s important to have a smooth-running blockchain for project and founder expansion. Today, the NEAR Foundation launches the Infrastructure Committee, a new initiative aimed to strengthen NEAR’s Key Infrastructure. With $4 million earmarked for infrastructure projects, the initiative is meant to support the success of NEAR projects while distributing funds and sourcing projects in an open, transparent way. What is Key Infrastructure? It includes RPC nodes, relayers, indexers, bridges, wallets, load balancers, and oracles. Also, NEAR should be listed correctly on all the DEX tools available. Incidents and outages need to be easily reported and fixed. The committee is made up of ecosystem leaders and NEAR partners from across core NEAR orgs. Its goals are to: Decentralize decision-making Enhance critical infrastructure Streamline efforts for greater clarity and decentralization The committee primarily focuses on proposals, with multiple Requests For Proposals (RFPs) planned to meet important ecosystem needs. These proposals will undergo review and asynchronous voting by the committee. Progress of the Infrastructure Committee The Infrastructure Committee has already funded five critical infrastructure proposals: Jutsu IDE infrastructure implementation (AI development environment) FASTNEAR infrastructure services (new RPC nodes and custom endpoints) Aurora Web 3.0 Wallet Support Services The building of a Treasury App for use by governing committees An audit of the Ledger integrations The committee also inherited some projects that it will now actively manage: Aurora RPC SpeedUp MyNEARWallet maintenance by Meteor With over half of the allocated $4 million budget remaining, there is an open invitation to the community to bring forward innovative infrastructure projects such as: Faster RPC Nodes Specific common endpoints to replace broad RPC queries New bridges to improve cross-chain transactions and increase the number of chains supported ICANN-compliant DNS and expansion of top-level domains Focused relayers to support gas-free and other specialized relayer needs The committee encourages community members to contribute their ideas, proposals, and feedback, and welcomes a range of perspectives from founders, developers, and NEAR enthusiasts on how to improve the foundations of NEAR technology. The current Infrastructure Committee is comprised of the following members: Abhishek Vaidyanathan, NEAR Foundation (serving as a non-voting meeting Chair) Alex Shevchenko, Aurora Labs Bowen Wang, Director of Protocol, Pagoda Vlad Frolov, DevHub Sandi Fatic, Calimero Eric Winer, Pagoda Illia Polosukhin, NEAR Foundation (serving as an ad-hoc member on an as-needed basis) Christopher Donovan, NEAR Foundation (serving as an ad-hoc member on an as-needed basis) The Working Group comprises the following admins and advisors: Project Oversight – Konrad Merino, Head of Blockchain Success, NEAR Foundation Product Manager – Gautham Ravi, Sr. Product Manager, Pagoda Project Manager – Trentin C Bergeron, Sr. Technical Program Manager, Pagoda Technical BD – Vikas Pandey, Success & Partner Engineering, NEAR Foundation Technical Advisor – Robert Tsia, SRE Manager, Pagoda Technical Advisor – Ernesto Cejas Padilla, Sr. SRE, Pagoda Technical Advisor – Firat Sertgoz, Engineering Manager, Pagoda Technical Advisor – Patrick Engvall, Sr. Engineer, Pagoda Technical Advisor – Pierre Leguen, Software Engineer, NEAR Foundation Finance Broadcast MC & Project Advisor – Marcus Ribeiro, Ecosystem Relations, NEAR Foundation For those looking to participate, the Interim Proposal and Funding Process provides a comprehensive guide on how to submit proposals. To foster transparency and public engagement, the committee has established clear processes to track and discuss proposals openly. The community can view the public tracking of proposals document and participate in public discussions, including announcements of Requests for Proposals (RFPs). The committee’s meeting notes will be shared with the community to maintain openness about the committee’s decisions and discussions. Engaging the Community and Fostering Collaboration To facilitate community engagement, anyone interested can join the discussion on the Github repo, which will serve as the hub for suggestions, collaboration, and support among members interested in contributing to NEAR infrastructure. The Infrastructure Mandate & Charter and Working Group Details will offer additional insights into the committee’s mission, structure, and ongoing projects. These resources are designed to educate and inspire community members to contribute their skills and ideas towards building a more robust and scalable NEAR ecosystem. Future Plans for the NEAR Infrastructure Committee As NEAR continues to grow, so will the necessity for robust infrastructure to support an increasing number of transactions and users. Future enhancements include the introduction of a more sophisticated incident management system and post-mortem processes for infrastructure outages. The development of a Blockchain Operating System (BOS)-based app for proposal management will be another significant move towards optimizing the efficiency of the funding process. This upgrade will streamline the proposal and funding workflow, making it easier for community members to submit and manage their projects. The committee’s work will also support NEAR’s growth and chain abstraction efforts, ensuring the blockchain can handle the anticipated surge in traffic as more users join the ecosystem. Those interested in getting involved with the Infrastructure Committee can join the Working Group Discussion on GitHub to collaborate on initiatives, discuss proposals and RFPs, or ask questions.
Berry Club: A Fun, Creative Example of a DeFi Yield Farming App on NEAR Blockchain COMMUNITY February 12, 2021 What is Berry Club? Berry Club is a DeFi app designed to let users have fun creating shared pixel art while farming token rewards. Berry Club achieves this with the elegant use of tokens called Avocados, Bananas, and Cucumbers. It’s also a great use of NEAR Protocol’s built-in features that aren’t found in other blockchains, such as automatic fee payments to smart contract creators. It started as a DeFi proof of concept, and has since grown into a popular community project on NEAR. In this post we’ll frame up how NEAR and Berry Club fit into the rapidly growing DeFi ecosystem. In the follow-up article we’ll walk through details of Berry Club and share my experiments using it for farming. DeFi and Yield Farming To be broad, DeFi (or decentralized finance) is a suite of smart contracts that brings traditional financial services to the blockchain. This includes lending and borrowing, exchange services, payments services, and much more. DeFi allows users to earn passive yield on their native blockchain assets (and, increasingly, tokenize their real world assets on the blockchain, too). DeFi has also been one of the largest growth sectors in the cryptocurrency market in the past few months. It wouldn’t be appropriate to mention earning a yield in DeFi without mentioning yield farming. What is yield farming? To be even more broad, yield farming involves distribution of a token to the users of a smart contract in order to incentivize a specific behavior. One of the most common examples of yield farming is distributing a token to users who provide liquidity to decentralized exchange pools such as Ethereum’s Uniswap. The users who deposit their funds into the smart contract benefit from cash flow denominated in the token, and the smart contract creators benefit from increased usage of their application (and liquidity, in the case of Uniswap). To generalize, most of the DeFi use cases on Ethereum are financially related, but not all. Yield Farming on NEAR Some Berry Farm shared artwork. Each pixel is earning a yield for its owner. In the case of Berry Club, tokens are distributed in order to encourage community creation of constantly-evolving artwork. Berry Farm and Banana Swap are partner contracts that allow automated exchange for Berry Farm tokens. Because of the unique design of the NEAR blockchain, the combination of Berry Club and Berry Farm can benefit both the users and the smart contract creators in an innovative way. Benefits are paid from increased usage of the application in the form of distribution of smart contract rewards to both creators and token holders. This is something that is not possible on Ethereum in its current implementation, and provides another great incentive for users and developers to start experimenting with NEAR. Popular images are less likely to be overwritten by other artists. The longer the pixel stays on the board, the more yield its owner will earn. Additionally, Banana Swap is what’s known as an automated market maker (AMM) – similar to Uniswap that was mentioned earlier – but simpler, and without the ability to add liquidity. While Berry Club and related contracts use tokens that are named after berries, make no mistake: this suite of smart contracts allows users to earn a real return on their NEAR tokens while making art on the blockchain. May the best artist win! NEAR vs Ethereum Certainly, Ethereum has the most DeFi applications with the most use cases as it stands today. But how does DeFi on NEAR compare to DeFi on Ethereum? For starters, yield farming at Berry Club is actually really fun and can bring out the creative side in even the most left-brained of us. The complexity of DeFi in and of itself can be a turn-off for some users, and a boring user interface does nothing to help with that user pain point, whereas Berry Farm is inherently art-based. Additionally, profit calculations are made much easier by the predictable and low transaction fees on NEAR. Ethereum transaction fees have been extremely volatile in the past few months, not to mention absurdly expensive, and can become a considerable expense for users that wish to yield farm on Ethereum. While the ecosystem of DeFi dApps on NEAR is still growing (Mooniswap is building on NEAR now, too), the ease of use and speed of DeFi dApps on NEAR cannot be understated, especially as somebody who often has large parts of their day tied up waiting for pending transactions to clear on the Ethereum blockchain. The Future of Berry Club We had a conversation with Evgeny (AKA “Eugene THE DREAM”), the creator of Berry Club, about the future of the project. He didn’t want to make any major changes to the economics or functionality of Berry Club in its current form. The addition of low opacity pixels is actually the second iteration of Berry Club, meant to encourage users to preserve the amazing artwork that others have created. We asked him if it would be possible to “scale” Berry Club by adjusting the size of the board (in the event that even more users start to use the application and yield dries up). Instead of merely changing the economics and size of the board, Evgeny described a potential future version of Berry Club that could include Dencentraland-esque plots of land. Ownership of the land would be achieved via non-fungible tokens, and could be rented out to hard working farmers. This, combined with some sort of incentivization system for rewarding the best artwork (we didn’t dive too deep into it), could further expand the Banana economy, and show off some more cool features that are in the works for the NEAR mainnet. Berry Club Points the Way That’s a brief overview of Berry Club’s purpose and features: a DeFi app that uses shared pixel art as a way to explore yield farming on the NEAR blockchain. It uses unique features of NEAR to point the way for numerous future DeFi apps on NEAR. And it’s not just for fun. You can earn real yield. In the next article, We’ll show you how. Join us for a more detailed walkthrough of Berry Club in Part 2: How Does The Berry Club Yield Farming App Work? Interested in building with NEAR, or just want to chat with a like-tribe community? Head on over to our Discord, follow us on Twitter, read up on our Forum and don’t forget to sign up for our newsletter.
--- id: network title: Network --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The RPC API enables you to query status information for nodes and validators. --- ## Node Status {#node-status} > Returns general status of a given node (sync status, nearcore node version, protocol version, etc), and the current set of validators. - method: `status` - params: `[]` Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "status", "params": [] } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.status(); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=status params:='[]' id=dontcare ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "version": { "version": "1.14.0-rc.1", "build": "effa3b7a-modified" }, "chain_id": "testnet", "protocol_version": 35, "latest_protocol_version": 35, "rpc_addr": "0.0.0.0:3030", "validators": [ { "account_id": "node3", "is_slashed": false }, { "account_id": "node0", "is_slashed": false }, { "account_id": "staked.pool.f863973.m0", "is_slashed": false }, { "account_id": "01node.pool.f863973.m0", "is_slashed": false }, { "account_id": "node2", "is_slashed": false }, { "account_id": "dokia.pool.f863973.m0", "is_slashed": false }, { "account_id": "node1", "is_slashed": false }, { "account_id": "lowfeevalidation.pool.f863973.m0", "is_slashed": false }, { "account_id": "sl1sub.pool.f863973.m0", "is_slashed": false }, { "account_id": "zainy.pool.f863973.m0", "is_slashed": false }, { "account_id": "chorus-one.pool.f863973.m0", "is_slashed": false }, { "account_id": "thepassivetrust.pool.f863973.m0", "is_slashed": false }, { "account_id": "certusone.pool.f863973.m0", "is_slashed": false }, { "account_id": "joe1.pool.f863973.m0", "is_slashed": false }, { "account_id": "bisontrails.pool.f863973.m0", "is_slashed": false }, { "account_id": "valeraverim.pool.f863973.m0", "is_slashed": false }, { "account_id": "lunanova.pool.f863973.m0", "is_slashed": false }, { "account_id": "bazilik.pool.f863973.m0", "is_slashed": false }, { "account_id": "dsrvlabs.pool.f863973.m0", "is_slashed": false }, { "account_id": "kronos.pool.f863973.m0", "is_slashed": false }, { "account_id": "nodeasy.pool.f863973.m0", "is_slashed": false }, { "account_id": "kytzu.pool.f863973.m0", "is_slashed": false }, { "account_id": "bitcat.pool.f863973.m0", "is_slashed": false }, { "account_id": "pool_easy2stake.pool.f863973.m0", "is_slashed": false }, { "account_id": "fresh_lockup.pool.f863973.m0", "is_slashed": false }, { "account_id": "staking-power.pool.f863973.m0", "is_slashed": false }, { "account_id": "syncnode.pool.f863973.m0", "is_slashed": false }, { "account_id": "inotel.pool.f863973.m0", "is_slashed": false }, { "account_id": "zpool.pool.f863973.m0", "is_slashed": false }, { "account_id": "aquarius.pool.f863973.m0", "is_slashed": false }, { "account_id": "cloudpost.pool.f863973.m0", "is_slashed": false }, { "account_id": "staked.pool.6fb1358", "is_slashed": false }, { "account_id": "moonlet.pool.f863973.m0", "is_slashed": false }, { "account_id": "jazza.pool.f863973.m0", "is_slashed": false }, { "account_id": "orangeclub.pool.f863973.m0", "is_slashed": false }, { "account_id": "blazenet.pool.f863973.m0", "is_slashed": false }, { "account_id": "pathrock.pool.f863973.m0", "is_slashed": false }, { "account_id": "stakin.pool.f863973.m0", "is_slashed": false }, { "account_id": "northernlights.stakingpool", "is_slashed": false }, { "account_id": "alexandruast.pool.f863973.m0", "is_slashed": false }, { "account_id": "top.pool.f863973.m0", "is_slashed": false } ], "sync_info": { "latest_block_hash": "44kieHwr7Gg5r72V3DgU7cpgV2aySkk5qbBCdvwens8T", "latest_block_height": 17774278, "latest_state_root": "3MD3fQqnm3JYa9UQgenEJsR6UHoWuHV4Tpr4hZY7QwfY", "latest_block_time": "2020-09-27T23:59:38.008063088Z", "syncing": false }, "validator_account_id": "nearup-node8" }, "id": "dontcare" } ``` </p> </details> #### What could go wrong? {#what-could-go-wrong} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `status` method: <table> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## Network Info {#network-info} > Returns the current state of node network connections (active peers, transmitted data, etc.) - method: `network_info` - params: _none_ Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "network_info", "params": [] } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=network_info params:='[]' id=dontcare ``` </TabItem> </Tabs> <details> <summary>Example response:</summary> <p> ```json { "jsonrpc": "2.0", "result": { "active_peers": [ { "id": "ed25519:GkDv7nSMS3xcqA45cpMvFmfV1o4fRF6zYo1JRR6mNqg5", "addr": "35.193.24.121:24567", "account_id": null } ], "num_active_peers": 34, "peer_max_count": 40, "sent_bytes_per_sec": 17754754, "received_bytes_per_sec": 492116, "known_producers": [ { "account_id": "node0", "addr": null, "peer_id": "ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX" } ] }, "id": "dontcare" } ``` </p> </details> #### What could go wrong? {#what-could-go-wrong-1} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `network_info` method: <table> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## Validation Status {#validation-status} > Queries active validators on the network returning details and the state of validation on the blockchain. - method: `validators` - params: `["block hash"]`, `[block number]`, `{"epoch_id": "epoch id"}`, `{"block_id": block number}`, `{"block_id": "block hash"}`, or `[null]` for the latest block **Note:** If you want the latest `block hash`, `block number` and `epoch id`, you will need to query from the last block in an epoch. You can also query validators endpoint for past epochs if you input `block hash`, `block number` or `epoch id` of the past epoch that you want. Example: input: `[block number]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": [17791098] } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=validators params:='[17791098]' id=dontcare ``` </TabItem> </Tabs> input: `["block hash"]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": ["FiG2nMjjue3YdgYAyM3ZqWXSaG6RJj5Gk7hvY8vrEoGw"] } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=validators params:='["FiG2nMjjue3YdgYAyM3ZqWXSaG6RJj5Gk7hvY8vrEoGw"]' id=dontcare ``` </TabItem> </Tabs> input: `{"block_id": "block hash"}` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": { "block_id": "FiG2nMjjue3YdgYAyM3ZqWXSaG6RJj5Gk7hvY8vrEoGw" } } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=validators \ params:='{ "block_id": "FiG2nMjjue3YdgYAyM3ZqWXSaG6RJj5Gk7hvY8vrEoGw" }' ``` </TabItem> </Tabs> input: `{"block_id": block number}` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": { "block_id": 17791098 } } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=validators \ params:='{ "block_id": 17791098 }` ``` </TabItem> </Tabs> input: `{"epoch_id": "epoch id"}` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": { "epoch_id": "8hJSZNNyimPvsCA1v3dMr3Hg5ucYeLUbTvEfhr6jaWJy" } } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=validators \ params:='{ "epoch_id": "8hJSZNNyimPvsCA1v3dMr3Hg5ucYeLUbTvEfhr6jaWJy" }` ``` </TabItem> </Tabs> input: `[null]` <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "validators", "params": [null] } ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 method=validators params:='[null]' id=dontcare ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "current_validators": [ { "account_id": "01node.pool.f863973.m0", "public_key": "ed25519:3iNqnvBgxJPXCxu6hNdvJso1PEAc1miAD35KQMBCA3aL", "is_slashed": false, "stake": "176429739989396285019500901780", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "alexandruast.pool.f863973.m0", "public_key": "ed25519:A3XJ3uVGxSi9o2gnG2r8Ra3fqqodRpL4iuLTc6fNdGUj", "is_slashed": false, "stake": "151430394143736014372434860532", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "aquarius.pool.f863973.m0", "public_key": "ed25519:8NfEarjStDYjJTwKUgQGy7Z7UTGsZaPhTUsExheQN3r1", "is_slashed": false, "stake": "130367563121508828296664196836", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "bazilik.pool.f863973.m0", "public_key": "ed25519:3pDJwDQ6Y5B9QeW1jz8KunhZH4D4GQG86reTmrRfdD7c", "is_slashed": false, "stake": "169013447850997135034919151338", "shards": [0], "num_produced_blocks": 211, "num_expected_blocks": 213 }, { "account_id": "bisontrails.pool.f863973.m0", "public_key": "ed25519:8g4P5EXyp2b2pfVMHY1QLfkRcY59hjPfWrFCKUWX3RmR", "is_slashed": false, "stake": "184162578269044826045352223479", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "bitcat.pool.f863973.m0", "public_key": "ed25519:9mtnwPQyyap1QNH9ag6r4the7Jkkpdyt9HUF5G1dWxKx", "is_slashed": false, "stake": "135215509376418353124295451543", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "blazenet.pool.f863973.m0", "public_key": "ed25519:DiogP36wBXKFpFeqirrxN8G2Mq9vnakgBvgnHdL9CcN3", "is_slashed": false, "stake": "137364229255641651855065314186", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "certusone.pool.f863973.m0", "public_key": "ed25519:CKW7f41Kn8YCDPzaGLs1MrPb9h3BjQmHhbei6Ff6nRRF", "is_slashed": false, "stake": "176644821310043228577017742667", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "chorus-one.pool.f863973.m0", "public_key": "ed25519:6LFwyEEsqhuDxorWfsKcPPs324zLWTaoqk4o6RDXN7Qc", "is_slashed": false, "stake": "110397600457815316527526651811", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 213 }, { "account_id": "cloudpost.pool.f863973.m0", "public_key": "ed25519:AVVLmJDG8z6UgmW9fmJGVFTdYxxfnqXH6c7FVQmhE6dp", "is_slashed": false, "stake": "136597929514591130855076834167", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "dokia.pool.f863973.m0", "public_key": "ed25519:935JMz1vLcJxFApG3TY4MA4RHhvResvoGwCrQoJxHPn9", "is_slashed": false, "stake": "220445043066799898276306006919", "shards": [0], "num_produced_blocks": 426, "num_expected_blocks": 426 }, { "account_id": "dsrvlabs.pool.f863973.m0", "public_key": "ed25519:61ei2efmmLkeDR1CG6JDEC2U3oZCUuC2K1X16Vmxrud9", "is_slashed": false, "stake": "161508967845718247649113721019", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "fresh_lockup.pool.f863973.m0", "public_key": "ed25519:7CMFLtEohojtxBkmj9Jb6AGgbphb1zvxymHzpzuyCjfG", "is_slashed": false, "stake": "193574159400241036715020269158", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "inotel.pool.f863973.m0", "public_key": "ed25519:C55jH1MCHYGa3tzUyZZdGrJmmCLP22Aa4v88KYpn2xwZ", "is_slashed": false, "stake": "178598870951670469578754984993", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "jazza.pool.f863973.m0", "public_key": "ed25519:85cPMNVrqUz8N7oWbbvWbUuamHcJNe49uRbaSzftLCz9", "is_slashed": false, "stake": "155762349362951827286303475797", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "joe1.pool.f863973.m0", "public_key": "ed25519:G3SxwzmiEZSm3bHnTLtxJvm3NvT1TLQcWuV1iod6i6NJ", "is_slashed": false, "stake": "129230772267511696840933436174", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "kronos.pool.f863973.m0", "public_key": "ed25519:3i2pertqzF8xqkJ4BrE4t4r67YiYYrUKCktbqvDgjzuQ", "is_slashed": false, "stake": "144544279093485390569527924033", "shards": [0], "num_produced_blocks": 202, "num_expected_blocks": 213 }, { "account_id": "kytzu.pool.f863973.m0", "public_key": "ed25519:61tgPZpy8tqFeAwG4vtf2ZKCRoENiP2A1TJVWEwnbxZU", "is_slashed": false, "stake": "113758432843198726378418342568", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "lowfeevalidation.pool.f863973.m0", "public_key": "ed25519:EXyjSMGSnk5uGphF3gVV1jCudaAudbW8imoEccYEJg3V", "is_slashed": false, "stake": "113685537557977098595863252617", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "lunanova.pool.f863973.m0", "public_key": "ed25519:2fZ59qfo9QHNLijoht9cwUb9enSNcnRmXbQn1gKZxvkw", "is_slashed": false, "stake": "172903039219549397267702571804", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "moonlet.pool.f863973.m0", "public_key": "ed25519:3e1nVCVGNS3yr6CcUvpDAs3BhiWtyM9uTBWkyVR5Xn3K", "is_slashed": false, "stake": "140599784944681716744261599779", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "node0", "public_key": "ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX", "is_slashed": false, "stake": "1907234923845608896091985071588", "shards": [0], "num_produced_blocks": 3614, "num_expected_blocks": 3616 }, { "account_id": "node1", "public_key": "ed25519:6DSjZ8mvsRZDvFqFxo8tCKePG96omXW7eVYVSySmDk8e", "is_slashed": false, "stake": "1906065501889463342906704128820", "shards": [0], "num_produced_blocks": 3613, "num_expected_blocks": 3614 }, { "account_id": "node2", "public_key": "ed25519:GkDv7nSMS3xcqA45cpMvFmfV1o4fRF6zYo1JRR6mNqg5", "is_slashed": false, "stake": "1840271519773089248112279578450", "shards": [0], "num_produced_blocks": 3615, "num_expected_blocks": 3615 }, { "account_id": "node3", "public_key": "ed25519:ydgzeXHJ5Xyt7M1gXLxqLBW1Ejx6scNV5Nx2pxFM8su", "is_slashed": false, "stake": "1247270566437910246525604113433", "shards": [0], "num_produced_blocks": 2335, "num_expected_blocks": 2342 }, { "account_id": "nodeasy.pool.f863973.m0", "public_key": "ed25519:25Dhg8NBvQhsVTuugav3t1To1X1zKiomDmnh8yN9hHMb", "is_slashed": false, "stake": "131652957125263756523827257067", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "northernlights.stakingpool", "public_key": "ed25519:CsMecqKCfagnebMB3ha1uRubay5Z4V85req23bNAJSG3", "is_slashed": false, "stake": "159669819380982417675619400525", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "orangeclub.pool.f863973.m0", "public_key": "ed25519:HezFeSzcwuR5wvkqccgMCMnpf1eQkVCfk52tXZEdKZHz", "is_slashed": false, "stake": "143971234567521206686862639104", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "pathrock.pool.f863973.m0", "public_key": "ed25519:G138GdQsU7PdFLD6X88NmTLAEDR7agPcq9HLZqGpegkm", "is_slashed": false, "stake": "125204431569306697735287326827", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "pool_easy2stake.pool.f863973.m0", "public_key": "ed25519:8nzKxvmyeauQRehWkby8GfWNLgqPiF5FCRFSD75M1Rwh", "is_slashed": false, "stake": "176893731686620703671521068552", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "sl1sub.pool.f863973.m0", "public_key": "ed25519:3URBpNUjNAMzugQH1rdSKMtwFM8AwHaJgZk5Z6YtnfFL", "is_slashed": false, "stake": "155741680601335529540438949153", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 213 }, { "account_id": "staked.pool.6fb1358", "public_key": "ed25519:684rMbuVYYgL2CkmYgC1weLh3erd2bwrmtQtJJhWzPwj", "is_slashed": false, "stake": "126911347639167461321544980789", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "staked.pool.f863973.m0", "public_key": "ed25519:D2afKYVaKQ1LGiWbMAZRfkKLgqimTR74wvtESvjx5Ft2", "is_slashed": false, "stake": "140558085958535444819294942478", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "stakin.pool.f863973.m0", "public_key": "ed25519:GvddxjaxBCqGGB4kMNWNFtvozU1EEZ2jrnggKZW8LaU4", "is_slashed": false, "stake": "122221693837484004905170552626", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "staking-power.pool.f863973.m0", "public_key": "ed25519:4s79F6Fdjgb3rHXPLwaXZG4Hq7Za8nogUu3vXEamRBQo", "is_slashed": false, "stake": "113293334165305165414435157738", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "syncnode.pool.f863973.m0", "public_key": "ed25519:FUAVDkmLhuTbKYv4GWuWv9ogjKzRatLd5ZBMKXRy7WqE", "is_slashed": false, "stake": "133414422809248011010747790387", "shards": [0], "num_produced_blocks": 212, "num_expected_blocks": 212 }, { "account_id": "thepassivetrust.pool.f863973.m0", "public_key": "ed25519:4NccD2DNJpBkDmWeJ2GbqPoivQ93qcKiR4PHALJKCTod", "is_slashed": false, "stake": "162714097201953456968339272308", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "top.pool.f863973.m0", "public_key": "ed25519:FR5qxAsP8GgXDN96pappLtWMywiqWsPVqT3HLE3YaUx", "is_slashed": false, "stake": "164760602493727447176131601464", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "valeraverim.pool.f863973.m0", "public_key": "ed25519:3686ABqNUZc1qhLWLHg5xZpBzrWPiUCMNZxcCNmg3e2s", "is_slashed": false, "stake": "191733144511459134091274432419", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "zainy.pool.f863973.m0", "public_key": "ed25519:37KfhBNYjqpaUVh3ft5kPcFn3xK1eVvtDZJCQQVCGnzQ", "is_slashed": false, "stake": "113441017844444454951489924484", "shards": [0], "num_produced_blocks": 213, "num_expected_blocks": 213 }, { "account_id": "zpool.pool.f863973.m0", "public_key": "ed25519:ETFRFNHfvd6fpj74MGYYQp3diY8WB4bFmWMxjTB2yY4V", "is_slashed": false, "stake": "140932616764414290525265048028", "shards": [0], "num_produced_blocks": 120, "num_expected_blocks": 212 } ], "next_validators": [ { "account_id": "01node.pool.f863973.m0", "public_key": "ed25519:3iNqnvBgxJPXCxu6hNdvJso1PEAc1miAD35KQMBCA3aL", "stake": "177341160716540400974121040893", "shards": [0] }, { "account_id": "alexandruast.pool.f863973.m0", "public_key": "ed25519:A3XJ3uVGxSi9o2gnG2r8Ra3fqqodRpL4iuLTc6fNdGUj", "stake": "152212670433756011274558210225", "shards": [0] }, { "account_id": "aquarius.pool.f863973.m0", "public_key": "ed25519:8NfEarjStDYjJTwKUgQGy7Z7UTGsZaPhTUsExheQN3r1", "stake": "131041030638338742265060835987", "shards": [0] }, { "account_id": "bazilik.pool.f863973.m0", "public_key": "ed25519:3pDJwDQ6Y5B9QeW1jz8KunhZH4D4GQG86reTmrRfdD7c", "stake": "169886556654364796730036727847", "shards": [0] }, { "account_id": "bisontrails.pool.f863973.m0", "public_key": "ed25519:8g4P5EXyp2b2pfVMHY1QLfkRcY59hjPfWrFCKUWX3RmR", "stake": "185113946165399113822995097304", "shards": [0] }, { "account_id": "bitcat.pool.f863973.m0", "public_key": "ed25519:9mtnwPQyyap1QNH9ag6r4the7Jkkpdyt9HUF5G1dWxKx", "stake": "135914020962862866419944507506", "shards": [0] }, { "account_id": "blazenet.pool.f863973.m0", "public_key": "ed25519:DiogP36wBXKFpFeqirrxN8G2Mq9vnakgBvgnHdL9CcN3", "stake": "138073840925159254185212483041", "shards": [0] }, { "account_id": "certusone.pool.f863973.m0", "public_key": "ed25519:CKW7f41Kn8YCDPzaGLs1MrPb9h3BjQmHhbei6Ff6nRRF", "stake": "177557353126393581856047095474", "shards": [0] }, { "account_id": "chorus-one.pool.f863973.m0", "public_key": "ed25519:6LFwyEEsqhuDxorWfsKcPPs324zLWTaoqk4o6RDXN7Qc", "stake": "110967904880664326100649881128", "shards": [0] }, { "account_id": "cloudpost.pool.f863973.m0", "public_key": "ed25519:AVVLmJDG8z6UgmW9fmJGVFTdYxxfnqXH6c7FVQmhE6dp", "stake": "137303582563490110045159846741", "shards": [0] }, { "account_id": "dokia.pool.f863973.m0", "public_key": "ed25519:935JMz1vLcJxFApG3TY4MA4RHhvResvoGwCrQoJxHPn9", "stake": "221583843027440134728813179120", "shards": [0] }, { "account_id": "dsrvlabs.pool.f863973.m0", "public_key": "ed25519:61ei2efmmLkeDR1CG6JDEC2U3oZCUuC2K1X16Vmxrud9", "stake": "162343309156672629963246208215", "shards": [0] }, { "account_id": "fresh_lockup.pool.f863973.m0", "public_key": "ed25519:7CMFLtEohojtxBkmj9Jb6AGgbphb1zvxymHzpzuyCjfG", "stake": "194574146707912827852030100603", "shards": [0] }, { "account_id": "inotel.pool.f863973.m0", "public_key": "ed25519:C55jH1MCHYGa3tzUyZZdGrJmmCLP22Aa4v88KYpn2xwZ", "stake": "179521497218882663562358374377", "shards": [0] }, { "account_id": "jazza.pool.f863973.m0", "public_key": "ed25519:85cPMNVrqUz8N7oWbbvWbUuamHcJNe49uRbaSzftLCz9", "stake": "156567004141558073310769195719", "shards": [0] }, { "account_id": "joe1.pool.f863973.m0", "public_key": "ed25519:G3SxwzmiEZSm3bHnTLtxJvm3NvT1TLQcWuV1iod6i6NJ", "stake": "129898367221448376460128575495", "shards": [0] }, { "account_id": "kronos.pool.f863973.m0", "public_key": "ed25519:3i2pertqzF8xqkJ4BrE4t4r67YiYYrUKCktbqvDgjzuQ", "stake": "145291600307308103830278523851", "shards": [0] }, { "account_id": "kytzu.pool.f863973.m0", "public_key": "ed25519:61tgPZpy8tqFeAwG4vtf2ZKCRoENiP2A1TJVWEwnbxZU", "stake": "114346099616381729581424582943", "shards": [0] }, { "account_id": "lowfeevalidation.pool.f863973.m0", "public_key": "ed25519:EXyjSMGSnk5uGphF3gVV1jCudaAudbW8imoEccYEJg3V", "stake": "114272827178534171015566175242", "shards": [0] }, { "account_id": "lunanova.pool.f863973.m0", "public_key": "ed25519:2fZ59qfo9QHNLijoht9cwUb9enSNcnRmXbQn1gKZxvkw", "stake": "173796241314359640924313305613", "shards": [0] }, { "account_id": "moonlet.pool.f863973.m0", "public_key": "ed25519:3e1nVCVGNS3yr6CcUvpDAs3BhiWtyM9uTBWkyVR5Xn3K", "stake": "141326111231422084384405939935", "shards": [0] }, { "account_id": "node0", "public_key": "ed25519:7PGseFbWxvYVgZ89K1uTJKYoKetWs7BJtbyXDzfbAcqX", "stake": "1917087533938315356792420553580", "shards": [0] }, { "account_id": "node1", "public_key": "ed25519:6DSjZ8mvsRZDvFqFxo8tCKePG96omXW7eVYVSySmDk8e", "stake": "1915912070849706566898523265362", "shards": [0] }, { "account_id": "node2", "public_key": "ed25519:GkDv7nSMS3xcqA45cpMvFmfV1o4fRF6zYo1JRR6mNqg5", "stake": "1849778202731933988446605407109", "shards": [0] }, { "account_id": "node3", "public_key": "ed25519:ydgzeXHJ5Xyt7M1gXLxqLBW1Ejx6scNV5Nx2pxFM8su", "stake": "1253713857932062021626652303305", "shards": [0] }, { "account_id": "nodeasy.pool.f863973.m0", "public_key": "ed25519:25Dhg8NBvQhsVTuugav3t1To1X1zKiomDmnh8yN9hHMb", "stake": "132333065508677559475570461579", "shards": [0] }, { "account_id": "northernlights.stakingpool", "public_key": "ed25519:CsMecqKCfagnebMB3ha1uRubay5Z4V85req23bNAJSG3", "stake": "160494659810582810750858869593", "shards": [0] }, { "account_id": "orangeclub.pool.f863973.m0", "public_key": "ed25519:HezFeSzcwuR5wvkqccgMCMnpf1eQkVCfk52tXZEdKZHz", "stake": "144714977470413958038055754809", "shards": [0] }, { "account_id": "pathrock.pool.f863973.m0", "public_key": "ed25519:G138GdQsU7PdFLD6X88NmTLAEDR7agPcq9HLZqGpegkm", "stake": "125851226796631921571804668732", "shards": [0] }, { "account_id": "pool_easy2stake.pool.f863973.m0", "public_key": "ed25519:8nzKxvmyeauQRehWkby8GfWNLgqPiF5FCRFSD75M1Rwh", "stake": "177807549352374182247265978294", "shards": [0] }, { "account_id": "sl1sub.pool.f863973.m0", "public_key": "ed25519:3URBpNUjNAMzugQH1rdSKMtwFM8AwHaJgZk5Z6YtnfFL", "stake": "156546228606913052982706314599", "shards": [0] }, { "account_id": "staked.pool.6fb1358", "public_key": "ed25519:684rMbuVYYgL2CkmYgC1weLh3erd2bwrmtQtJJhWzPwj", "stake": "127566960646771620637977634520", "shards": [0] }, { "account_id": "staked.pool.f863973.m0", "public_key": "ed25519:D2afKYVaKQ1LGiWbMAZRfkKLgqimTR74wvtESvjx5Ft2", "stake": "141284196855966747583242721111", "shards": [0] }, { "account_id": "stakin.pool.f863973.m0", "public_key": "ed25519:GvddxjaxBCqGGB4kMNWNFtvozU1EEZ2jrnggKZW8LaU4", "stake": "122853080560791799567241762038", "shards": [0] }, { "account_id": "staking-power.pool.f863973.m0", "public_key": "ed25519:4s79F6Fdjgb3rHXPLwaXZG4Hq7Za8nogUu3vXEamRBQo", "stake": "113878597697173990840757447344", "shards": [0] }, { "account_id": "syncnode.pool.f863973.m0", "public_key": "ed25519:FUAVDkmLhuTbKYv4GWuWv9ogjKzRatLd5ZBMKXRy7WqE", "stake": "134103630138795323490241660174", "shards": [0] }, { "account_id": "thepassivetrust.pool.f863973.m0", "public_key": "ed25519:4NccD2DNJpBkDmWeJ2GbqPoivQ93qcKiR4PHALJKCTod", "stake": "163554668234785516757420218799", "shards": [0] }, { "account_id": "top.pool.f863973.m0", "public_key": "ed25519:FR5qxAsP8GgXDN96pappLtWMywiqWsPVqT3HLE3YaUx", "stake": "165611741467072665024638629174", "shards": [0] }, { "account_id": "valeraverim.pool.f863973.m0", "public_key": "ed25519:3686ABqNUZc1qhLWLHg5xZpBzrWPiUCMNZxcCNmg3e2s", "stake": "192723621295992295990275575014", "shards": [0] }, { "account_id": "zainy.pool.f863973.m0", "public_key": "ed25519:37KfhBNYjqpaUVh3ft5kPcFn3xK1eVvtDZJCQQVCGnzQ", "stake": "114027175849273464802110072969", "shards": [0] }, { "account_id": "zpool.pool.f863973.m0", "public_key": "ed25519:ETFRFNHfvd6fpj74MGYYQp3diY8WB4bFmWMxjTB2yY4V", "stake": "141660662431449802378487016195", "shards": [0] } ], "current_fishermen": [ { "account_id": "staked.stakingpool", "public_key": "ed25519:5VmCXxWepj22uFoKmrxk6DTiFa3fuTzDcwGxM8uUErpr", "stake": "5957256918881889179239884296" }, { "account_id": "bisontrails.stakingpool", "public_key": "ed25519:ED2v5KtScbk6aNjGcTn1YMDUu3EXfD5HPt1x6RiYBypk", "stake": "7679439354334034871130713908" }, { "account_id": "cryptium.stakingpool", "public_key": "ed25519:2usUkjmKWxQw7QUeFfELHCEqS2UxjwsRqnCkA5oQ6A2B", "stake": "6484546971716985483357166277" }, { "account_id": "buildlinks3.pool.f863973.m0", "public_key": "ed25519:Cfy8xjSsvVquSqo7W4A2bRX1vkLPycLgyCvFNs3Rz6bb", "stake": "81221864655530313350540629757" }, { "account_id": "mmm.pool.f863973.m0", "public_key": "ed25519:3jEqDDKaJEg1r8UGu2x2dC55BXE7i26yNFQzvfJkkHkf", "stake": "80030001196381772535600000000" } ], "next_fishermen": [ { "account_id": "staked.stakingpool", "public_key": "ed25519:5VmCXxWepj22uFoKmrxk6DTiFa3fuTzDcwGxM8uUErpr", "stake": "5957256918881889179239884296" }, { "account_id": "bisontrails.stakingpool", "public_key": "ed25519:ED2v5KtScbk6aNjGcTn1YMDUu3EXfD5HPt1x6RiYBypk", "stake": "7679439354334034871130713908" }, { "account_id": "cryptium.stakingpool", "public_key": "ed25519:2usUkjmKWxQw7QUeFfELHCEqS2UxjwsRqnCkA5oQ6A2B", "stake": "6484546971716985483357166277" }, { "account_id": "buildlinks3.pool.f863973.m0", "public_key": "ed25519:Cfy8xjSsvVquSqo7W4A2bRX1vkLPycLgyCvFNs3Rz6bb", "stake": "81221864655530313350540629757" }, { "account_id": "mmm.pool.f863973.m0", "public_key": "ed25519:3jEqDDKaJEg1r8UGu2x2dC55BXE7i26yNFQzvfJkkHkf", "stake": "80030001196381772535600000000" } ], "current_proposals": [ { "account_id": "kytzu.pool.f863973.m0", "public_key": "ed25519:61tgPZpy8tqFeAwG4vtf2ZKCRoENiP2A1TJVWEwnbxZU", "stake": "114346100195275968419224582943" }, { "account_id": "nodeasy.pool.f863973.m0", "public_key": "ed25519:25Dhg8NBvQhsVTuugav3t1To1X1zKiomDmnh8yN9hHMb", "stake": "132333066144809013154670461579" }, { "account_id": "thepassivetrust.pool.f863973.m0", "public_key": "ed25519:4NccD2DNJpBkDmWeJ2GbqPoivQ93qcKiR4PHALJKCTod", "stake": "163554672455685458970920218837" } ], "prev_epoch_kickout": [], "epoch_start_height": 17754191, "epoch_height": 321 }, "id": "dontcare" } ``` </p> </details> #### What could go wrong? {#what-could-go-wrong-2} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `validators` method: <table> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td>HANDLER_ERROR</td> <td>UNKNOWN_EPOCH</td> <td>An epoch for the provided block can't be found in a database</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to an archival node</li> <li>Check that the requested block is the last block of some epoch</li> </ul> </td> </tr> <tr> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> ---
--- sidebar_position: 4 --- # Payable Methods We can allow methods to accept token transfer together with the function call. This is done so that contracts can define a fee in tokens that needs to be paid when they are used. By default the methods are not payable and they will panic if someone will attempt to transfer tokens to them during the invocation. This is done for safety reason, in case someone accidentally transfers tokens during the function call. To declare a method as payable, use the `#[payable]` annotation within the [`near_bindgen` macro](../contract-structure/near-bindgen.md) as follows: ```rust #[payable] pub fn my_method(&mut self) { ... } ``` This will allow the `my_method` function to be called and transfer balance to the contract. Example: ```rust #[near_bindgen] impl Contract { #[payable] pub fn take_my_money(&mut self) { near_sdk::env::log_str("Thanks!"); } pub fn do_not_take_my_money(&mut self) { near_sdk::env::log_str("Thanks!"); } } ``` is equivalent to: ```rust #[near_bindgen] impl Contract { pub fn take_my_money(&mut self) { near_sdk::env::log_str("Thanks!"); } pub fn do_not_take_my_money(&mut self) { if near_sdk::env::attached_deposit() != 0 { near_sdk::env::panic_str("Method do_not_take_my_money doesn't accept deposit"); } near_sdk::env::log_str("Thanks!"); } } ```
NEAR CLI 3.0.0 Released DEVELOPERS December 2, 2021 Our command-line interface tool just got a new major version release that introduced some big changes. NEAR’s DevRel team would like to take a moment to go over these changes to not only show you the changelog but explain why these changes were made. This is a new initiative to give our developer community an insight into our decision-making process as well as a better understanding of how NEAR works. Deployment changes – near deploy now warns users if there is an existing contract deployed. (PR #883) near deploy (used for deploying smart contracts to a given account) now has an added prompt warning users if an existing contract has already been deployed. NEAR accounts can only have one contract deployed per account, but we frequently saw developers would accidentally overwrite existing contracts, especially when first onboarding to our platform. This prompt should help folks understand the singular contract concept and mitigate any accidental state changes to existing smart contracts. Access Keys changes – near delete-key now prompts for confirmation of key deletion. (PR #890) Similar to the near deploy update, near delete-key (used for deleting an access key from an account) now prompts users for confirmation of this action. It will also ask the user to make sure this key is not for a recovery method. In addition, if you are deleting the last full-access key it will give a second prompt warning the user that this will fully lock the account/contract. Deleting all full-access keys will disable the ability to recover access to an account and should have an extra warning layer to prevent an accidental ownership lockout. New flags – `-f, –force` flags added to override warning prompts. (PR #890) The two big changes introduced with this CLI release are only new for those who are already using scripts to run the above commands (deploy and delete-key). For those who want to upgrade to NEAR CLI 3.0.0 and still use scripting for these commands, we have added the -f or –force flags to override the warning prompts.
```js const tokenContract = "token.v2.ref-finance.near"; const tokenMetadata = Near.view(tokenContract, "ft_metadata", {}); ``` <details> <summary>Example response</summary> <p> ```json { "spec": "ft-1.0.0", "name": "Ref Finance Token", "symbol": "REF", "icon": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='16 24 248 248' style='background: %23000'%3E%3Cpath d='M164,164v52h52Zm-45-45,20.4,20.4,20.6-20.6V81H119Zm0,18.39V216h41V137.19l-20.6,20.6ZM166.5,81H164v33.81l26.16-26.17A40.29,40.29,0,0,0,166.5,81ZM72,153.19V216h43V133.4l-11.6-11.61Zm0-18.38,31.4-31.4L115,115V81H72ZM207,121.5h0a40.29,40.29,0,0,0-7.64-23.66L164,133.19V162h2.5A40.5,40.5,0,0,0,207,121.5Z' fill='%23fff'/%3E%3Cpath d='M189 72l27 27V72h-27z' fill='%2300c08b'/%3E%3C/svg%3E%0A", "reference": null, "reference_hash": null, "decimals": 18 } ``` </p> </details>
NEARCON ‘23 Lifts Off: Start Your Journey into the Open Web NEAR FOUNDATION November 8, 2023 Lisbon is about to light up as NEARCON ‘23 kicks off in the heart of the city. The stars are aligned for Day One to kick things off in spectacular fashion with a wide array of sessions, speakers, and activities you won’t want to miss. Doors open at 9:00 AM for breakfast, so make sure to head on over bright an early, grab a bite with your fellow NEARCON-goers. And stay connected throughout the conference with Calimero Chat for private, decentralized comms on the NEAR blockchain. So start off the most iconic NEARCON yet and catch some of the most intriguing and impactful happenings on what promises to be an epic first day of NEARCON ‘23. Can’t miss speaker sessions Speaker stages ramp up at 10:45 AM until 5:30 PM, so set your alarms for an invigorating start to NEARCON ‘23 with sessions that promise to shape your understanding of the open web and the NEAR ecosystem. NEAR: The Open Web Stack (2:00 PM – 2:30 PM at Layer 1 Stage). Join Illia Polosukhin, CEO of NEAR Foundation and NEAR co-founder, as he shares his strategic vision on what’s next for the NEAR ecosystem. Regulating the Open Web (1:40 PM – 2:00 PM, Layer 1 Stage). Michael Casey from CoinDesk and NEAR Foundation COO Chris Donovan take a forward-thinking look at regulatory headwinds and regional approaches to open web regulations. Innovations in AI, Account Abstraction, and NFTs Today (3:00PM – 3:15 PM, Layer 2 stage). If you’re into the intersection of AI and NFTs, Nate Grier of Mintbase’s talk is one you won’t want to miss. Marketing Through Web3 Mechanisms at DevHub and Beyond (4:15 PM – 4:30 PM, Block Zero Stage). Shardog’s Joe Spano shares how the open web provides unique opportunities to create relationships while allowing users to retain control and privacy. More speaker highlights The Interop Future (11:30 AM – 12:00PM at Layer 1 Stage). An in-depth panel including Aurora founder Alex Shevchenko, and Mariano Sorgente of a16z will dive into NEAR’s critical role in driving open web interoperability. Unstore Your Data for the AI Revolution (11:20 AM – 11:40AM at Block Zero Stage). Don’t miss Jonathan Bryce and Polina Aladina from OnMachina as they delve into the future of data and AI, exploring new ways of working with unstructured data. Anjali Young’s Web3 Advertising Revolution (1:15 PM – 1:30 PM, Layer 2 Stage). Dive into the world of advertising and the open web with Anjali Young from Collab.Land. She’ll illustrate how Web3 is redefining brand-customer relationships through community engagement, NFTs, and token-gated communities. Richard Muirhead’s Vision of the Open Economy (4:30PM – 4:45 PM, Layer 1 Stage). Fabric Ventures’ Richard Muirhead presents a compelling vision of 2023’s open economy, discussing the profound impact of token economics and the massive impact of AI on decentralized economies. Conclude your day enriched with insights from these thought leaders of the open web, and get revved up for the evening networking and festivities. Hackathon and HZN1 in full force There’s also tons of activity for builders, founders, and developers during Day One. Things kick off at 9:00AM with the all day HZ1 Retreat for Founders. It’s an invite-only event so if you’re on the list, get ready for a full day of jumpstarting your vision supported by the best open web experts until 5:00PM. And then there’s what promises to be an epic Hackathon. Make sure you’re registered, submit your projects, and join your fellow builders over at the Hacker HQ. Get the full low-down over at the official NEARCON ‘23 Hackathon webpage, and kick things off with a full day of hacking and B.O.S building. Finally, there’s the invite-only Validator Session at Hacker HQ from 1:00-4:00PM, so if you’re registered for that don’t forget to check it out and participate. Must attend side events SailGP Happy Hour (5:45 – 7:00 PM, SailGP Lounge, Layer 2 Stage): Wind down from a dynamic day of sessions and celebrate the community spirit of NEARCON ‘23 with one of the pioneers of Web3 and fan engagement.. Opening Night Party (8:00 PM, Pavilhão Carlos Lopes): Don’t miss Day One’s biggest networking event, sponsored by Cosmose AI and BitGo, where the energy of NEARCON ‘23 will be on full display under the Lisbon stars. Shout out to the Day One sponsors A heartfelt thanks to our sponsors that highlighted Day One of NEARCON ‘23: SailGP BitGo Cosmose AI PlayEmber Aurora Labs Day One of NEARCON promises to be an amazing kick off to an iconic gathering of minds, builders, and creators in the open web. From interoperability and cryptonomics to drinks and brainstorming well into the night, make sure to mark your calendars for all of the notable speakers and sessions that will make Day One a simply can’t miss.
--- id: indexer-for-explorer title: Indexer for Explorer (Deprecated) --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; While developing a decentralized app you might want to query usage information for a contract such as: 1. Which users have called a specific method in my contract? 2. How much money and gas did they deposit? 3. Which transactions failed? In order to simplify asking these questions is that we developed the [NEAR Indexer for Explorer](https://github.com/near/near-indexer-for-explorer). Both `testnet` and `mainnet` networks have active instances that fill the database with all the data from the network starting from the genesis as [Explorer](https://nearblocks.io/) requires. :::info GitHub repo NEAR Indexer for Explorer is an indexer built on top of [NEAR Indexer microframework](/concepts/advanced/near-indexer-framework). It watches the network and stores all the data from the blockchain in the PostgreSQL database. You can find the source code on [this GitHub repository](https://github.com/near/near-indexer-for-explorer). ::: --- ## Example Queries ### Transactions Calling a Method Query for all transactions that called `contribute` in the `v1.faucet.nonofficial.testnet` testnet account. ```sql select r.predecessor_account_id, t.transaction_hash from receipts r, action_receipt_actions ara, transactions t where r.receiver_account_id ='v1.faucet.nonofficial.testnet' and ara.receipt_id = r.receipt_id and ara.action_kind = 'FUNCTION_CALL' and ara.args @> '{"method_name": "contribute"}' and t.transaction_hash = r.originated_from_transaction_hash ``` <hr className="subsection" /> ### Users, Status, and Attached Money Query for all users that called `contribute` in `v1.faucet.nonofficial.testnet`, how much they attached to the call, and the transaction status. ```sql select t.transaction_hash, eo.status, r.predecessor_account_id , ara.args -> 'deposit' as deposit from receipts r, action_receipt_actions ara, transactions t, execution_outcomes eo where r.receiver_account_id ='v1.faucet.nonofficial.testnet' and ara.receipt_id = r.receipt_id and ara.action_kind = 'FUNCTION_CALL' and ara.args @> '{"method_name": "contribute"}' and t.transaction_hash = r.originated_from_transaction_hash and r.receipt_id = eo.receipt_id ``` <hr className="subsection" /> ### Sent Money Query for all the transfers going out from `v1.faucet.nonofficial.testnet`. ```sql select r.receiver_account_id, ara.args -> 'deposit' as deposit from receipts r, action_receipt_actions ara where r.predecessor_account_id ='v1.faucet.nonofficial.testnet' and ara.receipt_id = r.receipt_id and ara.action_kind = 'TRANSFER' ``` --- ## NEAR Explorer sunsetting Pagoda made a decision to sunset NEAR Explorer as a product. This means that `nearblocks.io` (and `explorer.testnet.near.org`) will become a landing page with a list of available alternatives, and the existing [nearblocks.io](https://nearblocks.io) will be hosted under a new domain name and will be transitioned to the community through DevHub. [Read more here](https://near.social/devgovgigs.near/widget/gigs-board.pages.Post?id=635). ### What exactly is being shut down? You will lose access to databases with these URLs, or other Replicas you might have been given access to: * `testnet.db.explorer.indexer.near.dev/testnet_explorer` * `mainnet.db.explorer.indexer.near.dev/mainnet_explorer` There is no plan to shut down any other data products, such as [NEAR Lake](https://docs.near.org/concepts/advanced/near-lake-framework) or [EnhancedAPI](https://www.pagoda.co/enhanced-api) at the moment. ### What is the timeline? Postgres users will lose access to data on the 30th of November, Thursday (12:00 pm Pacific Time Zone). Please migrate to one of the options listed below instead. ### What does this mean for me? If you are using the public Postgres Explorer Database, you will need to migrate to other solutions, depending on your use-case. You should start planning for it right now and reach out to [this Telegram group](https://nearbuilders.com/tg-data) to get help. ### What are the alternatives? There are two major use-cases that you might be using Explorer DB for: analytics and real-time queries from web user interfaces. #### Analytics Use-Case This is if you use Explorer DB to build internal or external dashboards. Pagoda has been working with Google Web3 team to enable BigQuery public dataset that has a compatible schema with Explorer DB. :::tip Find more information about our [BigQuery solution here](../2.build/6.data-infrastructure/big-query.md). ::: #### Web or API usage This is if you make queries to Explorer DB in response to API requests that your users make on your application. There are various options that you can explore: 1. If you are working with token balances, including $NEAR, fungible or non-fungible tokens, consider using [Enhanced API](https://www.pagoda.co/enhanced-api) hosted by Pagoda, or run it yourself using https://github.com/near/near-enhanced-api-server and https://github.com/near/near-microindexers 2. Use NEAR QueryAPI – serverless indexers and GraphQL endpoints: https://near.org/s/p?a=nearpavel.near&b=97029570 3. Use NEAR Lake Indexer. Create an indexer using [Rust](https://github.com/near/near-lake-framework-rs), [JavaScript](https://github.com/near/near-lake-framework-js). There are other languages supported by community, [try this search](https://github.com/search?q=near-lake-framework&type=repositories). 4. Consider other indexer solutions built by the community ### Can I still continue using Explorer Database? No, you won’t be able to continue using Public Explorer Database after the sunset. However you can start your own instance of https://github.com/near/near-indexer-for-explorer and reindex the history from scratch or use a latest backup. We will share a backup of Explorer DB in September if you want to run your own instance. To run your own infra, you will need: * **Indexer services:** We use two e2-medium instances on GCP for redundancy, with 2 vCPUs and 4GB of RAM. * **A database:** We use Postgres version 11, with 8+ vCPUs, 52GB+ RAM and ~8TB of SSD storage. In addition, we recommend running an extra read-replica on a similar or more powerful machine.
NEAR Community Update: Nov 29, 2018 COMMUNITY November 29, 2018 It’s official: as promised, we’re now open source. As Illia announced in the accompanying post, this is the first milestone on the path to TestNet and it’s intended to help us build a more engaged early developer community. This early community is important because they will help us fulfill our commitment to creating the most developer-friendly toolset out there. Speaking of community, the ball is officially rolling on our in-person community here in SF and it’s going to pick up speed quickly. Speaking and Events We’ve focused primarily on building out our local event series which addresses not just developers but a broad ecosystem of designers, product people and startuppers too. Recent Highlights We kicked off our cross-disciplinary San Francisco Meetup group with a look at the state of the ecosystem. Expecting the recording shortly. We attended a sharding panel with the Stanford Blockchain Club on Nov 28th alongside OmniLedger. Upcoming Events [SF] Dec 5: Blockchain 101 Onramp: Start Here! Deconstructing the Blockchain Ecosystem [SF] Dec 12: Improving Blockchain Developer Experience: When UX Meets Developer Tools Writing and Content Aliaksandr Hudzilin started a series on the promise of blockchain in the music industry Engineering Highlights I’ve already provided the lead on engineering highlights — we officially open-sourced our core client repos, including: The NEAR Studio web IDE, which allows you to play with writing contracts using TypeScript in a web window. The interface is still preliminary. NEARCore repo including the local DevNet code. This is in the context of the following upcoming milestones: DevNet: Finish building out the developer experience for our blockchain. We are progressing on this milestone pretty well, but there is still more work to be done. “Minimum Viable Blockchain” (MVB): a fully functioning blockchain that can provide a platform for running experiments on governance, economics and user experience. This version will only have a Beacon Chain consensus. Shard Chains: Add sharding of state and processing to MVB. How You Can Get Involved If you want to stay up to date with what we build at NEAR, use the following channels: Twitter — https://twitter.com/nearprotocol, Discord — https://discord.gg/kRY6AFp, we have open conversations on tech, governance and economics of blockchain on our discord. https://upscri.be/633436/
Near at ETHDenver Highlights NEAR FOUNDATION March 2, 2023 Near will see a number of partnership and project announcements at Near Day and ETHDenver. Over a 1,000 people are attending Near Day, with many more visiting the Near booth and dropping in on ETHDenver talks and panels featuring Near ecosystem figures. Beyond the many engaging talks and projects demos, there was also an ecosystem party, side events, a hackathon, and much more. Let’s take a quick look at a few of the latest announcements from Near at ETHDenver. A number of other announcements will be rolling out over the course of Near Day and ETHDenver, so stay tuned for those below in the coming days. Few and Far raises $10.5 million in funding Few and Far, a leading Digital Collectibles web3 platform, announced today that it has raised $10.5 million in a funding round led by Pantera Capital, the leading blockchain investment firm.The raise marks a significant milestone for Few and Far, which has been experiencing exponential growth since launch. The new funds will help expand the platform’s capabilities, enhance user experience, and increase the number of Web3 developers. IP owners also stand to benefit from the platform. Few and Far features an all-inclusive platform available to carry out everything related to next generation digital collectibles, including a suite of developer tools. The round also included top VCs, Cypher Capital, Huobi Ventures, Hypersphere, Metaweb, Mantis Partners, K5 Global and many more. Near Blockchain Operating System now live on Alpha.Near.Org Read the full Near Blockchain Operating System announcement here For Near Day on March 2nd, Near launched alpha.nearpages.wpengine.com — a composable frontend for Web3. It will allow end users to easily and frictionlessly discover all of Web3’s possibilities in one seamless experience. It will also empower developers to create and code interfaces in a single environment with the ability to fork a host of components to build apps faster and more efficiently than ever before. Anyone in the Open Web ecosystem can create their own frontends (i.e., their own versions of alpha.nearpages.wpengine.com), compatible with the blockchain of their choice. This means that builders from any ecosystem can create components in just a few lines of code, and take advantage of fast onboarding to help make new and custom Web3 experiences. This is an industry first. With the addition of composable frontends to the tech stack, Near now becomes the Blockchain Operating System, allowing seamless, one-time onboarding and removing friction points like making accounts for every experience, while supercharging development from a collection of over 1,800 components. Alpha.nearpages.wpengine.com is the first step in Near’s Blockchain Operating System journey. It’s the Alpha version, where builders can see the frontend come to life. Try out the Alpha at alpha.nearpages.wpengine.com to experience the world’s first Blockchain Operating System — a revolutionary moment in Web3. If you’re a developer, see how easy it is to fork components and create new experiences. If you’re an end user, see how easy it is to explore Web3 experiences, social, and news all in one place. The Blockchain Operating System is Near and it’s here. #NearistheBOS Flow Carbon announces carbon-market ecosystem built on Near Near and Flowcarbon, the pioneering climate technology company, announced the launch of a carbon-market ecosystem that will enable carbon credits to be traded on the Near network through Flowcarbon’s tokenized carbon credits. With this collaboration, Near will realize its vision of becoming a carbon-negative blockchain. As part of this partnership, Near plans to offset its carbon footprint through Flowcarbon. Flow Carbon’s carbon credit token will be launched on both Near and Aurora, an Ethereum Virtual Machine (EVM) built on Near. Validators will be set up for the purpose of offsetting, and large Near holders will be able to stake with these validators. Designed to make carbon offsetting more accessible and transparent, this partnership will help Near become carbon-negative, solidifying Near’s position as one of the top players in Regenerative Finance (ReFi). With Stacksports, parents and athletes can mint royalty-free NFTs StackNFT is teaming up with Near to offer an NFT platform that allows youth athletes of all ages and skill levels to create and capture their favorite sports memories digitally. Youth sports parents and athletes can now mint royalty-free NFTs effortlessly, without any advanced knowledge of the minting or wallet creation process. Just upload, decorate, and mint. Parents and athletes can also mint NFTs knowing that Near is a carbon-neutral, environmentally friendly blockchain, which supports several forest protection and restoration projects. StackNFT is owned and operated by Stack Sports, a global technology leader in SaaS platform offerings for the sports industry, with nearly 50 million users in 35 countries. From little league to the pros, Stack Sports powers the many moments that create the story of your journey through sports. Calimero’s private shard infrastructure now live on Near Calimero.network, a secure private shard infrastructure provider announced that after several months running in a stealth mode, during which it was tested by beta testers and partners, is ready to serve customers with unique blockchain power and a Web2 interface. With roots in the Near Protocol, Calimero is a high performance blockchain that launched on mainnet in 2020. Founded by Sandi Fatic and Mario Halambek, two of the first infrastructure engineers at Near, Calimero allows projects to launch their own shard in a matter of minutes. In launching a private shard, users can be certain of the network’s performance and security, which is managed by Calimero itself. Calimero is targeting so-called “Web2.5”, seeking a way to connect Web3 and Web2 worlds. For Web3 startups, Calimero provides a unique way to scale their products and leverage the privacy features, giving access to target Enterprise customers and getting access to new audiences. For classic Enterprises, Calimero offers a way to build new products and onboard chosen Web3 mechanics to find new areas to grow their businesses with growth rates compared to DeFi and NFT markets. With the cheapest option starting from less than $300, Calimero provides a flexible model to maximize the cost efficiency by adjusting shard performance according to the load. Calimero also offers a 14-day grace period to test out the platform for startups who are in the very beginning of their journey. Calimero.network is a London-based startup that has recently raised an investment round of $8.5M, co-led by Khosla Ventures, Lyrik Ventures, and Near foundation. Near Foundation Council updates Near Foundation announced that Mona El Isa, a founding council member at Near Foundation Council (NFC), has been appointed as Chair. Marieke Flament, CEO of Near Foundation, has joined as a council member, and will govern alongside existing members Richard Muirhead, Chairman and Managing Partner at Fabric Ventures, and Jason Warner, Managing Director at Redpoint Ventures as well as Sheila Warren advisor to Near Foundation and CEO of the Crypto Council for Innovation. Mona takes the place of Illia Polosukhin, co-founder of Near Protocol and CEO of Pagoda (formerly Near Inc.), who has stepped down as Chair and member of the Near Foundation Council (NFC) to focus on Web3 ecosystem development and participation. “It was an honor to serve as Chair and Council Member of the NEAR Foundation Council over the past two years,” said Illia Polosukhin. “I’m stepping down in order to focus fully on the development of products and technology at Pagoda, which is critical to the continuing success of the NEAR Ecosystem.” “I will continue to be involved with NFC in my capacity as Pagoda CEO,” he added. “From a governance perspective, my departure increases the council’s independence and further decentralizes leadership and decision-making in the NEAR Ecosystem. I welcome Mona’s appointment as the new Chair and Marieke’s as council member to continue steering the Foundation in its mission of supporting NEAR’s growth.”
NEAR Q4 Protocol Roadmap Update DEVELOPERS January 12, 2024 By Bowen Wang, Director of Protocol In this post, the NEAR Protocol work group would like to provide an update of the protocol roadmap to show what we accomplished in 2023 and what is planned for 2024. TLDR: 2023 saw major experience improvements via meta transactions and zero-balance accounts, as well as node performance improvements and optimizations. Preparations are underway for a major upgrade to stateless validation, completing Phase 2 of the sharding roadmap in early 2024. What we accomplished in 2023 There were a total of six protocol upgrades in 2023 which introduced a number of new protocol features. Meta transactions were added as a protocol feature at the beginning of the year to support gasless transactions, which means that users can transact on NEAR and start using apps without necessarily needing to pay transaction fees in NEAR. We also added zero-balance accounts, an important feature that enables users to create an account without holding NEAR to pay for storage. This makes it easy to onboard new users to applications. These two features form a solid foundation for a seamless onboarding experience for end users — a top goal for NEAR overall. In addition to easy user onboarding, we have also been working hard to optimize the performance of NEAR. Flat storage, which was released in Q2 this year, optimized state reads and improved the stability and performance of the network overall. Another feature that optimizes NEAR nodes is cold storage, which allows for a split between hot and cold storage for a node. This means an archival node does not need to store most of the historical data on SSD and therefore can save a lot on cost. We also optimized the network communication between validator nodes by introducing the tier1 network, which reduces the latency of network messages between two validator nodes. Furthermore, we improved state sync and reduced the time it took a node to synchronize the latest state. We have also worked on improving the stability and maintainability of contract runtime with initiatives like finite wasm and limited replayability. There are a few major initiatives that we started this year and expect to finish next year, such as stateless validation, congestion control, and transaction priority. We will dive deeper into those in the section below. Plans for 2024 There are a few major projects that we want to deliver in 2024 to improve the usability, scalability, and decentralization of NEAR Protocol: Stateless validation. Stateless validation is a major initiative that we have been working on for a few months. It adjusts the original Nightshade sharding design to avoid implementing fraud proofs while improving the performance of each shard significantly by putting state in memory. The stateless validation work is expected to be delivered in Q2 2024, which would also mark the completion of the original goal we set for Phase 2 of sharding. We expect the launch of stateless validation to also dramatically increase the throughput of each shard and prepare NEAR for the continued growth of usage. Congestion control and transaction priority. While NEAR’s sharding design is horizontally scalable, it is important to provide a good user experience when there is short-term congestion on the network. This includes localizing congestion so that gas price increase does not affect the entire network and allowing users to prioritize their transactions during congestion if they are willing to pay more in transaction fees. Support for account aggregation. Account aggregation allows a user to control accounts on different chains with one NEAR account, an important pillar of the chain abstraction vision for NEAR. It requires chain signatures, which does MPC to sign payload. This requires a new runtime API to facilitate the asynchronous nature of chain signatures. zkWASM. We have been working on zkWASM with the Polygon team for a few months and the work will continue in 2024. The goal is to build a prover for WebAssembly smart contracts. This could be used as a part of the initiative to prove the state transition of NEAR in a ZK proof. Moreover, zkWASM also provides wasm as an alternative execution environment to EVM for L2s. Data availability improvements. We launched NEAR DA in early November 2023 and there are a few things that we plan to work on to further improve the efficiency of NEAR DA. Those improvements include introducing KZG commitment to avoid having data availability fraud proofs, as well as real-time bridging to allow verification of data availability on Ethereum. Ethereum wallet support. Supporting wallets like MetaMask natively on NEAR allows us to attract more users to NEAR and also be more Ethereum aligned. This requires changes to the protocol to support Ethereum addresses natively and support processing of RLP serialized Ethereum transactions. Research into the future of sharding. There are two major directions of exploration: synchronous sharding and ZK-centric sharding. Synchronous sharding enables synchronous execution of smart contracts and addresses the developer experience pain point of having to deal with asynchronous execution. ZK-centric sharding leverages zero-knowledge proofs to validate state transition of different shards and improves the scalability and decentralization of the protocol. In addition, we will also research the next and final phase of sharding: dynamically adjusting the number of shards based on usage. The roadmap can be seen below for those interested in more timeline specifics. It is split into two parts: Experience and Core. The Experience section encompasses user and/or developer experience and the protocol features needed to enable those experiences. As an example, synchronous execution addresses the pain point that developers feel when they implement cross-contract calls. The Core section, on the other hand, covers major efforts to improve the scalability and decentralization of the protocol. This includes stateless validation, zkWASM, improvements to data availability, and so on. As always, the protocol team is proud to have made several important improvements to the core protocol with zero disruption for users and developers. We look forward to making some major advancements in 2024 to help the entire NEAR ecosystem deliver its vision of mainstream adoption of an Open Web, where all internet users can control their own data, assets, and power of governance. We will share more details on Phase 2 advancements and timelines soon. If you’d like to learn more, join the NEAR Protocol X Spaces on Tuesday, January 16 at 5pm UTC to hear from Director of Protocol Bowen Wang and NEAR Foundation CEO Illia Polosukhin on upcoming protocol developments.
--- id: debug-pages title: Debug Pages sidebar_label: Debug Pages description: Debug Pages --- # Debug Pages Debug pages is a feature that allows node maintainers to navigate detailed information about the node in a structured way ## Enable Debug Pages To enable debug pages modify your config.json file and restart the node. ``` ... "rpc": { ... "enable_debug_rpc": true, ... } ... ``` By default, debug pages will become accessible on `<your node ip>:3030/debug`. If you modified your rpc address in config, then debug page will be accessible on `<config.rpc.addr>/debug`. ## Last blocks page Displays 50 most recent blocks. Shows hash, as well as time and gas stats for block and every shard. On the left schematically displays the chain to visualize forks. ## Network info page Displays a table of peers. For every peer shows: - some sync information like height and last block hash; - id information like validator pool name (if peer is a validator), peer id; - network information like address, traffic, route; - node information like archival flag and tracked shards. ## TIER1 Network info page Similar to network page, but about TIER1 network. ## Epoch info page Displays several tables related to epochs: - Start height and epoch hash for last 4 epochs, current epoch and next epoch; - Validators in the current epoch; - Validators in the next epoch; - Validator proposals; - Validator kickouts; - Validator type for current validators in 6 epochs described on the page. Whether the validator is a block producer or a chunk-only producer; - Shard sizes for 5 out of 6 epochs described on the page (because one of them didn't start yet). ## Chain & Chunk info page Displays information about chunks requested and received by the node ## Sync info page Displays a page with tracked shards for this epoch and the next epoch. Also shows status of three sync algorithms that are executed sequentially if the node is behind: - Header sync - State sync - Block sync ## Validator info page Displays information related to blocks and chunks produced by the node and approvals or skips sent by other nodes. ## Client Config page Displays client config JSON of the node.
Blockchain Promise for Music Industry (Industry Background) CASE STUDIES November 15, 2018 What will blockchain enable in the long term? From my subjective point of view, blockchain has the potential to re-imagine many industries in the same way that the Internet has been reshaping almost every industry for the past 25 years. Today, we are on day #1 of the blockchain paradigm shift. Adoption is almost non-existent. In my view, it’s likely that we are living through the same tech adoption phase as Internet adoption circa the early 1990s. Future mainstream use cases are hard to predict, just as nobody in the early 1990s assumed that broadband would become cheap enough to enable movie streaming, a.k.a., Netflix. Despite the uncertainties, I want to walk through a number of industries which could be re-imagined with the blockchain long term. This blog post will cover music industry dynamics, and what we might see emerging with blockchain. To keep the article relatively short, I embedded multiple links that provide much more detailed industry background. Blog Post Summary: Music industry over time evolved into an industry that has a middleman in music label, with three players earning the majority of revenue: UMG, Sony Music, WMG. Music Labels make astonishing ~$800,000 per employee in revenue, while musicians are making on average below $40,000 per year. Music labels historically covered two functions: music production and distribution. The cost of music production and distribution decreased significantly over time, while the music discovery became the most challenging hurdle for musicians wanting to build the listener audience. Digital music distributors, such as Napster, iTunes, Pandora, and Spotify over time offered new ways to distribute and discover music, slowly transitioning the power away from labels to music distributors, although with limited success. Blockchain technology can enable several advantages, for both music listeners and musicians. Music listeners will use blockchain to store digital rights to music and thus have the ability to port their owned content to various service providers (i.e. Spotify, Amazon, etc.). Because music song licenses will be stored in an immutable public ledger, it will become possible to exercise end-user rights, i.e. listen to owned music across platforms. Musicians will be able to raise funds directly from early listeners by giving out song tokens in exchange for fiat money, thus bypassing music label. In addition to capital, it will create incentives for bootstrapping early audience. Since the supply of song tokens will be limited, early token holders will be interested in spreading the word about the band. Tokenization will create market liquidity which is beneficial for creators and supporters and shifts the value away from the current middleman. Now, let’s dive into this in more detail. The rise of the middleman Over time, the music industry has consolidated power around organizations providing funding, publishing, and network for musicians: music labels. We will skip going into many aspects of the music industry history, and use this section to show how music distributors paid various royalties to music labels relative to how much power music labels had throughout the various eras. In the 1930s, the music labels didn’t have enough centralized power to exert influence, and the music distributors of that era (terrestrial radio) didn’t need to pay royalties to the music label. They only needed to pay royalties to musicians and writers instead. In other words, the music industry had a fairly decentralized value chain. The 1970s and 1980s saw the creation of six major record labels, known as the Big Six: Warner Music, EMI, Sony Music, BMG, Universal, and Polygram. As a result, by the 1990s, when satellite radio became a mainstream way to distribute music, the royalties required to be paid out included the royalties to publishers, in addition to royalties to writers and musicians. SiriusXM pays something around 15.5% of its revenue in royalties (source). In contrast to 1930, music labels started to consolidate power, and, as a result, started to collect large payouts. To further exacerbate the situation, the music label industry saw further consolidation: Polygram merged with Universal, Sony merged with BMG, leading to a situation where the majority of the power is controlled by three major corporate labels: the French-owned Universal Music Group, the Japanese-owned Sony Music Entertainment, and the US-owned Warner Music Group (revenue data). Fast forward to 2000, the year Pandora started. As a consequence of power organized essentially in three hands (UMG, Sony Music, WMG), Pandora was required to pay different kinds of royalties, vastly different from terrestrial radio broadcasters and from satellite radio. Digital Performance Right in Sound Recordings Act (DPRA) was enacted by Congress in 1996 and later appended by the Digital Millennium Copyright Act (DMCA) in 1998. It included new categories of licensees, which then led to a new entrant, such as Pandora, to comply under a completely different set of royalties. As a result, Pandora was forced to pay for streams on “pay-for-play” basis, which is eating up to 50% of Pandora revenue. As a result, Pandora became a poster child for music business fight over royalties (more on this here). In conclusion, we observed the ways the royalty payouts changed due to relative power dynamics of the industry in every era: relatively distributed model with terrestrial radios in the 1930s, more centralized payout model with satellite radio in 1990s, and completely centralized value chain in which Pandora operated. Music industry value chain fairness is covered in a lot more detail here. Economics of Major Label & Musician’s Options Now that we’ve briefly covered the industry evolution through the prism of royalty payouts to music labels, let’s take a look at one of the major labels, Warner Music. Warner Music made ~$3.6 billion in revenue in 2017 and employed ~4,500 people in its organization. That’s on average ~$800,000 in revenue per employee. For comparison, Warner Music’s revenue per employee is 16x higher than McDonald’s revenue per employee (source). On other hand, musicians on average make $39,328 per year (data). As a musician, you can work with a major label, work with independent labels, or go DIY. Under the major label model, you will significantly reduce your fraction of payouts, but at the same time de-risk your success by outsourcing the high-quality production and distribution (network) to a reputable label. You will get money for video production, studio recording, and touring support, in addition to an up-front cash advance. By going with indie label, you will get a smaller cash infusion, and the music distribution might end up being outsourced to larger labels since indies don’t have as much staff working for them. As DIY musician, you will hope to build an organic music base via using social media, Spotify and YouTube. There are also emerging services, such as Bandcamp and Patreon. You can post your recording on Spotify, and Spotify will pay you anywhere from $0.006 to $0.0084 per stream (data). That’s $6 for every thousand listens, or $6,000 for every million listens. Decreasing Music Production Cost & Challenges of Music Discovery Over the years, the cost of music production decreased significantly: you can record an album with just $10,000, even though it took ~$2M to record albums, such as Rolling Stones’s “Exile on Main Street” some 40 years ago (data). Prior to digital music and digital content purchasing, the choice was limited by shelf space, whereas Internet expanded the choice, thus making the discovery of music a challenge. In this regard, digital content presents challenges for the musician looking to get discovered. On one hand, you can use essentially free global distribution. On another hand, so can everyone else, making it close to impossible to be uncovered. As a musician now, you need to get exposure via ads and concert tours. Through these two types of exposures, you will get discovered and build followers in the long term. The problem is that both approaches aren’t sustainable. Ads aren’t cheap with Google and Facebook controlling the publishing business. Touring across the country has its own middleman since Ticketmaster merged with LiveNation with a combined entity representing a choke point on live music space (more on this here). In conclusion, even though the cost of music production went down substantially, music discovery presents many challenges in a world of abundant content. As a result, it becomes extremely hard for a musician to stand out and sustain their living as a musician. Digital Music Distribution Models Napster was a first striking example of being able to download music in a peer-to-peer manner and discover music via the platform. Some 80M users were blocked from using it as a result of music publishing industry shutting down the website (source). iTunes was born out of Napster’s ashes when Steve Jobs saw the demand for music downloads (more on backstory is written here). iTunes was able to unbundle the CD concept, allowing consumers to purchase a single song for 99 cents. Music labels at the time needed to counteract the problem of piracy of downloaded music, and iTunes presented a way to legalize some of the downloads. Then the consumer trend evolved from digital content downloads into streaming. In 2008, Spotify launched and focused on an emerging trend: the ability to stream music instead of downloading it. Spotify was forced to pay much higher royalties than even mentioned above Pandora, but new consumer behavior (streaming) took off. Spotify has its own long-term challenges. Without building original content, Spotify is merely passing through content and giving large royalties (~70%) to content publishers. In order to move the power away from music labels, Spotify needed to do what Netflix did, aggressively move into original content, to be able to dictate the terms when it comes to sitting down at the negotiation table with labels. It’s an open question whether the power will shift to music distributor, or whether the value will continue flowing to owners of the music catalog. Additionally, a consortium of digital music (YouTube, Apple, Spotify) distributors is also proposing new blanketed licenses which might change the power dynamics a bit, but this is out of the scope of the current article. More detail can be found here. Blockchain As a Tool for Capital Formation and Incentive for Music Distribution The introduction of tokens can change the existing model. The middleman could be decentralized by using token incentives. There are multiple ways for how tokens can be used for that. The role of capital formation will be replaced from a music label to music listeners. The general idea is to get access to liquidity pools from selling tokens, thus replacing the music label with music fans as the main source of capital for the band. The music will still have a fiat price associated with songs, but the bands will be able to exchange limited supply of song tokens to early listener base, who now will be incentivized to spread the word about the music. Similar to how Spotify used the capital to purchase content to bootstrap marketplace, crypto incentives will draw people and allow for new content creation. Over time, more users will switch to distributed platforms giving it more leverage, weakening the original middleman. Blockchain as a System of Record for Digital Rights Management From the listener perspective, the powerful use case for blockchain is to use an immutable distributed ledger to keep the records of ownership. This will allow end users to use services like Amazon Music, iTunes, and Spotify interchangeably because now you will be able to verify ownership of the music asset without needing to keep it on a single platform. In effect, there is an opportunity for Napster 2.0: fully legal this time. We will cover this use case in detail in the next blog post on the music industry. Early Startup Examples There are a number of early startups tackling the space from various angles. For instance, Tune Token and Ujo Music focus on digital songwriter rights and royalty transparency, while SingularDTV focuses on music peer-to-peer fundraising and decentralized distribution. Finally, Vibrate focuses squarely on music discovery. — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — If you want to stay up to date with what we build at Near, use the following channels: Twitter — https://twitter.com/nearprotocol, Discord — https://discord.gg/kRY6AFp, we have open conversations on tech, governance and economics of blockchain on our discord. Our recently launched research forum — http://research.nearprotocol.com/ https://upscri.be/633436/
--- description: Everything you need to know about NEAR Token title: NEAR Token sidebar_position: 0 --- --- This is the native token used in NEAR Protocol. It has multiple use cases: - Secures the network through staking - Provides a unit of account - NEAR is used for processing transactions and storing data - Serves as a medium of exchange ### Securing the Network NEAR Protocol is a proof-of-stake (PoS) network, which means that resistance from various attacks comes from staking NEAR. Staked NEAR represents the decentralized infrastructure of servers that maintain the network and process transactions for applications and users on NEAR. Rewards for providing this service are received in NEAR. ## Providing a Unit of Account NEAR is used to price computation and storage on the NEAR infrastructure. The network charges transaction fees in NEAR to process changes and transactions. ## Medium of Exchange NEAR is readily available on the protocol level, so it can be used to transfer value between NEAR applications and accounts. This means that applications can use NEAR to charge for various functions, like access to data or other complex transactions. Entities can also easily exchange NEAR between each other, without the need for trusted third parties to clear and settle transactions. For a deeper dive on NEAR Economics: [https://near.org/blog/near-protocol-economics](https://near.org/blog/near-protocol-economics) For more information about the NEAR token, visit [NEAR Token Supply and Distribution](https://near.org/blog/near-token-supply-and-distribution/) or [Nomicon](https://nomicon.io).
--- NEP: 514 Title: Reducing the number of Block Producer Seats in `testnet` Authors: Nikolay Kurtov <nikolay.kurtov@near.org> Status: New DiscussionsTo: https://github.com/nearprotocol/neps/pull/514 Type: Protocol Version: 1.0.0 Created: 2023-10-25 LastUpdated: 2023-10-25 --- ## Summary This proposal aims to adjust the number of block producer seats on `testnet` in order to ensure a positive number of chunk-only producers present in `testnet` at all times. ## Motivation The problem is that important code paths are not exercised in `testnet`. This makes `mainnet` releases more risky than they have to be, and greatly slows down development of features related to chunk-only producers, such as State Sync. That is because `testnet` has fewer validating nodes than the number of block producer seats configured. The number of validating nodes on `testnet` is somewhere in the range of [26, 46], which means that all validating nodes are block producers and none of them are chunk-only producers. [Grafana](https://nearinc.grafana.net/goto/7Kh81P7IR?orgId=1). `testnet` configuration is currently the following: * `"num_block_producer_seats": 100,` * `"num_block_producer_seats_per_shard": [ 100, 100, 100, 100 ],` * `"num_chunk_only_producer_seats": 200,` It's evident that the 100 block producer seats significantly outnumber the validating nodes in `testnet`. An alternative solution to the problem stated above can be the following: 1. Encourage the community to run more `testnet` validating nodes 1. Release owners or developers of features start a lot of validating nodes to 1. ensure `testnet` gets some chunk-only producing nodes. 1. Exercise the unique code paths in a separate chain, a-la `localnet`. Let's consider each of these options. ### More community nodes This would be the ideal perfect situation. More nodes joining will make `testnet` more similar to `mainnet`, which will have various positive effects for protocol developers and dApp developers. However, this option is expensive, because running a validating node costs money, and most community members can't afford spending that amount of money for the good of the network. ### More protocol developer nodes While this option may seem viable, it poses significant financial challenges for protocol development. The associated computational expenses are exorbitantly high, making it an impractical choice for sustainable development. ### Test in separate chains That is the current solution, and it has significant drawbacks: * Separate chains are short-lived and may miss events critical to the unique code paths of chunk-only producers * Separate chains need special attention to be configured in a way that accommodates for chunk-only producers. Most test cases are not concerned about them, and don't exercise the unique code paths. * Separate chains can't process real transaction traffic. The traffic must either be synthetic or "inspired" by real traffic. * Each such test has a significant cost of running multiple nodes, in some cases, tens of nodes. ## Specification The proposal suggests altering the number of block producer seats to ensure that a portion of the `testnet` validating nodes become chunk-only producers. The desired `testnet` configuration is the following: * `"num_block_producer_seats": 20,` * `"num_block_producer_seats_per_shard": [ 20, 20, 20, 20 ],` * `"num_chunk_only_producer_seats": 100,` I suggest to implement the change for all networks that are not `mainnet` and have `use_production_config` in the genesis file. `use_production_config` is a sneaky parameter in `GenesisConfig` that lets protocol upgrades to change network's `GenesisConfig`. I don't have a solid argument for lowering the number of chunk producer seats, but that reflects the reality that we don't expect a lot of nodes joining `testnet`. It also makes it easier to test the case of too many validating nodes willing to join a network. ## Reference Implementation [#9563](https://github.com/near/nearcore/pull/9563) If `use_production_config`, check whether `chain_id` is eligible, then change the configuration as specified above. ## Security Implications The block production in `testnet` becomes more centralized. It's not a new concern as 50% of stake is already owned by nodes operated by the protocol developers. ## Alternatives See above. ## Future possibilities Adjust the number of block and chunk producer seats according to the development of the number of `testnet` validating nodes. ## Consequences ### Positive * Chunk-only production gets tested in `testnet` * Development of State Sync and other features related to chunk-only producers accelerates ### Neutral * `testnet` block production becomes more centralized ### Negative * Any? ### Backwards Compatibility During the protocol upgrade, some nodes will become chunk-only producers. The piece of code that updates `testnet` configuration value will need to be kept in the database in case somebody wants to generate `EpochInfo` compatible with the protocol versions containing the implementation of this NEP. ## Changelog ### 1.0.0 - Initial Version The Protocol Working Group members approved this NEP on Oct 26, 2023. [Zulip link](https://near.zulipchat.com/#narrow/stream/297873-pagoda.2Fnode/topic/How.20to.20test.20a.20chunk-only.20producer.20node.20in.20testnet.3F/near/396090090) #### Benefits See [Consequences](#consequences). #### Concerns See [Consequences](#consequences). ## Copyright Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).
Like, totally random? | August 12, 2019 COMMUNITY August 12, 2019 We’ve been up to a lot recently! Still pushing as hard as we can towards MainNet launch. In the last couple weeks, Alex published a new paper on Randomness, Illia talked to Nervos and Holochain for two new whiteboard series videos (linked below), and Jess and I did a short workshop in preparation for the IDEO+Coinlist hackathon. The hackathon has kicked off! If you’ve got an idea, you’ve got plenty of time to jump aboard here! After a successful round of applications for the Beta Program, we’re announcing the next thing: the NEAR Ambassador Program! If you want to create or support a NEAR Protocol community in your area, check out some info on the program. We’re particularly looking for diverse applicants (age, gender, ethnicity, geography, and more!) so if that is you, please feel encouraged to apply. On top of that, the Beta Program is done taking applications (although if you have an epic team and idea you can still apply late). In engineering, we’ve been battling bugs and kicking out new features based on what you’ve been saying. So keep building and telling us what’s missing. This is what randomness would look like if it were a bunny with a pancake on its head COMMUNITY AND EVENTS We’re heading to Germany for Berlin Blockchain Week, from Aug 18-25. Come say hi if you’re in town! Also, we’re looking for self-starters who want to create community around blockchain in their area. If you’re the type of person who sees themselves as a founder, you should definitely join our ambassador program. We’re allocating tokens to people who want to create a movement. The IDEO hackathon is in progress. Don’t miss out! We’ve kicked off the ambassador program. Set something up in your community! We’re hiring aggressively. If you don’t see anything that fits you, email us! We’ve gotten a ton of great applications for our beta program and have already onboarded our first projects. If you have a late application, it’s still worth sending it in here: https://pages.near.org/beta UPCOMING EVENTS We’ll be involved in a couple of events at Berlin Blockchain Week: Illia will present at a Pantera event on Aug 19th on the Web3 Stack Illia will be on a panel on the Road to Adoption for the decentralized web on August 20th, with Celo and Nexus Mutual Alex will be presenting at the Web3 Summit on sharding Illia will be on a panel on August 22nd for Berlin Blockchain Week ENGINEERING HIGHLIGHTS This is an image of what Chunks would look like if it were a wild cat. He C H O N K Y. Chunks are in a mega-PR; you can take a look here. We’re also polishing staking, and adding features to make building stuff on NEAR faster and better. You can now send money through the command line! Check out the wallet API proposal below as well. If you want to add some features, or have a cool idea don’t forget that everything we do is entirely open source! 71 PRs across 14 repos by 16 authors. Featured repos: nearcore, nearlib, near-shell, and near-wallet Here are the highlights of what’s been added in the last two weeks: Enabled sending telemetry data over HTTPS in near core Updated testnet genesis in core Near shell updated to 0.9.4 Improve error handling for login in near shell Display transactions per second (tps) and max tps in explorer New enhancement proposal for Wallet API Validator rewards implemented and merged in core Kickouts added to validator manager and account deletion added to core New calls added for sending money through the command line New testing pipeline in CI added to the online IDE Block search added and major performance boost to block explorer WRITING AND CONTENT We’ve released a paper and a post on randomness. When Illia was in China recently, he had a chance to sneak into a room with a whiteboard and break down Nervos with Haichao Zhu. Later, Eric Harris-Braun from Holochain came by our office and explore the concepts behind DHT. Check out the links below! Alex’s post on Randomness The formal paper on Randomness The new Whiteboard Series Episode 25 with Nervos here. (There were some technical difficulties, but it’s still comprehensible) The new Whiteboard Series Episode 26 with Holochain here Workshop for IDEO + Coinlist on getting set up quickly for the hackathon 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. Reminder: you can help out significantly by adding your thoughts in our 2-minute Developer Survey. https://upscri.be/633436/
NEAR at Collision: Start Your BOS Journey and Expand into the Open Web NEAR FOUNDATION June 27, 2023 Collision is here. Today, June 26th through the 29th in Toronto, Ontario, NEAR experts will be on hand at Collision to showcase how brands and companies can make a move into the Open Web with NEAR’s Blockchain Operating System (BOS). The BOS redefines the Web2-to-Web3 experience. Now anyone can effortlessly create and distribute decentralized applications, using any blockchain — all in one browser. Don’t miss NEAR Horizon, NEAR Foundation’s new Web3 startup support platform, which will also be at Collision. If you’re a founder or developer, then you will definitely want to meet with the Horizon team to get started on the Web3 funding and building journey. Here is what to expect from NEAR at Collision 2023. NEAR Speaker Sessions you won’t want to miss Tuesday, Jun 27, 12:00 – 12:45 PM Location: Beanfield Centre, Masterclass 1 Masterclass: “The Fastest Way to Add Web3 to Your App” NEAR is transforming Web3 for developers, enterprises, and users alike with the Blockchain Operating System (BOS) – a common layer for browsing and discovering open web experiences compatible with any blockchain. NEAR founder Illia Polosukhin shows how the fastest onboarding in Web3 combined with decentralized frontends and embedded social features can help Web2 brands and Web3 projects deliver new & easy experiences and grow their communities. Speaker: Illia Polosukhin, NEAR Protocol, Co-founder Tuesday, Jun 27, 2:10 – 2:35 PM Location: Enercare Centre, MoneyConf Fireside Chat: “At the intersection of AI and Web3” Speakers: lllia Polosukhin, Near Protocol, Co-founder Elad Gil, Investor Moderator: Lucinda Shen, Axios, Fintech Reporter Wednesday, Jun 28, 01:30 – 02:15 PM Location: Beanfield Centre, Masterclass 4 Masterclass: “How to Decentralize Any Frontend Using BOS” Learn how to store your frontend codebase entirely on-chain and make it more accessible to users with NEAR’s Blockchain Operating System (BOS). Speaker: Miao Jiang, Head of Product, Proximity Labs Wednesday, Jun 28, 02:30 – 03:15 PM Location: Beanfield Centre, Masterclass 4 Panel: “Charting the Course for a Thriving Web3 Ecosystem” Delve into the current state of web3 investing, identify the crucial elements for building a thriving web3 ecosystem, and explore innovative strategies for scaling startup support platforms. Speakers: Joyce Yang, Founder, Global Coin Research Steven Chien, Founder, Press Start Capital Paul Hsu, Co-founder, Decasonic Moderator: Laura Cunningham, General Manager, NEAR Foundation Thursday, Jun 29, 12:23 – 12:27 PM Location: Enercare Centre, Growth Summit Keynote: “Solving the Blockchain Enterprise Dilemma” Speaker: Sandi Fatic, Co-founder, CEO, Calimero Network Events from the NEAR Community June 27, 6-9 PM – NEAR Horizon Pitch & Networking | Collision 2023 The NEAR Horizon team is partnering with VCs and Funding Teams from around the world who are looking to back exceptional entrepreneurs for the long term to build the future of Web3. June 28, 10 AM-8 PM – Web3 Day (& Night) | Collision Conference Toronto An invite-only event for the Web3 community & Web3 curious during the Collision conference in Toronto. Panels, speakers, networking, art, music, food & drinks, pitch opportunities, and more. June 29, 6-9 PM – NEAR Toronto Launch Party An exhilarating event that marks the launch of the NEAR Toronto Regional Community and concludes the three-day Collision Conference. Stay tuned to Near.org/collision for the latest event updates.
Detailed overview of Ethereum 2.0 shard chains: Committees, Proposers and Attesters DEVELOPERS October 21, 2018 Many details of how Ethereum 2.0 will work are available today, and multiple teams are already working on implementations of it. One large component for which neither spec nor any detailed info is available today is the shard chains. Ultimately the spec will appear here, but in the meantime I will provide a detailed overview in this blog post. Footnote: an earlier version of this write-up was describing a now obsolete version of Ethereum’s approach called IMD (immediate message driven). That version can be found here. Committees and their formation Any participant of Ethereum network can become a validator, for which it is sufficient to stake 32 ETH into a dedicated smart contract on the existing Proof-of-Work chain. Image by Hsiao-Wei Wang Once a participant is in a validator pool, they can be assigned to a certain shard. The assignment is completely random, and leverages a smart usage of Verifiable Delay Functions (VDFs) to achieve unbiased randomness. If one stakes significantly more than 32 ETH (say 320 ETH), they get proportional number of validator seats. Those seats are in no way connected to each other, in particular each of them is assigned to a shard independently, and thus in the worst case a participant that staked 320 ETH could at any single moment be a validator in 10 shards. Not doing so would increase the likelihood of an adversary overtaking a shard, and there’s an expectation that higher stakes generally mean access to more resources, and thus more compute power. Block production in a proof-of-stake system Ethereum 2.0 is a proof-of-stake system. In this section I will review a general framework of how blocks are created in many existing and proposed proof-of-stake blockchains: In such a framework, blocks are produced at a regular schedule, say once every 5 seconds. There’s a set of validators that produce and validate blocks. For each 5 seconds time slot one validator is assigned who is expected to produce a block at that time slot. If validators have non-equal stakes, validators with larger stakes generally have more time slots in which they propose blocks. When forks appear, the selected chain that an honest validator is expected to build upon is the one that has the most blocks in it. For as long as the honest members control more than half of all the validators, it is expected that reversing a large chain of blocks is very hard. Even if the entirety of the dishonest minority intentionally chooses not to produce blocks during their time slots on the honest chain, and concurrently secretly builds a fork chain, their chain is expected to be shorter than the honest chain, an argument similar to that in proof-of-work systems, for as long as more than half of the hash power is controlled by honest participants, the probability of reversing a long tail of blocks is very unlikely. However, such framework, if implemented naively, has a multitude of issues. First, short term forks are still very possible. If the minority controls just 10% of all the validators, the probability of reversing even the last say 6 blocks becomes prohibitively high. Second, all sorts of censoring problems arise. For example, if dishonest participants happen to have two slots in a row, they can censor the block in the slot immediately preceding theirs: On the figure above dishonest validators control time slots 3 and 4. They intentionally produce their blocks on top of the block from time slot 1, effectively censoring the block in time slot 2. The honest validator in slot 5 will choose the longer chain that 3 and 4 have built when produce their block. A single dishonest validator can also attempt to censor the block from the previous time slot. Consider the following figure. The X-axis is time, with time slots for each validator labeled at the bottom. The number on each block is the slot at which the block was expected to be published. Honest validators assigned to slots 0 and 2 have published their blocks in time, but the dishonest validator assigned to slot 1 delayed their block and only published it after the block for time slot 2 was published (thus the validator in time slot 2 was not aware of the block and built their block on top of block in time slot 0): What block shall honest validator at slot 3 built upon? Consider 4 possible rules: Always build on the block from the earlier slot. This way a dishonest validator in the earlier slot can delay publishing their block until the validator from the latter slot published theirs, effectively censoring them (exactly the scenario depicted above); Always build on the block from the later slot. This way a dishonest validator in slot X can choose to ignore the block published for slot X-1, and be certain the validator in slot X+1 will choose their block, effectively censoring the block in X-1; Always build on the block that was received earlier. This way either of the above scenarios are possible if the dishonest validator has better network connection to the validator in the next slot; Choose the block randomly. This way dishonest validators can never censor with certainty (unless they have multiple slots in a row), but if censoring has higher value for them than the block reward, can still naturally attempt to censor and have a 50% chance of succeeding. All of the above scenarios are undesirable. BFT approaches A family of proposals that address the issues above use some sort of a BFT consensus algorithm on each block among the validators. One of the earliest papers suggesting such approach is ByzCoin, but a multitude of other protocols were built upon this idea since then. The main property of such protocols is that once a block was finalized by the committee, for as long as dishonest participants control less than ⅓ of the validators, the block is irreversible, so neither forking nor censoring is possible. Two major disadvantages are then a) most of the existing BFT algorithms are very slow, and were not designed for a large set of participants trying to reach the consensus, and b) being offline is considered to be adversarial behavior, and thus if less than ⅔ of participants are online, the consensus on the blocks cannot be reached, and the system, at least for some time, stalls. Attestations Ethereum 2.0 instead uses the former approach, each time slot having a particular validator who is assigned to create a block at that time slot. Such a validator is called a proposer. However, Ethereum 2.0 extends the approach by encouraging each other validator in the committee to “attest” to the block by signing it. The signatures are accumulated using BLS signatures aggregation, which prevents the block size from exploding with the number of attesters. Moreover, if for a given slot a validator didn’t see the block being produced, or the block was produced on a chain that the validator doesn’t see as the current chain, the validator is encouraged to attest to a so-called “skip-block”. This way an honest validator is expected to attest to exactly one block each time slot, either the actual block produced by a proposer, or a “skip-block”. By using attesters and a smart fork choice rule Ethereum 2.0 shard chains manage to avoid most of the issues of both vanilla PoS approach and the family of BFT consensus algorithms. Fork choice rule To get the selected chain, one starts at the genesis block, and at each step if there’s a fork chooses the block that has the most unique attesters attesting to either that block, or any block in that block’s branch (with a caveat described below in section Latest Message Driven). Consider the example above. Letters in each block indicate the names of the attesters on the block. The dashed blocks are skip-blocks. There’s a fork early on, and Alice (A), Bob (B), Carol (C), Dave (D), Elaine (E) have attested to some blocks in the lower branch, while Victor (V), Xavier (X), Yasmine (Y) and Zach (Z) have attested to some blocks in the upper branch. To find out the selected chain, one starts at the genesis block (slot 1) and moves to the right. At the block in slot 2 the participant has to choose between the upper branch and the lower branch. The fork choice says that the branch with more unique attesters across all the blocks in the branch shall be selected. The lower branch has five unique attesters (Alice, Bob, Carol, Dave and Elaine), while the upper branch only has four (Victor, Xavier, Yasmine and Zach), so the lower branch is chosen. Note that there’s no actual chain in the lower branch that has five attesters attesting to the blocks in it, moreover there’s no chain in the lower branch that has even four unique attesters attesting the blocks in it (the chain that ends in the block at slot 7 has only attestations from Alice, Bob and Carol, while the chain that ends in the block at slot 8 has only attestations from Alice, Dave and Elaine). But accumulated across all the blocks in the lower branch the number of attesters is higher than in the upper branch, and thus the lower branch is chosen. Similarly, at block in slot 6 one would have to choose between two branches, with the upper branch having attestations from 3 unique attesters (Alice, Bob and Carol) and the lower from only two (Dave and Elaine), thus one would go to the upper branch eventually choosing the chain with blocks in slots 1, 2, 4, 6, 7. Latest Message Driven In the present fork choice rule design only the attestation from each attester with the highest slot number is considered. For example, on the figure below Alice attested to a block in slot 3, and only that attestations from Alice is used throughout the fork choice rule. In particular, her attestation in slot 2 is no longer considered, and thus when deciding on the branch at slot 0 the upper chain will be chosen since it has three attestations (Alice, Bob and Elaine), while the lower chain only has two (Carol and Dave): Note that it doesn’t matter which of the two attestations from Alice was submitted by her first, or in which order the attestations were received by a particular observer, only the attestations with the highest slot number (in this case 3) will be considered. Attestation conditions An honest attester must only attest to a block if the following conditions are met: The block belongs to the chain that the attester considers to be the currently selected chain; The attester hasn’t attested to any other block for the same time slot. Note that honest proposers would never propose two blocks for the same slot, so this rule only kicks in if a malicious proposer attempted to create a fork by producing multiple blocks for the same slot, a condition that is immediately slashable. If an attester doesn’t receive a block for a particular slot, they attest to a skip-block for that time slot. It is up for the attester to decide how far into the time slot they wait until they decide to stop waiting for the block and attest to the skip block. Danny Ryan suggests for a honest attester to wait until the middle of the time slot, but ultimately they shall do what they believe optimizes for the chance that they will attest to the same block (whether actual or skip-) as the majority of the other attesters. Analysis Liveness Unlike the family of BFT consensus algorithms, the approach discussed above continues to operate even if more than ⅓ of all the validators are offline. The participants in the network will observe that the blocks do not get ⅔ of attestations, and will be more cautious about the finality of the blocks, waiting for additional security (for example by waiting until the block is cross-linked to the beacon chain and is finalized by Casper FFG there, topics outside the scope of this write-up), but importantly, the blocks will continue to be published, and the system doesn’t stall. Censorship First observe that of the two censorship scenarios discussed above, the one in which two validators that have two consecutive slots censor out the block in the slot immediately preceding them is no longer valid, since the length of the chain doesn’t affect the fork choice rule any longer. The second scenario (in which the proposer for a block delays it until the next block is published), would still be possible if the attesters were not required to only attest during the time frame for the corresponding slot: a malicious proposer in time slot X could delay their block until the block X+1 is published, and then publish theirs. The attesters would not be able to distinguish between malicious intent and mere network delay, and without a specific requirement not to attest during the time window for the corresponding slot could still attest to block for slot X, effectively censoring X+1. The requirement to attest within the time frame completely solves the problem if the clocks among all the participants are perfectly synchronized. If the clocks are not synchronized (but are still within at most couple seconds from each other), some sorts of timing attacks are possible, though are extremely unlikely. Forkfulness Between the two possible approaches to how the attesters are accounted for (LMD in which only the largest-slot-number attestation from each attester is considered, and IMD in which all the attestations are considered) the latter provides slightly better forkfulness guarantees (see Forkfulness section in my original write-up here), though still not as good as the family of BFT consensus algorithms. With the LMD approach that is the current proposal for Ethereum 2.0 described in this write-up the forkfulness is weaker (i.e. forks are more likely). To understand why consider a branch with 60 attestations, some of which are by malicious attesters, and another branch with 40 attestations. In IMD 21 of the attesters who attested to the first branch need to exercise a malicious intent and attest to a block in the competing chain for that chain to beat the selected chain (in the end having 61 attestations vs 60 on the previously selected chain). In LMD it is sufficient for 11 attesters to exercise malicious behavior (in the end having 51 attestations vs 49 on the previously selected chain). Despite this weakness LMD still helps reduce the forkfulness, though does not remove the forks completely, even if more than ⅔ of attestations are accumulated and less than ⅓ of adversaries are present. Consider the following example: Assume there are 7 validators, Alice (A), Bob (B), Carol (C), Dave (D) and Elaine (E) are honest, while Xavier (X) and Yasmine (Y) are malicious. (i) There’s a fork with producers for time slot 2 and 3 both building on top of the block in slot 1. Alice and Bob both saw the block in time slot 2 during the time it was published and attested to it; (ii) Carol saw the block in time slot 3 when it was published, but hasn’t seen the block in slot 2 and its attestations yet, and thus attested to block in slot 3, so did Xavier and Yasmine; (iii) Now that the block in time slot 3 has three attestations, Alice and Bob consider it to be the selected block and also attest to it (assuming the time for the attestations hasn’t expired yet); The block in time slot 3 at this point has more than ⅔ of all the validators attesting to it and ideally shall not be reversible. (iv) Unknown to other attesters Dave and Elaine also attested to block in slot 2 back when it was still legal, but their attestations were delayed due to slow network, and were not seen by Alice and Bob previously; (v) Xavier and Yasmine exercise a malicious intent and build and attest to block in time slot 4 that is built on top of a block in time slot 2. At this point the upper chain has more attestations (Dave, Elaine, Xavier and Yasmine) than the lower chain (Carol, Alice and Bob), and becomes current, even though the lower chain had more than ⅔ attestations previously. (vi) All honest validators now also attest to the new block in slot 4. Note that this scenario requires a multitude of unlikely events (such as attestations from Dave and Elaine being delayed, which with hundreds of validators becomes extremely unlikely unless the adversaries control the network communication) and resorting to malicious behavior (Xavier and Yasmine attesting to a block they know is not on the selected chain, but still shows that the attestation framework doesn’t provide theoretical guarantees as strong as the family of BFT consensus algorithms. Comparison to TxFlow TxFlow is a consensus algorithm that NEAR uses for its shard chains. The informal spec of TxFlow can be found here. The two drawbacks of the Ethereum’s approach are the possibility of forks even after a very large number of attestations and the dependency on synchronized clocks among the validators. In the present proposal blocks are published every 8 seconds, so the clocks need to be synchronized up to several seconds. Simulations ran by the Ethereum Foundation show that even with the clocks discrepancy up to 10 seconds the chain continues to grow. Most of the blocks attested to become skip-blocks, but such skip-blocks point to regular blocks, effectively making the chain of regular blocks continue growing. TxFlow maintains most of the guarantees and properties of the Ethereum’s approach, but doesn’t have the dependency on the synchronized clocks, and guarantees block irreversibility under an assumption that fewer than ⅓ of all the validators are malicious. In the present design it does, however, lose liveness if more than ⅓ of the validators are offline until the validators are rotated. Footnote: Note that the assumption of less than ⅓ of malicious validators in a shard is not reasonable when the number of shards is high and the adversaries are adaptive, so the family of BFT protocols including TxFlow are also likely to ultimately have forks. It is worth pointing out that in the EthResearch thread on TxFlow, Vitalik points out that the TxFlow’s approach to deciding when blocks can be published (which is effectively “as fast as the network allows”) has another drawback, which is that nodes now have an incentive to pool and collocate to reduce the latency between them. The counterargument to this point is that in TxFow the bottleneck on the blocks is the latency of the fastest validator among the slowest ⅓, meaning that unless around ⅔ of all the validators collocate, collocation doesn’t speed up block production (and thus rewards) much. Thus for the collocation and the centralization it brings to occur, a major cooperation among validators is needed, which is extremely unlikely for as long as the pool of the validators is sufficiently large. The choice between the TxFlow and Attestations framework narrows down to the following table: Outro If you are interested in the space of sharded decentralized ledgers, please follow our progress: NEAR Twitter — https://twitter.com/nearprotocol, My Twitter — https://twitter.com/AlexSkidanov Medium — https://medium.com/nearprotocol, Discord — https://discord.gg/kRY6AFp, Research Forum — http://research.nearprotocol.com https://upscri.be/633436/ We will also make our primary repository on GitHub open within coming weeks, so stay tuned. Huge thanks to Vitalik Buterin, Justin Drake and Danny Ryan for answering numerous question and clarifying the attestations framework, and to Bowen Wang and David Stolp for reviewing the draft of this article.
```js import { Wallet } from './near-wallet'; const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near"; const NFT_CONTRACT_ADDRESS = "nft.primitives.near"; const NFT_TOKEN_ID = "1"; const DROP_AMOUNT = "10000000000000000000000"; const wallet = new Wallet({ createAccessKeyFor: DAO_CONTRACT_ADDRESS }); await wallet.callMethod({ method: "create_drop", contractId: KEYPOM_CONTRACT_ADDRESS, args: { public_keys: state.publicKeys, deposit_per_use: DROP_AMOUNT, fcData: { // 2D array of function calls. In this case, there is 1 function call to make for a key use // By default, if only one array of methods is present, this array of function calls will be used for all key uses methods: [ // Array of functions for Key use 1. [{ receiverId: NFT_CONTRACT_ADDRESS, methodName: "nft_mint", args: JSON.stringify({ // Change this token_id if it already exists -> check explorer transaction token_id: NFT_TOKEN_ID, metadata: { title: "My NFT drop", description: "", media: "", } }), accountIdField: "receiver_id", // Attached deposit for when the receiver makes this function call attachedDeposit: "10000000000000000000000" }] ] } }, deposit: "23000000000000000000000" // state.publicKeys.length * dropAmount + 3000000000000000000000, gas: "100000000000000", }); ``` _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
--- id: lido title: Lido Example --- # Hello Lido! If you are ready to explore further, the [Lido component](https://near.org/zavodil.near/widget/Lido) serves as an excellent fully-fledged example, as it demonstrates how to interact with a smart contract deployed on the Ethereum mainnet. :::info Ethers.js This component uses the [Ethers JavaScript](https://ethers.org) library to interact with Ethereum smart contracts. Follow [this link](https://docs.ethers.org/v6/) for the official `ethers.js` documentation. ::: :::info Web3 connect The Lido example uses the [Web3Connect component](https://near.org/near/widget/ComponentDetailsPage?src=a_liutiev.near/widget/button_web3connect) to provide a [WalletConnect modal](https://github.com/WalletConnect/web3modal) so the user can connect with any Web3 Ethereum wallet like Ledger or MetaMask. ::: ### Fork the component 1. Navigate to [the component](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/Lido) 2. Select `Fork` 3. Feel free to make any changes 4. Click on <kbd>Save</kbd> to deploy the component :::note To deploy the component, you'll need to sign in with a NEAR account and to make a deposit of a small amount of NEAR for the storage cost. This is because the components are stored in the NEAR network. ::: ### Source code ```js if ( state.chainId === undefined && ethers !== undefined && Ethers.send("eth_requestAccounts", [])[0] ) { Ethers.provider() .getNetwork() .then((chainIdData) => { if (chainIdData?.chainId) { State.update({ chainId: chainIdData.chainId }); } }); } if (state.chainId !== undefined && state.chainId !== 1) { return <p>Switch to Ethereum Mainnet</p>; } // FETCH LIDO ABI const lidoContract = "0xae7ab96520de3a18e5e111b5eaab095312d7fe84"; const tokenDecimals = 18; const lidoAbi = fetch( "https://raw.githubusercontent.com/lidofinance/lido-subgraph/master/abis/Lido.json" ); if (!lidoAbi.ok) { return "Loading"; } const iface = new ethers.utils.Interface(lidoAbi.body); // FETCH LIDO STAKING APR if (state.lidoArp === undefined) { const apr = fetch( "https://api.allorigins.win/get?url=https://stake.lido.fi/api/sma-steth-apr" ); if (!apr) return; State.update({ lidoArp: JSON.parse(apr?.body?.contents) ?? "..." }); } // HELPER FUNCTIONS const getStakedBalance = (receiver) => { const encodedData = iface.encodeFunctionData("balanceOf", [receiver]); return Ethers.provider() .call({ to: lidoContract, data: encodedData, }) .then((rawBalance) => { const receiverBalanceHex = iface.decodeFunctionResult( "balanceOf", rawBalance ); return Big(receiverBalanceHex.toString()) .div(Big(10).pow(tokenDecimals)) .toFixed(2) .replace(/\d(?=(\d{3})+\.)/g, "$&,"); }); }; const submitEthers = (strEther, _referral) => { if (!strEther) { return console.log("Amount is missing"); } const erc20 = new ethers.Contract( lidoContract, lidoAbi.body, Ethers.provider().getSigner() ); let amount = ethers.utils.parseUnits(strEther, tokenDecimals).toHexString(); erc20.submit(lidoContract, { value: amount }).then((transactionHash) => { console.log("transactionHash is " + transactionHash); }); }; // DETECT SENDER if (state.sender === undefined) { const accounts = Ethers.send("eth_requestAccounts", []); if (accounts.length) { State.update({ sender: accounts[0] }); console.log("set sender", accounts[0]); } } //if (!state.sender) return "Please login first"; // FETCH SENDER BALANCE if (state.balance === undefined && state.sender) { Ethers.provider() .getBalance(state.sender) .then((balance) => { State.update({ balance: Big(balance).div(Big(10).pow(18)).toFixed(2) }); }); } // FETCH SENDER STETH BALANCE if (state.stakedBalance === undefined && state.sender) { getStakedBalance(state.sender).then((stakedBalance) => { State.update({ stakedBalance }); }); } // FETCH TX COST if (state.txCost === undefined) { const gasEstimate = ethers.BigNumber.from(1875000); const gasPrice = ethers.BigNumber.from(1500000000); const gasCostInWei = gasEstimate.mul(gasPrice); const gasCostInEth = ethers.utils.formatEther(gasCostInWei); let responseGql = fetch( "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `{ bundle(id: "1" ) { ethPrice } }`, }), } ); if (!responseGql) return ""; const ethPriceInUsd = responseGql.body.data.bundle.ethPrice; const txCost = Number(gasCostInEth) * Number(ethPriceInUsd); State.update({ txCost: `$${txCost.toFixed(2)}` }); } // FETCH CSS const cssFont = fetch( "https://fonts.googleapis.com/css2?family=Manrope:wght@200;300;400;500;600;700;800" ).body; const css = fetch( "https://pluminite.mypinata.cloud/ipfs/Qmboz8aoSvVXLeP5pZbRtNKtDD3kX5D9DEnfMn2ZGSJWtP" ).body; if (!cssFont || !css) return ""; if (!state.theme) { State.update({ theme: styled.div` font-family: Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; ${cssFont} ${css} `, }); } const Theme = state.theme; // OUTPUT UI const getSender = () => { return !state.sender ? "" : state.sender.substring(0, 6) + "..." + state.sender.substring(state.sender.length - 4, state.sender.length); }; return ( <Theme> <div className="LidoContainer"> <div className="Header">Stake Ether</div> <div className="SubHeader">Stake ETH and receive stETH while staking.</div> <div className="LidoForm"> {state.sender && ( <> <div className="LidoFormTopContainer"> <div className="LidoFormTopContainerLeft"> <div className="LidoFormTopContainerLeftContent1"> <div className="LidoFormTopContainerLeftContent1Container"> <span>Available to stake</span> <div className="LidoFormTopContainerLeftContent1Circle" /> </div> </div> <div className="LidoFormTopContainerLeftContent2"> <span> {state.balance ?? (!state.sender ? "0" : "...")}&nbsp;ETH </span> </div> </div> <div className="LidoFormTopContainerRight"> <div className="LidoFormTopContainerRightContent1"> <div className="LidoFormTopContainerRightContent1Text"> <span>{getSender()}</span> </div> </div> </div> </div> <div className="LidoSplitter" /> </> )} <div className={ state.sender ? "LidoFormBottomContainer" : "LidoFormTopContainer" } > <div className="LidoFormTopContainerLeft"> <div className="LidoFormTopContainerLeftContent1"> <div className="LidoFormTopContainerLeftContent1Container"> <span>Staked amount</span> </div> </div> <div className="LidoFormTopContainerLeftContent2"> <span> {state.stakedBalance ?? (!state.sender ? "0" : "...")} &nbsp;stETH </span> </div> </div> <div className="LidoFormTopContainerRight"> <div className="LidoAprContainer"> <div className="LidoAprTitle">Lido APR</div> <div className="LidoAprValue">{state.lidoArp ?? "..."}%</div> </div> </div> </div> </div> <div className="LidoStakeForm"> <div className="LidoStakeFormInputContainer"> <span className="LidoStakeFormInputContainerSpan1"> <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"> <path opacity="0.6" d="M11.999 3.75v6.098l5.248 2.303-5.248-8.401z" ></path> <path d="M11.999 3.75L6.75 12.151l5.249-2.303V3.75z"></path> <path opacity="0.6" d="M11.999 16.103v4.143l5.251-7.135L12 16.103z" ></path> <path d="M11.999 20.246v-4.144L6.75 13.111l5.249 7.135z"></path> <path opacity="0.2" d="M11.999 15.144l5.248-2.993-5.248-2.301v5.294z" ></path> <path opacity="0.6" d="M6.75 12.151l5.249 2.993V9.85l-5.249 2.3z" ></path> </svg> </span> <span className="LidoStakeFormInputContainerSpan2"> <input disabled={!state.sender} className="LidoStakeFormInputContainerSpan2Input" value={state.strEther} onChange={(e) => State.update({ strEther: e.target.value })} placeholder="Amount" /> </span> <span className="LidoStakeFormInputContainerSpan3" onClick={() => { State.update({ strEther: (state.balance > 0.05 ? parseFloat(state.balance) - 0.05 : 0 ).toFixed(2), }); }} > <button className="LidoStakeFormInputContainerSpan3Content" disabled={!state.sender} > <span className="LidoStakeFormInputContainerSpan3Max">MAX</span> </button> </span> </div> {!!state.sender ? ( <button className="LidoStakeFormSubmitContainer" onClick={() => submitEthers(state.strEther, state.sender)} > <span>Submit</span> </button> ) : ( <Web3Connect className="LidoStakeFormSubmitContainer" connectLabel="Connect with Web3" /> )} <div className="LidoFooterContainer"> {state.sender && ( <div className="LidoFooterRaw"> <div className="LidoFooterRawLeft">You will receive</div> <div className="LidoFooterRawRight">${state.strEther ?? 0} stETH</div> </div> )} <div className="LidoFooterRaw"> <div className="LidoFooterRawLeft">Exchange rate</div> <div className="LidoFooterRawRight">1 ETH = 1 stETH</div> </div> {false && ( <div className="LidoFooterRaw"> <div className="LidoFooterRawLeft">Transaction cost</div> <div className="LidoFooterRawRight">{state.txCost}</div> </div> )} <div className="LidoFooterRaw"> <div className="LidoFooterRawLeft">Reward fee</div> <div className="LidoFooterRawRight">10%</div> </div> </div> </div> </div> </Theme> ); ``` #### Fork the component 1. Navigate to [the component](https://near.org/near/widget/ComponentDetailsPage?src=zavodil.near/widget/Lido) 2. Select `Fork` 3. Feel free to make any changes 4. Click on <kbd>Save</kbd> to deploy the component :::note To deploy the component, you'll need to sign in with a NEAR account and to make a deposit of a small amount of NEAR for the storage cost. This is because NEAR components are stored in the NEAR network. :::
```rust // Validator interface, for cross-contract calls #[ext_contract(ext_dao_factory_contract)] trait ExternalDaoFactoryContract { fn create(&mut self, name: AccountId, args: Base64VecU8) -> Promise; } // Implement the contract structure #[near_bindgen] impl Contract { #[payable] pub fn create_dao(&mut self, name: AccountId, args: Base64VecU8) -> Promise { let promise = ext_dao_factory_contract::ext(self.dao_factory_contract.clone()) .with_attached_deposit(env::attached_deposit()) .with_static_gas(Gas(30*TGAS)) .create(name, args); return promise.then( // Create a promise to callback query_greeting_callback Self::ext(env::current_account_id()) .with_static_gas(Gas(50*TGAS)) .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") } } } ```
Encode x NEAR Horizon Bootcamp: Your Mission to Master Web3 Rust Contracts NEAR FOUNDATION June 14, 2023 Web3 builders, developers, and founders are gearing up to join the Encode x NEAR Horizon Bootcamp starting July 10th, 2023 to upgrade their building, development, and coding skills. Following the recent partnership between NEAR Horizon and Encode Club, the bootcamp is part of a broader initiative to accelerate blockchain expertise with a focus on developing Rust smart contracts. Encode Club is a community that helps builders grow their technical capabilities with tangible results, such as completing projects, promoting employability, and gaining funding. This mission aligns seamlessly with NEAR Horizon, a new branch of the NEAR Foundation fostering innovation and development among early stage Web3 Founders building in the NEAR ecosystem If you’re a self-starting developer hungry to learn more about building on NEAR, then the NEAR x Encode Club Bootcamp might just be the perfect crash course to get started and progress rapidly. Apply here for the NEAR x Encode Bootcamp. Here’s the lowdown on what the bootcamp will entail and how NEAR builders can fast track their Web3 skillset and knowledge base to the next level. Ranking up in Web3 with the NEAR x Encode Club Bootcamp Firstly, selected participants can attend the bootcamp for free, reflecting Encode Club’s commitment to supporting Web3 builders. The 90-minute lessons will be conducted via Zoom (or similar), Monday through Thursday over the course of eight weeks, and feature an engaging mix of deep educational content focused on smart contract development as well as hands-on learning from Encode Club technical experts. Mentors will guide participants through a variety of topics and related subjects, demystifying the myriad of concepts and nuances inherent in blockchain development. The focus will be primarily on the NEAR ecosystem, with the goal of ensuring that everyone gains the practical skills and knowledge to excel, succeed, and create in the rapidly evolving Web3 world. Calling all coders: Bootcamp application and selection process There are no official prerequisites to applying for the bootcamp. However, previous coding and Web3 or blockchain experience (particularly with RUST) will help you get the most from the sessions. The Bootcamp is also part-time, giving attendees flexibility with their full-time commitments. After registration, the pool will be whittled down to a shortlist who will be asked to conduct a brief interview before being formally selected and invited to attend. At this time, selectees will be asked to provide a small deposit, repaid when the Bootcamp concludes. The cohort size will be roughly 50 people, with Encode Club assisting in job placement once finished. The NEAR x Encode Club Bootcamp is a perfect example of the work NEAR Horizon is doing as a startup support platform for the entire ecosystem. Any builders, developers, or NEAR blockchain enthusiasts should apply directly through Encode Club right away, as cohort space is currently limited. To learn more about NEAR Horizon or to list your project on the Horizon platform, visit near.org/horizon. Your mission – should you choose to accept and sign the transaction – is to master Web3 at the NEAR x Encode Club Bootcamp. Apply now and report for duty on July 10th!
Announcing Web Push Notifications on B.O.S NEAR FOUNDATION October 4, 2023 Starting today, developers can better engage with their users thanks to Web Push Notifications on both desktop and mobile for applications built on B.O.S. Apps and components built on the NEAR B.O.S have always benefited from in-site notifications to keep their users informed about relevant updates. Until now, these notifications were only shown within near.org (and other compatible gateways), meaning that users had to visit the website to see them. Now, users can opt-in to receive push notifications directly on their computers and phones about important events in their favorite apps. This way, users can be notified in real time, even if they are not actively navigating near.org. Why are push notifications useful? Thanks to push notifications, users can receive timely updates and information about their account’s activities in real time and through multiple channels. The increase in awareness also benefits application developers by encouraging users to return to the app, thus significantly improving user engagement. This way, push notifications help to tackle one of the biggest problems for founders in Web3: re-engaging and retaining users. Nowadays, user retention rates in Web3 fall short of the industry standard for web apps, which stands at a 35% retention rate after 30 days. Thanks to web push notifications, developers on BOS now benefit from a powerful new tool to re-engage their user base. What will the notification experience look like on near.org? On near.org, users will be asked to opt-in to the new push notification system on their desktop and iOS/Android mobile browsers. (To enable browser push notifications on iOS, users need to update their device at least to iOS 16.4 and will also need to add the near.org website as an app icon to their home screen – see link.) If the user accepts, they will automatically start to receive notifications for baseline social activities on their account. Users will be able to view all notifications in the notification center, and set their notification preferences via the designated settings menu. For developers implementing components and apps, the new notification system is completely transparent. Apps that already leverage the in-site notification system will automatically benefit from web push notifications, meaning their users will also be notified on their desktop and mobile in real time. For gateway developers, Pagoda is releasing a comprehensive guide on how to add web push notifications using a simple web service. What are some examples of notifications I could add to my application? Notifications can apply to any event that developers want to inform users about. Some examples of how developers have used these are: Notify updates on the status of a bid placed on an NFT marketplace. Tell users that they gained a new follower. Inform of a reply to a comment on a discussion. Any other on-chain action that is sent to the current notification system. How do I learn more and get started? The best place to start is by checking the official documentation. You can also check examples of apps sending notifications such as the LikeButton and FollowButton. If you have any questions or need to reach out to the Pagoda product team, remember that we have weekly office hours, and an active Telegram channel where members of the community can help you. What’s coming next? Stay tuned! Pagoda plans to release additional notification features later this year, including support for more granular notification settings and safeguards to manage notification volume for users on near.org. They will also be exploring support for near.org notifications via email.
Unlocking the Future of DeFi with the idOS on NEAR: A Developer’s Guide NEAR FOUNDATION November 9, 2023 In the ever-evolving landscape of web3, DeFi has stood apart as a driver of innovation, promising a decentralized financial future. But for developers and founders, the challenge has always been integrating real-world applications with the decentralized world, ensuring compliance, and providing a seamless user experience. Enter the idOS on NEAR, a solution — built with Fractal — that bridges this gap and brings the Open Web closer to mainstream adoption. Why the idOS Matters For developers diving into DeFi, the idOS (Identity Operating System) on NEAR offers a robust framework. It’s not just about creating decentralized financial applications; it’s about crafting solutions that can interact with real-world systems, regulations, and meet user expectations. 1. Composable & Permissionless Integration: With the idOS, developers can effortlessly combine different protocols that require identity verification, leveraging the “money legos” concept. This composability ensures that your DeFi applications can scale and evolve with the ecosystem. 2. Enhanced User Experience & Identity Verification: One of the major pain points in the decentralized world is the repetitive identity verification processes, often known as KYC. With the idOS, this process is streamlined. Users verify their identity once, and then, by simply signing with their wallet, they can reuse their verified credentials across any NEAR dApp without undergoing KYC again. This not only enhances user experience but also ensures faster onboarding and interaction with dApps. 3. Seamless On/Off Ramps: The idOS facilitates smoother crypto-fiat transactions, a significant pain point in web3 adoption. By integrating the idOS, developers can offer users the ability to easily transition between the decentralized and traditional financial worlds, unlocking use cases like remittances or DeCommerce payments. Beyond DeFi: Proof-of-Personhood Use Cases While DeFi is the cornerstone, the idOS’s potential extends beyond. For founders looking to innovate in areas like decentralized governance or community voting, the idOS provides the tools to ensure proof-of-personhood: 1. Decentralized Voting: Governance is a critical aspect of any decentralized protocol. With the idOS, developers can integrate systems where users prove their unique human status, ensuring one person, one vote. This minimizes the influence of bots and whales, leading to fairer governance outcomes. 2. Portable user profiles across Web3: For platforms that require user profiles like Near.org, the idOS offers a decentralized solution. Users can create and manage their profiles, ensuring data privacy and control. This is especially crucial for platforms that want to offer personalized experiences without compromising on user data sovereignty. Privacy-Preserving KYC & Compliance No developer wants to compromise on user privacy. With the idOS, KYC processes become more user-centric. Users can obtain KYC credentials from multiple providers, with the assurance that their data remains encrypted and under their control. For founders, this means complying with global financial regulations without sacrificing user trust. Join the revolution with idOS For developers and founders ready to shape the future of DeFi and decentralized applications, the idOS on NEAR offers the tools, scalability, and compliance required for success. As we venture into a world where decentralized finance and real-world applications converge, solutions like the idOS will be at the forefront, ensuring that innovation remains uncompromised. Join the revolution and explore how the idOS can redefine your DeFi applications and enhance user identity verification on NEAR.
Mintbase Brings New Open Web Wallet Tech to Families Celebrating Raksha Bandhan NEAR FOUNDATION August 29, 2023 Mintbase, a leading NFT platform that allows users to mint, buy, and sell digital assets has partnered with the NEAR Foundation to help friends and family celebrate the traditional Indian festival, Raksha Bandhan, with Open Web technology. By bringing together several pieces of breakthrough wallet technology for the first time, photos can be instantly converted into NFTs and stored permanently on the NEAR blockchain — all without users needing to create seed phrases or pre-loaded wallets. A new type of wallet Mintbase’s new wallet streamlines the blockchain user experience like never before thanks to innovations on the NEAR blockchain. FastAuth, created by NEAR, is an open-source protocol that provides an onboarding and account recovery process similar to what you find in Web2. It uses meta transactions, allowing a third party to pay the gas fee on behalf of the user, solving one of the most significant problems new users face in the blockchain world. The other killer feature is NEAR’s built-in account abstraction system. Users no longer need to deal with seed phrases or require NEAR to mint. Instead, a full access key is stored in the user’s passkey system, so biometric signing will work in a noncustodial way without any local storage interactions. This means no more seed phrases, and no more having to pre-load the wallet with currency before use. Instead, users of Mintbase’s wallet will be able to use and interact with blockchain in the same way they would with Web2 apps. Celebrating the essence of Rakhi To celebrate Raksha Bandhan, the popular Indiana festival where sisters tie a talisman or amulet called a Rakhi around the wrists of their brothers, users will be able to capture the moment with a photo and upload it instantly to the blockchain via the Mintbase wallet. The metadata will be permanently stored on the Arweave blockchain and a NFT of the moment will be minted on the NEAR blockchain and delivered back to the user. It’s a sizable step forward in showcasing how far Web3 technology has come in making the user experience easier and more familiar to non-blockchain users. As part of this celebration, there’s more than just memories to win. Participants can win prizes for NFTs they created and share them on X (formerly Twitter) with the hashtag #RakhisNEAR. For more details, please visit https://rakhi.mintbase.xyz. Participate, share, and make this Raksha Bandhan more memorable with Mintbase and NEAR Foundation.
--- description: Expectations of participants using the NEAR Governance Forum --- # NEAR Social Channel Rules Welcome to NEAR’s social channels! We're excited to have you here as part of our community. Before you engage, please take a moment to read and understand our social channel rules: ## 1. NEAR Community Culture and Values We promote a respectful and inclusive environment. Please be kind and considerate to all community members, and participate in our social channels in a way that aligns with, and furthers, the NEAR community culture and values (as described below). The NEAR social channels, and the wider community, serve to nurture the development of the NEAR ecosystem, the community, and the incredible innovation stemming from it. The culture of the NEAR community is one of **openness, inclusiveness, and positivity**. ### The NEAR Foundation has five core values: **1. Ecosystem First** _Always put the health and success of the ecosystem above any individual’s interest._ The focus of all community members should be the growth and development of the NEAR ecosystem. We will not tolerate intentional disruption, subterfuge, or any act which amounts to “trolling”. **2. Openness** _Operate transparently and consistently share knowledge to build open communities._ The NEAR social channels, by their very nature, are open, accessible, and transparent. Feel free to share your thoughts and ideas on anything and everything NEAR. **3. Pragmatism Over Perfection** _Find the right solution not the ideal solution and beat dogmatism by openly considering all ideas._ The NEAR Foundation, just like the NEAR technology itself, doesn’t play favorites and is ultimately here to make everyone successful, regardless of where they come from. We are here to BUIDL, and the NEAR social channels are another tool in the arsenal of the NEAR ecosystem which will allow us to achieve success. All ideas, regardless of what they are and who they’re from, are welcome in the NEAR social channels. **4. Make It Feel Simple** _Strive to make the complex feel simple so the technology, platform and ecosystem are accessible to all._ The NEAR ecosystem is global and, naturally, not everyone speaks English as their first language. Let’s keep our discussion as accessible as possible, but don’t shy away from the complex when necessary. **5. Grow Constantly** _Learn, improve and fail productively so the ecosystem and the community are always becoming more effective._ We’re not just here to BUIDL awesome dApps and NEAR-fueled solutions, we’re here to BUIDL ourselves and each other too! There are a tonne of amazing people here (including you) who we can all learn from and teach. **Ultimately**, if you’re ever asking yourself “should I post this?” ask yourself if it aligns with the NEAR community cultures and values. If it does, and it doesn’t violate any other rules, then fire away! ## 2. Things You Should Do When participating in NEAR social channels, you should: * treat others online as you would treat them in real life; * be tolerant towards other’s viewpoints, and respectfully disagree when opinions do not align; * respect the privacy and personal information of other contributors; * communicate with courtesy and respect; * provide accurate information, if you are not sure, please cross-check or contact a community moderator for support; and * always verify information posted by others, and be cautious of scams or phishing attempts. ## 3. Things You Should Not Do When participating in NEAR social channels, you should **not**: * make personal attacks on other community members; * use defamatory remarks or make false statements against others; * post prejudiced comments or profanity; * post sexually explicit content; * post discriminating content, this includes content around religion and politics; * bully or make inflammatory remarks to other community members; * post spam; * share personal or financial information; * discuss cryptocurrency, token, or asset prices – we encourage discussions about NEAR technology, its use cases, and development of the NEAR ecosystem, but prohibit any price predictions or speculation, or provision of any financial/investment advice; * promote other projects, tokens, or services without prior permission from a community moderator (this includes directly messaging other community members) – unsolicited self-promotion may result in removal; * engage in server raiding or any activity that disrupts or harasses other communities or channels; or * solicit or request funds from community members. ## 4. Legal Disclaimer The NEAR Foundation maintains NEAR social channels for informational and community-building purposes only. The NEAR Foundation does not endorse any specific tokens (including, without limitation, the NEAR token), projects, or financial activities. All information and content shared within NEAR social channels are for general informational purposes and should not be considered as financial, legal, or investment advice. Any decisions made based on the information shared here are made at your own risk. Any views, opinions, or statements expressed by anyone in a NEAR social channel are their own and do not necessarily represent the views or opinions of the NEAR Foundation. The NEAR Foundation is not responsible for the accuracy, completeness, or reliability of the information shared in NEAR social channels, including (without limitation, any third-party websites which are linked to in the social channels, which if you access you do so entirely at your own risk). Participation in NEAR social channels is at your own risk, and the NEAR Foundation and its representatives and moderators are not responsible for any financial or legal consequences that may arise in connection with such participation (including, without limitation, resulting from any actions, statements, or content posted or shared by anyone participating in the channel, including administrators, moderators or other community members). The NEAR Foundation is not responsible for any technical issues, disruptions, or interruptions in NEAR social channels, including but not limited to server outages, network problems, or third-party service failures. ## 5. Changes to these Rules These guidelines may be updated from time to time. It is your responsibility to stay informed about any changes. ## 6. Reporting Violations If you encounter any violations of these guidelines, please report them to a moderator. We rely on the community to help maintain a safe and positive environment. By participating in a NEAR social channel, you agree to abide by these rules. We reserve the right to remove or ban any member from our social channels, and moderate, edit, or remove any content, for any reason at our discretion and without warning. This includes but is not limited to violation of these rules, disruptive behavior, or spamming. Thank you for being a part of the NEAR community! We look forward to productive and respectful interactions within our community. _Last updated: 19 September 2023_
--- id: prototyping sidebar_label: Rapid Prototyping title: "Upgrading Contracts: Rapid Prototyping" --- import {CodeTabs, Language, Github} from "@site/src/components/codetabs"; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; # Rapid Prototyping When you change the interface of a contract and re-deploy it, you may see this error: Cannot deserialize the contract state. ### Why does this happen? When your contract is executed, the NEAR Runtime reads the serialized state from disk and attempts to load it using current contract code. When your code changes but the serialized state stays the same, it can't figure out how to do this. ### How can you avoid such errors? When you're still in the Research & Development phase, building a prototype and deploying it locally or on [testnet](/concepts/basics/networks), you can just delete all previous contract state when you make a breaking change. See below for a couple ways to do this. When you're ready to deploy a more stable contract, there are a couple of [production strategies](../../../2.build/2.smart-contracts/release/upgrade.md#migrating-the-state) that will help you update the contract state without deleting it all. And once your contract graduates from "trusted mode" (when maintainers control a [Full Access key](/concepts/protocol/access-keys)) to community-governed mode (no more Full Access keys), you can set up your contract to [upgrade itself](../../../2.build/2.smart-contracts/release/upgrade.md#programmatic-update). ## Rapid Prototyping: Delete Everything All The Time There are two ways to delete all account state: 1. Deploying on a new account each time 2. Deleting & recreating contract account For both cases, let's consider the following example. The [rust-status-message](https://github.com/near-examples/rust-status-message) example contract has the following structure: <CodeTabs> <Language value="rust" language="rust"> <Github fname="lib.rs" url="https://github.com/near-examples/rust-status-message/blob/b5fa6f2a30559d56a3a3ea52da8c26c5d3907606/src/lib.rs" start="5" end="29"/> </Language> </CodeTabs> Let's say you deploy this contract to testnet, then call it with: <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash near call [contract] set_status '{"message": "lol"}' --accountId you.testnet near view [contract] get_status '{"account_id": "you.testnet"}' ``` </TabItem> <TabItem value="near-cli-rs"> ```bash near contract call-function as-transaction [contract] set_status json-args '{"message": "lol"}' prepaid-gas '30 TeraGas' attached-deposit '0 NEAR' sign-as you.testnet network-config testnet sign-with-keychain send near contract call-function as-read-only [contract] get_status text-args '{"account_id": "you.testnet"}' network-config testnet now ``` </TabItem> </Tabs> This will return the message that you set with the call to `set_status`, in this case `"lol"`. At this point the contract is deployed and has some state. Now let's say you change the contract to store two kinds of data for each account: ```rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct StatusMessage { taglines: LookupMap<AccountId, String>, bios: LookupMap<AccountId, String>, } impl Default for StatusMessage { fn default() -> Self { Self { taglines: LookupMap::new(b"r"), bios: LookupMap::new(b"b"), } } } #[near_bindgen] impl StatusMessage { pub fn set_tagline(&mut self, message: String) { let account_id = env::signer_account_id(); self.taglines.insert(&account_id, &message); } pub fn get_tagline(&self, account_id: AccountId) -> Option<String> { return self.taglines.get(&account_id); } pub fn set_bio(&mut self, message: String) { let account_id = env::signer_account_id(); self.bios.insert(&account_id, &message); } pub fn get_bio(&self, account_id: AccountId) -> Option<String> { return self.bios.get(&account_id); } } ``` You build & deploy the contract again, thinking that maybe because the new `taglines` LookupMap has the same prefix as the old `records` LookupMap (the prefix is `r`, set by `LookupMap::new(b"r".to_vec())`), the tagline for `you.testnet` should be `"lol"`. But when you `near view` the contract, you get the "Cannot deserialize" message. What to do? ### 1. Deploying on a new account each time When first getting started with a new project, the fastest way to deploy a contract is [creating an account](../../../4.tools/cli.md#near-create-account) and [deploying the contract](../../../4.tools/cli.md#near-deploy) into it using `NEAR CLI`. <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash near create-account <account-id> --useFaucet near deploy <account-id> ./path/to/compiled.wasm ``` </TabItem> <TabItem value="near-cli-rs"> ```bash near account create-account sponsor-by-faucet-service <my-new-dev-account>.testnet autogenerate-new-keypair save-to-keychain network-config testnet create near contract deploy <my-new-dev-account>.testnet use-file <route_to_wasm> without-init-call network-config testnet sign-with-keychain ``` </TabItem> </Tabs> This does a few things: 1. Creates a new testnet account pre-funded with 10N from the faucet 2. Stores the private key for this account in the `~/.near-credentials` folder 3. Deploys your contract code to this account ### 2. Deleting & Recreating Contract Account Another option to start from scratch is to delete the account and recreate it. <Tabs className="language-tabs" groupId="code-tabs"> <TabItem value="near-cli"> ```bash title="Delete sub-account" near delete app-name.you.testnet you.testnet ``` </TabItem> <TabItem value="near-cli-rs"> ```bash title="Delete sub-account" near account delete-account app-name.you.testnet beneficiary you.testnet network-config testnet sign-with-keychain send ``` </TabItem> </Tabs> This sends all funds still on the `app-name.you.testnet` account to `you.testnet` and deletes the contract that had been deployed to it, including all contract state. Now you create the sub-account and deploy to it again using the commands above, and it will have empty state like it did the first time you deployed it.
Join Stake Wars to Become a Chunk-Only Producer DEVELOPERS June 30, 2022 Stake Wars is back to help decentralize the NEAR network and help the community with cool new challenges and rewards to members who want to become validators. In Stake Wars: Episode III, NEAR is focusing on Chunk-Only Producers—NEAR’s next step toward a fully-sharded protocol. By introducing this new type of validator, NEAR can increase the total number of validator seats. Stake Wars is helping Chunk-Only Producers to prepare for this moment. It’s an opportunity to gain confidence and learn how to work with contract-based delegation. With Stake Wars III set for July 13, here’s a brief rundown of the new Chunk-Only Producer role, and what to expect from the Stake Wars program. Chunk-Only Producers help decentralize and secure NEAR The NEAR Network is currently secured by 100 validators. NEAR’s roadmap will allow the protocol to become fully-sharded. This will help reach the ambitious goal to decentralize NEAR while keeping the network secure. Chunk-Only Producers are an important milestone along this path. Chunk-Only Producers are solely responsible for producing chunks in a single shard (a network partition). A chunk, of course, is a shard block (see Nightshade for more detail). What’s cool for Chunk-Only Producers is that they can run their validator node on a less demanding machine, such as a 4-Core CPU, with 8GB of RAM and 200GB SSD of storage. Once the Chunk-Only Producer is available on NEAR mainnet at the end of Q3, NEAR plans to onboard an additional 200-300 validators. This, combined with a lower barrier to entry (minimum stake) for validators, is a win for the NEAR network as it moves toward a more scalable future. By increasing the total number of validators, NEAR will become more decentralized and more secure. How Stake Wars III works Chunk-Only Producers can deploy the open-source Staking Pool smart contract from Github, to test their systems and gain confidence with contract-based delegation. Validators are also free to customize their delegation contract, build their web applications, and integrate the Staking Pool into their existing systems. Stake Wars is community-operated, and community members such as Metapool, Everstake, LiNEAR and Open Shards Alliance (OSA) will offer their support to the program. NEAR plans to use more than 4M $NEAR tokens as delegation rewards for the participants who complete the challenges. These rewards help put participants in a position to become a mainnet validators by Q4 of 2022. The Stake Wars: Episode III incentivized testnet for Chunk-Only Producers will launch on July 13th and run until early September. Any potential validators should join the Stake Wars community on Telegram and Discord to coordinate with other Validators, and follow @PagodaPlatform on twitter. The full Stake Wars III page is launching soon. So stay tuned.
--- id: split-storage-archival title: Split Storage for NEAR Archival Nodes sidebar_label: Split Storage sidebar_position: 4 description: Split Storage for NEAR Archival Nodes --- This page presents the Split Storage option for NEAR Archival nodes. ## Introduction {#introduction} With the 1.35.0 release we are rolling out split storage, a new option for storage management that is mainly targeted at archival nodes.. Split storage allows nodes to reduce storage costs and improve block production performance by splitting local storage into two separate areas: a hot and a cold database . The hot database is smaller in size and stores all of the data from the most recent epochs. The cold database is larger, and it stores all historical data for older epochs. Hot and cold databases can be independently placed on separate hardware storage, allowing configurations such as using hot storage on a fast NVMe drive, and placing cold storage on a cheaper HDD drive. In split storage mode, the Near Client only works with a smaller hot database to produce blocks, which results in increased performance. Cold database is not accessed for reads during normal block production and is only read when historical data is specifically requested. Thus, we recommend keeping the cold database on cheaper and slower drives such as an HDD and only optimize speed for the hot database, which is about 10 times smaller. Split storage is disabled by default, and can be enabled with a config change and going through a migration process that requires manual steps. We have several choices for the migration: * Use Pagoda-provided S3 snapshots of nodes that have split-storge configured. * Do a manual migration using S3 snapshots of the existing RPC single database * Do a manual migration using your own buddy RPC node | Migration option | Pros | Cons | | --------------------------------------------------- | ------------------------------- | ------------------------------------------------------ | | Pagoda-provided S3 snapshots of split-storage nodes | Fastest. Little to no downtime. | Requires trust in migration performed by Pagoda nodes | | Manual migration + S3 RPC snapshots | No need for extra node. Cold storage is initialized in a trustless way. | Requires trust in Pagoda RPC snapshots. The node will be out of sync at the end of the migration and will need to block sync several epochs. Migration takes days and you cannot restart your node during that time. | | Manual migration + your own node | Trustless. Little to no downtime | Requires an extra RPC node with bigger storage. Migration takes days and you cannot restart your node during that time. | ## Important config fields {#config} ```json { "archive": true, "save_trie_changes": <whether to store TrieChanges column need for garbage collection>, "store": { "path": <path to hot db, relative to near home dir, "data" by default> }, "cold_store": { # description of cold db, if such is present "path": <path to cold db, relative to near home dir, "cold-data" by default> }, "split_storage": { "enable_split_storage_view_client": <whether to query cold storage in view client request, essentially making node act as archival, not just store all archival information> } } ``` Example: ```json { "archive": true, "save_trie_changes": true, "store": { "path": "hot-data", ... }, "cold_store": { "path": "cold-data", ... }, "split_storage": { "enable_split_storage_view_client": true }, ... } ``` ## Using Pagoda-provided S3 split-storage snapshots {#S3 migration} 1. Find latest snapshot ```bash chain=testnet/mainnet aws s3 --no-sign-request cp s3://near-protocol-public/backups/$chain/archive/latest_split_storage . latest=$(cat latest_split_storage) ``` 2. Download cold and hot databases ```bash NEAR_HOME=/home/ubuntu/.near aws s3 --no-sign-request cp --recursive s3://near-protocol-public/backups/$chain/archive/$latest/ $NEAR_HOME ``` This will download cold database to `$NEAR_HOME/cold-data`, and hot database to `$NEAR_HOME/hot-data` 3. Make changes to your config.json ```bash cat <<< $(jq '.save_trie_changes = true | .cold_store = .store | .cold_store.path = "cold-data" | .store.path = "hot-data" | .split_storage.enable_split_storage_view_client = true' $NEAR_HOME/config.json) > $NEAR_HOME/config.json ``` 4. Restart the node ### If your node is out of sync after restarting from the latest snapshot {#syncing node} Downloading the cold database can take a long time (days). In this time your database can become very far behind the chain. You may wait for your node to catchup, but it still can take a long time. One alternative approach is to sync up your node by only downloading fresh hot database, and let the neard binary do the work of bringing cold database up to speed. Another option is to use an rpc database instead of hot. You will need to run some extra commands, but you will have database options (as rpc dbs are uploaded twice a day) and can sync up faster. This process should make your node "jump" to the head of a new snapshot. Your cold database will need some time to copy everything new from the fresh hot database. If after a day your node is still not in sync, you can repeat the process. #### Fast-forward node via downloading fresh hot database {#hot fast forward} 1. Check the head of cold database (your node has to be running for this step) ```bash curl --silent 0.0.0.0:3030/metrics | grep cold_head_height ``` 2. Check the time of creation of this block in any explorer of your choice 3. Check available split storage snapshots ```bash chain=testnet/mainnet aws s3 --no-sign-request ls s3://near-protocol-public/backups/$chain/archive/ ``` This list contains both split storage snapshots and legacy archival snapshots. To check that some snapshot is for split storage run ```bash timestamp=<snapshot timestamp> aws s3 --no-sign-request ls s3://near-protocol-public/backups/$chain/archive/$timestamp/ | head -n3 ``` If the snapshot is for legacy node, you should see some sst files. If the snapshot is for split storage node, you should see ```bash PRE cold-data/ PRE hot-data/ ``` 4. Select split storage snapshot with a timestamp roughly 48 hours after the time of creation of the cold head block. 5. Stop your node. 6. Replace your local database with hot database from selected snapshot ```bash NEAR_HOME=/home/ubuntu/.near HOT_DATA=$NEAR_HOME/hot-data rm -r $HOT_DATA aws s3 --no-sign-request cp --recursive s3://near-protocol-public/backups/$chain/archive/$timestamp/hot-data $HOT_DATA ``` 7. Restart your node. 8. Check that head of the cold database is progressing ```bash for i in {0..5} do curl --silent 0.0.0.0:3030/metrics | grep cold_head_height sleep 60` done ``` #### Fast-forward node via downloading fresh rpc database {#rpc fast forward} 1. Check the head of cold database (your node has to be running for this step) ```bash curl --silent 0.0.0.0:3030/metrics | grep cold_head_height ``` 2. Check the time of creation of this block in any explorer of your choice 3. Check available rpc snapshots ```bash chain=testnet/mainnet aws s3 --no-sign-request ls s3://near-protocol-public/backups/$chain/rpc/ ``` 4. Select rpc snapshot with a timestamp roughly 48 hours after the time of creation of the cold head block. Or use any snapshot that fully covers the epoch of cold head. For public snapshot 48 hours used as 12h * (5 - 1), because we roughly estimate an epoch to last 12 hours, and the snapshot nodes are set up to keep 5 epochs. If you have some rpc snapshot that keeps 10 epochs, for example, you may use it if it's head was created ~4.5 days after cold head. If your snapshot is incompatible with your cold database you are going to see it during the last step, because in that case cold head would not increase (or even wouldn't be present in logs). 5. Stop your node. 6. Replace your local database with rpc database snapshot ```bash NEAR_HOME=/home/ubuntu/.near HOT_DATA=$NEAR_HOME/hot-data rm -r $HOT_DATA aws s3 --no-sign-request cp --recursive s3://near-protocol-public/backups/$chain/rpc/$timestamp/ $HOT_DATA ``` 7. Turn an rpc snapshot into a hot snapshot. All you need to do is change the `DbKind` of the database. This can be done with ```bash NEAR_HOME=/home/ubuntu/.near CONFIG=$NEAR_HOME/config.json CONFIG_BKP=$NEAR_HOME/config.json.backup cp $CONFIG $CONFIG_BKP # preserving your old config cat <<< $(jq '.cold_store = null | .archive = false' $CONFIG) > $CONFIG # adjust config to open hot-data as rpc db ./neard --home $NEAR_HOME database change-db-kind --new-kind Hot change-hot # change DbKind of hot-data to Hot cp $CONFIG_BKP $CONFIG # return original config ``` 8. Restart your node. 9. Check that head of the cold database is progressing ```bash for i in {0..5} do curl --silent 0.0.0.0:3030/metrics | grep cold_head_height sleep 60` done ``` ## Doing the migration manually (based on an S3 RPC snapshot or your own node) {#manual migration} Note: We prepared an optimistic migration script that we have used several times to migrate our nodes. It follows a second scenario of using manual migration + S3 snapshots. https://github.com/near/nearcore/blob/master/scripts/split_storage_migration.sh This script relies on our internal infrastructure, you can find a list of assumptions commented at the top of the file. We do not recommend using this script as is, but it is a good reference point. To perform a manual migration you first need to decide whether you can afford the node being out of sync. If not, you should set up a second non-archival (rpc) node and increase its `gc_num_epochs_to_keep` to 100 (this is just an example of a ridiculously large number). The second node will now stop performing garbage collection, and its storage size will grow. This is needed for smooth transition between legacy archival storage and split storage. 1. If you decided to use your own node to support migration, set up an RPC node with `gc_num_epochs_to_keep` set to 100. 2. Next steps concern your archival node. Enable `save_trie_changes` in Neard configuration json. ```bash NEAR_HOME=/home/ubuntu/.near cp $NEAR_HOME/config.json $NEAR_HOME/config.json.bkp1 cat <<< $(jq '.save_trie_changes = true' $NEAR_HOME/config.json) > $NEAR_HOME/config.json ``` 3. Restart neard 4. Verify neard started fine with the new config option enabled. 5. Wait at least 100 new blocks to be produced. 6. Setup cold storage configuration json part and set the path to desired location. Note that `.cold_store.path` value should be relative to `$NEAR_HOME`, so in example below the path used by neard for cold-storage is `/home/ubuntu/.near/cold-data`. Command: ```bash NEAR_HOME=/home/ubuntu/.near cp $NEAR_HOME/config.json $NEAR_HOME/config.json.bkp2 cat <<< $(jq '.cold_store = .store | .cold_store.path = "cold-data"' $NEAR_HOME/config.json) > $NEAR_HOME/config.json ``` 7. Restart neard. This will trigger the cold database migration process. 8. Verify neard started fine with the new config option enabled. 9. Wait enough time for the migration to complete. **This migration takes several days.** Ensure that neard is not restarted because the migration process cannot resume and all progress made so far will be lost. During migration you'll be seeing high cold disk usage because effectively we are moving data from archival db to cold storage. Some useful command to check the progress: ```bash curl --silent 0.0.0.0:3030/metrics | grep near_cold_migration_initial_writes_time_count ``` Most of the time is spent on `State` column migration. Each other column should migrate in hours. To check on per-column progress look at `near_cold_migration_initial_writes` metric. ```bash curl --silent 0.0.0.0:3030/metrics | grep near_cold_migration_initial_writes ``` It appears when the process starts migrating a specific column, and stops growing for that column when the column migration is finished. 10. Once the migration process is complete, the disk usage will decrease and `cold_head_height` value will surface in node metrics and will continue to increase. This means that initial migration is over and you can safely restart the node. ```bash curl --silent 0.0.0.0:3030/metrics | grep cold_head_height ``` 11. Stop neard process. 12. If you set up your own RPC node, stop it and download its database to the hot data folder in `$NEAR_HOME`. Otherwise, download a fresh RPC DB backup to the hot data folder in `$NEAR_HOME`. 13. This step relies on your hot database and your cold database having blocks in common. If you properly set up your own RPC node as the first step, this should be true. If you are using S3 snapshot, the condition might not hold. In this case, this step will fail. You will need to restart the neard process and wait until the `cold_head_height` metric reports large enough value indicating the overlap between cold and hot databases. This command will open two dbs specified in your config file, plus additional db provided in the command line. It will check that db provided in the command line is compatible with the current storage and can be used as a replacement hot database, and make some adjustments. ```bash NEAR_HOME=/home/ubuntu/.near /home/ubuntu/neard --home $NEAR_HOME cold-store prepare-hot --store-relative-path='hot-data' ``` 14. Set the hot database path and enable split storage in neard configuration file ```bash NEAR_HOME=/home/ubuntu/.near cp $NEAR_HOME/config.json $NEAR_HOME/config.json.bkp3 cat <<< $(jq '.store.path = "hot-data" | .split_storage.enable_split_storage_view_client = true' $NEAR_HOME/config.json) > $NEAR_HOME/config.json ``` 15. Restart neard. If you chose to use S3 snapshot to initialize the hot database, your node may be out of sync for a while, due to your hot database becoming out-of-date, while you were waiting for cold head to increase enough. Verify neard started fine with the new config option enabled. You can also post a request about split storage status and check that `.result.hot_db_kind` is `Hot`. ```bash curl -H "Content-Type: application/json" -X POST --data '{"jsonrpc":"2.0","method":"EXPERIMENTAL_split_storage_info","params":[],"id":"dontcare"}' 0.0.0.0:3030 ``` ## Important metrics {#metrics} The metrics below can be used to monitor the way split storage works `near_cold_head_height` – height of cold storage. `near_block_height_head` – height of hot storage. These two metrics should be very close to each other. `near_rocksdb_live_sst_files_size` – size of column in hot storage. `near_rocksdb_live_sst_files_size_cold` – size of column in cold storage. `near_cold_store_copy_result` – status of the continuous block-by-block migration that is performed in background to block production and can be interrupted. Size of the hot db – should be close to the size of an RPC node’s storage. Size of the cold db – should be close to the size of a legacy archival node’s storage.
NEAR at ETHCC Highlights: Sustainability and the BOS Take Center Stage in Paris UNCATEGORIZED July 20, 2023 Missed out on NEAR’s rendezvous at ETHCC 2023 in Paris? No need to worry. In this roundup, all NEAR enthusiasts can catch up on the enlightening presentations by BOS, Web3, and blockchain experts. You’re in the perfect place to delve into notable announcements made during the conference, from NEAR signing up to the Ethereum Climate Platform to an epic new interactive Polygon zkEVM app dashboard. ICYMI, it’s time to dive into all the key speeches, events, and announcements that unfolded in the City of Lights over this past weekend. Interactive Polygon zkEVM app dashboard launches on the BOS In the most significant partnership announcement of ETHCC, an interactive Polygon zkEVM app dashboard has launched on the Blockchain Operating System (BOS). This integration will not only increase accessibility and discoverability for zkEVM developers and users on the open web but also vastly improve user experience. The collaboration is set to accelerate the creation of dApps that will onboard billions of users into the open web. The new Polygon zkEVM dashboard now combines the benefits of zero-knowledge technology with the power of the BOS to unlock even more seamless onboarding to the open web. The dashboard brings a new suite of zero knowledge development capabilities to zkEVM developers and lets them build apps that can reach more users from day one. It’s a groundbreaking partnership that brings together the NEAR and Polygon ecosystems, two of the most innovative names in Ethereum and blockchain scalability. NEAR makes waves with sustainability commitment NEAR Foundation made a significant stride in its commitment to Web3 sustainability. As part of its ongoing efforts, NEAR signed up to the Ethereum Climate Platform, demonstrating its resolve towards minimizing the environmental impact of Web3 development. This move aligns with NEAR’s ethos and commitment to sustainable and scalable blockchain solutions. Marieke storms the BOS-tille at “Funding the Commons” Adding to the list of notable NEAR occurrences during ETHCC, NEAR Foundation CEO, Marieke Flament, was a keynote speaker at the “Funding the Commons” event held at Sorbonne Université on July 15. Marike’s message was one of bringing more ethics and equity to the entire blockchain and Web3 ecosystem. In her speech, titled “The Open Web is NEAR: How the BOS, NDC, and DAOs are creating a Decentralized Web,” Marieke explored how NEAR Foundation serves the ecosystem by building public goods like the BOS, DevHub, NDC, DAOs, and more. “Funding the Commons” is an event designed to complement the Ethereum Community Conference, promoting connection amongst participants, and fostering new collaborations and projects. The event organizers also planned a dinner on July 15 at Le Procope Paris, where Marieke was among the most notable invited guests. Unpacking Insights: notable talks and events at ETH CC Near @ ETHCC wasn’t just a gathering of blockchain enthusiasts, but a hotbed of innovative discussions. Illia Polosukhin, co-founder of NEAR, and Nadir Dabit’s conversation around decentralized social networks piqued particular interest. They hinted at a shift in how we’ll connect and share information in the future and the potential role of decentralized social on the BOS. Matt Stephenson, head of crypto economics at crypto investment firm, Pantera Capital, took the audience on a thrilling Day Two journey through the intricacies of behavioral game theory. He showcased how game theory could be leveraged in this space, offering a unique lens to examine, understand, and potentially predict blockchain trends. Near @ ETHCC didn’t skimp on forward-looking conversations either. A panel featuring Max Mersch of Fabric Ventures, Maggie Love from SheFi, and Bilal El Alamy of PyratzLabs posed a pertinent question: “What’s the Next Big Use Case Being Built in the Bear Market?” Each speaker provided valuable insight about both challenges and opportunities posed by bear markets. Ecosystem Updates Despite the focus on the Near @ ETHCC side event itself, the NEAR ecosystem saw significant developments and milestones during the past few days. The NEAR Digital Collective’s I-AM-HUMAN movement has crossed 2,000 members in the NEAR ecosystem. The initiative allows users to vote, elect candidates for office, and shape the future of NEAR. You can sign up here. MintbaseSearch has gone live on NEAR mainnet along with its own ChatGPT plugin. Mintbase now enables users to ask anything about NFTs on the NEAR Protocol. More details here. Opolis has raised $6.6M in a bridge fundraising round with support from NEAR Foundation, Polygon Ventures, and Draper Capital. Read more details about the full announcement here. Black Snow: Battle For Earth, launched its demo version, offering an exciting free-to-play-and-earn experience that aims to enhance the NEAR ecosystem by boosting user count and transactions. Check out the demo here C’est la vie in Paris as ETHCC 2023 wraps up. As we reflect on these dynamic days, it’s clear that the future of NEAR and the BOS is exciting and full of potential. From environmental commitments to bold collaborations and fascinating talks, NEAR’s Parisian journey was full of engagement, enlightenment, and enthusiasm for everyone involved.
--- description: A guide to staking on NEAR. title: Staking Guide sidebar_position: 5 --- --- Staking allows you to earn NEAR rewards in return for delegating your tokens with a validator. This is an essential process in Proof-of-Stake (PoS) blockchains which is required to ensure security and decentralization. Staking is an important aspect of blockchains with a Proof-of-Stake mechanism, like NEAR. Proof-of-Stake (PoS) is a consensus mechanism to determine which users get to create new blocks on the NEAR blockchain. New block creators are selected by the amount of NEAR they’ve locked-up in the network. In the NEAR network, a decentralized pool of validators keeps the network secure by processing transactions and in return these validators receive a reward. ## Staking on NEAR Validators are pieces of hardware, ran by individuals, groups, or organizations, which serve to secure, maintain, and run the NEAR blockchain. Delegators are those who commit their NEAR to a validator to assist in securing the network and to earn rewards in the process. Potential validators should have between three and five years of system administration, performance and monitoring experience as well as familiarity with open source software. To learn how to set up a validator node, have a look at our [Validator BootCamp](https://near-nodes.io/validator/validator-bootcamp). The number of seats for validators is limited, so most people who stake on NEAR are delegators. Delegators are entities who provide security for NEAR by delegating their tokens to validators. This empowers members of the NEAR community to provide security to the network without becoming a validator. When you delegate your NEAR to a validator, you receive a percentage of their reward. This is what is commonly referred to as "Staking". ## How to Stake You can use [My NEAR Wallet](https://app.mynearwallet.com/) to stake your NEAR. Choose the `Staking` tab in the navigation menu. This screen shows you how much NEAR you currently have staked, how much you have earned in NEAR rewards from staking, and where you're NEAR is staked. Choose the `Stake My Tokens` button to start staking your NEAR. ![Staking tab](@site/static/img/staking1.png) You'll be able to choose a validator pool to stake your tokens with. Different pools charge different fees, and the fee is a percentage of your staking rewards. ![Choose pool](@site/static/img/staking2.png) After selecting a pool, you'll see: - The validator fee - A summary of how much you already have staked with that particular pool - The amount of NEAR rewards you've earned with that pool - How much you can withdraw from that pool If this is the first time you're staking with a particular pool, you won't have any rewards earned from them yet. When you're satisfied with your choice, click the `Stake with Validator` button. ![Pool summary](@site/static/img/staking3.png) Next, you can choose how much you'd like to stake with the validator pool. ![Staking page](@site/static/img/staking5.png) Finally, you'll have a success screen confirming that you've staked your NEAR with a validator pool. ![Staking success](@site/static/img/staking7.png) The staking tab will now be updated to show how much you have staked in total, and which validator pools you've staked your NEAR with. When you earn rewards, you'll also be able to see how much you have earned in NEAR here. ![Staking overview update](@site/static/img/staking8.png) ## Unstaking Your NEAR You can also unstake your NEAR from the `Staking` tab. When you'd like to unstake your NEAR, start by clicking the `Unstake` button. ![Staking Overview](@site/static/img/Unstaking1.png) The next screen will show you which validator pools you're currently staking your NEAR with. Choose the validator you want to unstake your NEAR from. ![Unstake from validator page](@site/static/img/Unstaking2.png) Next, choose the amount of NEAR you'd like to unstake from the validator and click `Unstake Tokens`. ![Unstake tokens page](@site/static/img/Unstaking3.png) Finally, confirm the amount of NEAR you're unstaking. This screen also tells you how long you'll need to wait for the NEAR you've unstaked to become available in your wallet. Unstaked tokens will be made available pending a release period of ~52-65hrs (4 epochs). ![Unstake confirmation page](@site/static/img/Unstaking4.png) You'll now see a success page to let you know your NEAR is being unstaked. ![Unstake success page](@site/static/img/Unstaking5.png) You can keep track of how much NEAR you have available, and how much is still being unstaked in the `Staking` tab. ![Staking tab with pending transaction](@site/static/img/Unstaking6.png) Next, let's take a look at how to find validators to stake with. ## Finding Validators The staking pool currently allows validators to choose what fee they charge on the rewards earned by their staking pools. There are several community-run validator lists that detail who they are, how much stake they have, and other information. These can help inform where you delegate your tokens. It's important to do your own due diligence before any transaction, including delegating your NEAR. | Operator | URL (to copy and paste) | | ------------------ | ---------------------------------------------------------------------------------------------------------- | | NEAR Explorer | [https://explorer.near.org/nodes/validators](https://explorer.near.org/nodes/validators) | | DokiaCapital | [https://staking.dokia.cloud/staking/near/validators](https://staking.dokia.cloud/staking/near/validators) | | Stardust NEAR Pool | [https://near-staking.com/](https://near-staking.com) | ## Liquid Staking Staking on PoS networks like NEAR means that your tokens are "locked", so you won't be able to transfer or use them for any other purpose while they are staked. This can present a dilemma for users who want to stake their NEAR, but also want to use their NEAR for other purposes. That's where liquid staking comes in. Liquid staking allows you to use your staked assets in other activities so that you can benefit from staking rewards, and other on-chain activities. The number of liquid staking solutions is always growing, check out the community-run resource [AwesomeNEAR](https://awesomenear.com/) to find them.
Octopus Network Partners with NEAR COMMUNITY March 17, 2021 The NEAR Ecosystem is excited to welcome Octopus Network onto NEAR Protocol. As a decentralized appchain network, Octopus Network inaugurates a new frontier of innovation on NEAR Protocol for the hundreds of developers and entrepreneurs looking to launch applications on their own blockchain. Notably, the NEAR Foundation has reached an agreement with the Octopus Foundation to invest one million dollars, so as to become Octopus Network’s exclusive strategic investor. While Octopus Network has tested out multiple Layer 1 blockchains including Cosmos, Polkadot, and others, they have selected NEAR to be the ‘mother-chain’ of the network. Faster than Cosmos Chains, and more affordable and scalable than Polkadot ‘Parachains’, NEAR Protocol welcomes the Octopus Team and the multiple communities interested in launching appchains on Octopus Network! A New Frontier of Innovation on NEAR Protocol: Octopus Appchains Octopus Network Relay will launch as a smart contract on NEAR to provide a foundational infrastructure for a validator marketplace between validators, and appchains launched through Octopus. As a home for developers and entrepreneurs looking to launch their own blockchain with customizable crypto-economic and governance parameters, Octopus Network provides affordable and easy integration with NEAR. In line with this design, Octopus Network is built around the OCT Token: A fungible, non-inflationary utility token, that is required for staking on different appchains built on top of the protocol. Validators secure Octopus appchains in return for appchain’s native token rewards. “Octopus provides out-of-the-box security, interoperability, and on-chain governance to projects looking to create a specific chain for their application.” Economically: Validators stake OCT Tokens to earn rewards from the respective application chains on Octopus Network. OCT Tokens are non-inflatable., Governance: OCT Token holders do not partake in the governance of different application-chains: That opportunity is left to native token holders of the respective chain. In the long term, Octopus Network will function as a composable means by which applications can operate with different security parameters on NEAR: Some applications may not need such high security from validators in order to prosper, while others may require more over time. Octopus Network effectively allows for developers on NEAR to quickly spin-up applications with low security in a cost-effective manner and with respect to unique crypto-economic or governance parameters. Illia Polosukhin, Co-Founder of NEAR commented: “NEAR’s vision is to give people control of their money, data and power of governance. To do that NEAR is building and funding various efforts for developers to build applications with such properties. Octopus’ multi-chain network architecture allows developers to cheaply and easily spin up self governed app chains. Unlocking use cases which normally wouldn’t be a good fit for a shared smart contract platform. It’s exciting to closely partner with the Octopus team, who have been working on multi-chain interoperability for the past few years to bring this to reality.” Notably, the team behind Octopus Network is exceptionally talented and experienced in both crypto and mainstream software development: With a team of eight engineers, they have successfully built IBC for Substrate, and also offered the initial Substrate online training course in China with other Substrate enthusiasts (from which a number of projects have originated from). Most notably, they are also active participants and co-organizers of the Rust community in China (they actively organize RustCon in China). Octopus Network: “We’re excited to form a strategic partnership with NEAR Protocol. NEAR has been widely recognized as one of the best technical teams in the whole blockchain space.” said Louis Liu, founder of Octopus Network. “Sharding, layer 2, and multi-chains are the most promising potential architectures of next generation blockchains, each having unique value and advantages over the others. The future of the blockchain universe will most likely involve all these architectures which will coexist with each other. NEAR Protocol has been in the leading position of homogeneous sharding protocols. By teaming with NEAR, Octopus could launch a novel multi-chains network in 2021, which provides unprecedented flexible cost effective shared security and interoperability to appchains. By leveraging a prosperous and sustainable appchain ecosystem together with partners, Octopus Network has the potential to take the lead in multi-chain direction.” With appchains deployed on NEAR through Octopus Network, a world of new applications, crypto-economic models, governance mechanisms and decentralized solutions are poised to launch on NEAR Protocol. About NEAR Protocol: NEAR exists to to accelerate the world’s transition to open technologies by growing and enabling a community of developers and creators. 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. If you’re a developer who wants to see what building on NEAR is all about, check out the NEAR documentation to get started. If you want to be part of the NEAR community, join our Discord or Telegram channels or follow NEAR on Twitter. About Octopus Network: Octopus Network is a decentralized appchain network natively built on NEAR Protocol. Octopus provides out-of-the-box security, interoperability, and on-chain governance to projects looking to create a specific chain for their open web application. The Octopus Network Relay runs as a smart contract on NEAR Protocol, provides the infrastructure for a validator marketplace between validators, and Octopus appchains. Built around the $OCT Token – a fungible, non-inflationary utility token – Octopus allows for flexible security, and autonomous governance for any application looking to launch their own appchain. . Visit Octopus on their website, say hello via their Twitter, or see the BUIDL on Github . You can also read news on their Medium and check out their Discord server.
--- title: 6.1 Theory and Evolution of the Metaverse description: Moving from a 2D to 3D interface for the internet --- # 6.1 Theory and Evolution of the Metaverse The metaverse as a topic is often the subject of much confusion and misunderstanding. The goal of this first lecture is to come to a clear and concise picture of what we mean, when we talk about a ‘Metaverse’. This requires first and foremost, an understanding as to the presuppositions underlying the Metaverse. From that, we can get into the nitty-gritty of different types of Metaverses and how they are poised to evolve into the future. ## Presuppositions: Crypto and the Metaverse In order to properly understand the metaverse, we need to start with the idea of _digitization_ and the increase in the world of bits. Since the early 2000s, the world has begun a process of digitizing: What started with basic information, expanded to the likes of streaming services and content, social media, gaming, and now value itself through the crypto-currency revolution. As these processes have unfolded, people have spent more and more time living in ‘digital worlds’. This is the basis for understanding crypto - from a high level, and consequently, the metaverse. **Crypto:** Is the domain of ownership in the digital world. Such ownership can be tangible (money, commodities, and other types of fungible value), as well as intangible (non-fungible value). Crypto is the mechanism by which value is attached to the digital world - on its own - and not reliant on any physical entity or institution. **The Metaverse:** The metaverse is the domain of _user experience of the digital world._ This refers to how we as people are able to interact digitally, - with one another, different products, and the internet itself. With the metaverse, we are challenged to imagine what ‘living inside a digital world’ might look like. To fully understand this, lets look at some quotes from Crypto-Punks podcast with a16z (referenced in our lecture on NFTs): _“The internet is becoming more immersive and more integrated. And we will be spending more time there. In which case we will want to have our stuff there.”_ In tandem with spending more time in the digital realm, we are in the process of transitioning from a localized and segregated internet, to a global and unified internet. This the second major presupposition underlying the rollout of the metaverse: _“The Metaverse is going to be the interim but with better visualization, augmented mixed reality. The field of vision will include mostly the world around you, and some digital objects. So one is better visualization, and the second is persistent digital objects. I have persistent cross-application digital objects on LinkedIn that are not cross-application or interoperable. If I want to make it interoperable I need to get an API key. Whereas a single contract can represent everything on-chain. Any number of thousands of different things you will be able to do with a crypto-punk in 5 to 10 years. The value here is that it is interoperable. The metaverse is the internet with better visualization and persistent digital interoperable objects. (13:05)”_ This is to say, crypto is intricately tied to the metaverse: The objects of the digital world are transitioning from fully centralized and connected to the outside world, to semi-centralized, with pockets of value living on their own. In a similar vein, interfacing with the digital world is moving from siloed, site by site exploration, to uniform and aggregated visualization. In short, the internet is moving from 2D to 3D: And the 3D interface is known as the Metaverse. To be crystal clear we could say the following: _As we digitize more of our world, we find ourselves ‘living online’ more and more. The Metaverse refers to the aggregated interface for interacting with the host of digital systems living on the internet. It is primarily an enhancement of visualization and experience combined with interoperable objects - living across digital systems of the internet._ Put more concisely [by Metaversed.net:](https://metaversed.net/) “_The[ Metaverse](https://en.wikipedia.org/wiki/Metaverse): a persistent, live digital universe that affords individuals a sense of agency, social presence, and shared spatial awareness, along with the ability to participate in an extensive virtual economy with profound societal impact.”_ ### Public or Private? With this loose definition, we can now begin to discuss one of the more controversial and confusing aspects of the Metaverse: Namely, a distinction between the _metaverse_ as an open-public, and decentralized concept - and _virtual worlds_, as private, closed, and centralized experiences. With private companies like Facebook rebranding themselves to _Meta_ and virtual reality (through Augmented Reality headsets) becoming familiar, it is easy to confuse virtual worlds with the Metaverse. To a certain extent this becomes a pedantic argument of terms - but for our context - we will follow a16z, in differentiating between _a Metaverse_ and a _Virtual World_ based upon its primary attribute of either being _open_ or _closed._ ![](@site/static/img/bootcamp/mod-em-6.1.1.png) As the framework above explicates, the _theory_ underlying the development of a metaverse, centers on the notion of it being _open._ Specifically, this means that it would be blockchain-denominated, as all other software systems would require a central entity in charge of governing the ‘rules’ of the interface - while crypto can be governed via smart contract and token based incentives. Hence, the primary distinction of a metaverse, is the following: _A Metaverse is an open-decentralized and public interface, for interacting with digital reality. A Virtual World, is a closed-centralized and private interface, for interacting with digital reality._ The challenge underlying this distinction centers on the fact that both of these concepts are largely _theoretical._ No one has built a scalable or widely adopted metaverse or virtual world - specifically one that is not itself a game. ## Features of the Metaverse, Or A Framework For Living Digitally With this premature distinction in mind, let’s address the primary features of a metaverse, to get a better intuition surrounding ‘what’ role the Metaverse plays. * **Property Rights**: Just as in the physical world there is a notion of land ownership or possession, such is the same in the Metaverse. Once more the premise of moving our realities online is increasingly the theory undergirding the drive in value of metaverse property (see our next lecture specifically on this topic). * **Self-Sovereign Identity:** Proving who someone is, functions as the basis of building up a history of behavior for that account, and inadvertently a reputation as well. A Metaverse, unlike a Virtual World, would allow the user to control their identity, without having their data harvested by a private corporation. * **Composable Infrastructure:** Meaning a technical design, that would allow creators to collaboratively build value into the Metaverse. As the quote below explains, the Metaverse is a middle ground between some of the innovation in gaming, and some of the convenience of Fintech services. Living on-chain means that users can act as creators, and others can share in the creativity and value creation present. _“To feature [composability](https://future.com/how-composability-unlocks-crypto-and-everything-else/) — a concept closely intertwined with interoperability — a metaverse would have to offer high quality, and open, technical standards as a foundation. In games like Minecraft and Roblox, you can build digital goods and new experiences out of the basic components supplied by the system, but it’s harder to move them outside that context or modify their inner workings. Companies offering embeddable services, like Stripe for payments or Twilio for communications, work across websites and apps — but they don’t allow outside developers to change or remix their black boxes of code.” ([a16z](https://future.com/7-essential-ingredients-of-a-metaverse/))_ * **dApp Integrations:** Offering services and activities in a Metaverse, requires third-parties, building, leasing, selling, and interacting with one another. Like blockchain ecosystems, providing the basic infrastructure for dApps to create value, a Metaverse is a specific front-end from which these dApps can also participate in the same world, user-base, activities, and incentives. * **Community Ownership:** Crypto-economics goes hand and hand with open-source, value denominated infrastructure. Community governance does as well. In this sense, Community Ownership encompasses both governance of a metaverse, as well as the monetary system built into that metaverse. This list is not exhaustive, but it should help paint a picture of what we mean when we say _‘Metaverse’_. We are referring to an immersive digital space - primarily via screen and eventually via headset or hardware immersion - from which uniquely identifiable users (could also call them ‘characters’) interact, and ‘live’ in a massive digital reality (world, with property), that is grounded with a set system of governance, economics, and sociality. While thrown around often, a _Metaverse_ is not a simple concept. ## The Metaverse and the Crypto Product Stack We are here after all to learn about crypto and the internet of value. So to fully-conceptualize what a Metaverse is, let’s dip into the role that the Metaverse plays in the crypto product stack. We can summarize this, as four separate potentials - that ideally - harmonize to create a ‘flywheel’ of users and value. * **The Business Potential for the Metaverse**. If the metaverse purports to allow users to ‘Live’ digitally, the business potential of the Metaverse is to offer users items, services, and experiences, similar to what they might be able to expect in the real world. From clothes, to items, to property, to generation services, there is a unique opportunity for existing brands to cross-launch items in the Metaverse (think Nike), and in tandem, Metaverse native companies to launch Brands digitally, before moving into the physical domain. Non-fungible tokenization and fungible tokenization play a prominent role here. * **The dApp potential of the metaverse:** For dApp creators in different blockchain ecosystems, a robust metaverse offers a simple home to jumpstart users from that ecosystem. This means that new games, new financial services, and new communities, can leverage an active metaverse to participate and grow themselves through a mature and active community. * **The Composable potential of the metaverse:** Within and beyond crypto, the Metaverse has the potential to allow for composability to exist across applications. Presupposing that there are dApps integrated with the Metaverse, a game might allow an in-game item to leave the game-world, and to translate into the larger Metaverse it is collaborating with. That item could then be used inside of a second game also connected to that Metaverse. The same concept would apply to coupon incentives leveraged by a company in one dApp, that could likewise translate over to another dApp. * **The Social potential of the metaverse:** At root, much of the existing growth in PFP communities in crypto, is based on socialization - via Twitter or another platform, such that it makes the discord or group look appealing to be a part of. An established Metaverse creates a home base, from which different communities can leverage social reputations, establish skills and expertise, engage in activities with one another, and share in collaborative value creation. At its best the Metaverse is the ‘glue’ of digital reality, that holds together the different independent objects, users, dApps, and services, that the on-chain world purports to bring to the world of internet users. ## The tech tree evolution of the metaverse: Too soon? As we close our initial overview of the Metaverse, we need to seriously consider the following question: _If all Metaverses’ presuppose notions such as sovereign identity, public and private property, composable value creation between dApps, community involvement, as well as some form of social immersion, AND much of crypto today is barely live - value creation in itself is in its earliest stages, identity remains unknown to many, and communities form sporadically and temporarily - considering all of these factors - is it too soon to talk about a scalable Metaverse? More importantly, is there a risk that a player like Meta, successfully uses their existing users on Facebook, Whataspp and Instagram, to cultivate a synthetic virtual world under the guise of it being a Metaverse?_ To close out, lets look at the ‘tech tree’ for a crypto-denominated Metaverse, and then talk about hybrid concepts between a Metaverse and Virtual World that may emerge sooner: ## The Tech Tree for a Metaverse Active users, value producing dApps, unique identifiers for users (identity), scalable infrastructure for transacting between users in the metaverse (high transaction throughput), an ecosystem of events, incentives, services, and tokens, as well as a well-designed and community governed economic system - are all required for a successful metaverse. Today, perhaps the only blockchain ecosystem mature enough for such capacities would be Ethereum - except the cost of transaction on the native network would eliminate it from realistically being used. All other ecosystems, first need to focus on the following: * Active Users. * Revenue Producing or Value Accruing dApps. * DAO infrastructure. * Communities of Diverse Tastes and Interests. * An ecosystem wide account model, used by all users such that they can reliably build an identity around a specific account. Interestingly, when we look at this from the perspective of a private corporation like _Meta_ moving into the Metaverse / Virtual Reality space, they already possess the active users and communities of diverse tastes and interests - missing are the unique identifiers, and composable integrations with other service providers on their platform. Massive games, meanwhile, may already possess a world, active users, and communities, but would need to expand ‘out of game’ in order to accommodate a broader set of services and potential users. Based upon the current state of crypto, it's fair to say that it will be a number of years before a robust metaverse grows and scales to the point of becoming ‘complete’. Nevertheless, as we will see in the proceeding lecture, the starting basis for these early stage projects centers upon the ‘reality’ component of the metaverse specifically in relation to digital property, digital worlds, and in-world items and objects that can be utilized or created, to offer optionality to future users.
Community Update – Beyond Launch COMMUNITY October 27, 2020 Hello citizens of NEARverse! This is NiMA coming to you from a NEARby planet in the Milky Chain … We have collectively voted to remove the training wheels from the NEAR blockchain and are now in the post-launch phase. The fate of NEAR is now in the hands of the NEAR community. Validators, token holders, users, and builders all play a significant role in what happens next … … which is why we would like to invite every single one of you to join us in the next NEAR Community Town Hall on Nov 2nd on Hopin! NEAR Core team members will share updates about our NEAR-term roadmap, wallet and staking, projects building on NEAR, and tons of cool stuff from our community of Guilds and Hackathon participants. You will also be able to interact directly with other community members in breakout sessions and find out how YOU can contribute to the NEAR ecosystem 🚀 The breakout sessions will be the following (happening in parallel): Deep Tech – lead and moderated by Illia and AlexS (NEAR co-founders) Wallet and Staking – moderated by Kendall Cole with participation from validators Guilds and Hack the Rainbow – moderated by Dani and NiMA (dev community team) Don’t forget to sign up for NEAR Town Hall here on Hopin 🙌 Balancer BUIDLing on NEAR Automated Market Makers (aka AMMs) are one of the core building blocks of any open finance platform. We are partnering with Balancer to provide builders on NEAR with the best tools to power their DeFi projects. Balancer is more than just a DEX. In addition to basic DEX functionalities, Balancer can also be used for creating and managing self-balancing smart index funds, fair token launches, and much more. You can read more about our collaboration and the two bounties powering Balancer on NEAR here on our blog! Hack the Rainbow Winners! Hack the Rainbow was NEAR’s first MOOH (Massive Open Online Hackathon). The event challenged community members to use the Rainbow Bridge to utilize Ethereum assets on NEAR—a fast, scalable, and low-cost environment. More than 400 participants and 80 projects from 18 countries around the world were submitted! Meet the winners. Development Updates: Stakewars is ending, but we have other exciting opportunities for you: https://pages.near.org/blog/stake-wars-is-over-but-were-just-getting-started/ Inflationary reward are live on NEAR: https://pages.near.org/blog/staking-rewards-are-live/ Vincent, one of our Hack the Rainbow hackers, write about bridging NFTs from Ethereum to NEAR: https://medium.com/@vince0656/bridging-ethereum-nfts-to-near-505a272ec949 Engineering updates: We have significantly reduced our memory footprint on restart We now can attribute and measure memory usage by all of our Rust code We made some improvements to our archival nodes (1 and2) We decided to not micro-optimize our gas counter for now We made improvements to how we test cross-contract calls, based on the community feedback. We have multiple new design discussions that we invite community to participate in: Discussion: Upgrade triggering mechanism. Enabling EVM Proposal: Solving state staking issue Proposal: Allowance-free safe-based token standard Bootstrapping native NEAR ecosystem Proposal: Fee upgrade process Calling all Founders! 🚀 Batch 2 applications for OWC Accelerator are now open! Our batch 1 teams have raised over $15m this year. Ready to join the collective? Apply Now: https://www.openwebcollective.com/ Details: Program Dates: Jan – Mar 2021 Program Highlights: Over 30+ mentors, 100+ VC connections and Demo Day with 300+ attendees Applicants are selected on a rolling basis. (We’ll likely find our 15 teams prior to the application deadline 12/11/20) Potential investment from OWC seed fund (launching this year!) Who Should Apply: Early startups anywhere in the world that are post-concept, prelaunch, or recently post-launch That’s it for this update. See you in the next one!
--- sidebar_position: 2 title: "Collections" --- # Collections When deciding on data structures to use for the application's data, it is important to minimize the amount of data read and written to storage, and the amount of data serialized and deserialized to minimize the cost of transactions. It is important to understand the tradeoffs of data structures in your smart contract because it can become a bottleneck as the application scales, and migrating the state to the new data structures will come at a cost. The collections within `near-sdk-js` are designed to split the data into chunks and defer reading and writing to the store until needed. These data structures will handle the low-level storage interactions and aim to have a similar API to the [native data structures in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures). It is important to keep in mind that when using collections, that each time state is loaded, all entries in the data structure will be read eagerly from storage and deserialized. This will come at a large cost for any non-trivial amount of data, so to minimize the amount of gas used the SDK collections should be used in most cases. The most up to date collections and their examples can be found [in the repository on GitHub](https://github.com/near/near-sdk-js). <!-- TODO include/update link for store module to replace collections mod when docs updated --> The following data structures that exist in the SDK are as follows: | SDK Collection | Native Equivalent | Description | | ------------------------------------- | ------------------------------- | ------------| | `Vector` | `Array` | A growable array type. The values are sharded in memory and can be used for iterable and indexable values that are dynamically sized. | | <code>LookupMap</code> | <code>Map</code> | This structure behaves as a thin wrapper around the key-value storage available to contracts. This structure does not contain any metadata about the elements in the map, so it is not iterable. | | <code>UnorderedMap</code> | <code>Map</code> | Similar to `LookupMap`, except that it stores additional data to be able to iterate through elements in the data structure. | | `LookupSet` | `Set` | A set, which is similar to `LookupMap` but without storing values, can be used for checking the unique existence of values. This structure is not iterable and can only be used for lookups. | | `UnorderedSet` | `Set` | An iterable equivalent of `LookupSet` which stores additional metadata for the elements contained in the set. | ## In-memory `Map` vs persistent `UnorderedMap` - `Map` keeps all data in memory. To access it, the contract needs to deserialize the whole map. - `UnorderedMap` keeps data in persistent storage. To access an element, you only need to deserialize this element. Use `Map` in case: - Need to iterate over all elements in the collection **in one function call**. - The number of elements is small or fixed, e.g. less than 10. Use `UnorderedMap` in case: - Need to access a limited subset of the collection, e.g. one or two elements per call. - Can't fit the collection into memory. The reason is `Map` deserializes (and serializes) the entire collection in one storage operation. Accessing the entire collection is cheaper in gas than accessing all elements through `N` storage operations. Example of `Map`: ```javascript import { NearBindgen, call, view, near } from "near-sdk-js"; @NearBindgen({}) export class StatusMessage { constructor() { this.records = new Map(); } @call({}) set_status({ message }) { let account_id = near.signerAccountId(); near.log(`${account_id} set_status with message ${message}`); this.records.set(account_id, message); } @view({}) get_status({ account_id }) { near.log(`get_status for account_id ${account_id}`); return this.records.get(account_id); } } ``` Example of `UnorderedMap`: ```javascript import { NearBindgen, call, view, near, UnorderedMap } from "near-sdk-js"; @NearBindgen({}) export class StatusMessage { constructor() { this.records = new UnorderedMap("a"); } @call({}) set_status({ message }) { let account_id = near.signerAccountId(); near.log(`${account_id} set_status with message ${message}`); this.records.set(account_id, message); } @view({}) get_status({ account_id }) { near.log(`get_status for account_id ${account_id}`); return this.records.get(account_id); } @view({}) get_all_statuses() { return this.records.toArray(); } } ``` ## Error prone patterns Because the values are not kept in memory and are lazily loaded from storage, it's important to make sure if a collection is replaced or removed, that the storage is cleared. In addition, it is important that if the collection is modified, the collection itself is updated in state because most collections will store some metadata. Some error-prone patterns to avoid that cannot be restricted at the type level are: ```javascript import { UnorderedMap, assert } from "near-sdk-js"; let m = new UnorderedMap("m"); m.insert(1, "test"); assert(m.length(), 1); assert(m.get(1), "test"); // Bug 1: Should not replace any collections without clearing state, this will reset any // metadata, such as the number of elements, leading to bugs. If you replace the collection // with something with a different prefix, it will be functional, but you will lose any // previous data and the old values will not be removed from storage. let m = new UnorderedMap("m"); assert(m.length(), 0); assert(m.get(1), "test"); // Bug 2: Should not use the same prefix as another collection // or there will be unexpected side effects. let m2 = new UnorderedMap("m"); assert(m2.length(), 0); assert(m2.get(1), "test"); ``` <!-- TODO: pagination with persistent collections in JS --> ## `LookupMap` vs `UnorderedMap` ### Functionality - `UnorderedMap` supports iteration over keys and values, and also supports pagination. Internally, it has the following structures: - a prefix value - a vector of keys - a `LookupMap` of keys and values - `LookupMap` only has a prefix, reading values to and from the contract's storage. Without a vector of keys, it doesn't have the ability to iterate over keys. ### Performance `LookupMap` has a better performance and stores less data compared to `UnorderedMap`. - `UnorderedMap` requires `2` storage reads to get the value and storage writes to insert a new entry. - `LookupMap` requires only one storage read to get the value and only one storage write to store it. ### Storage space `UnorderedMap` requires more storage for an entry compared to a `LookupMap`. - `UnorderedMap` stores the key twice (once in the first vector and once in its `LookupMap`) and value once. - `LookupMap` stores key and value once. <!-- TODO: UnorderedSet and LookUpSet -->
A NEAR Project Update in the Age of COVID COMMUNITY April 3, 2020 The base of contributors to the NEAR project has increased over the past several months and the global macro picture is obviously in chaos so I wanted to use this opportunity to provide the first of a regular series of updates on the project as a whole. I’ll start by addressing the macro environment and will then provide project-specific notes. Obviously, the star of this act is COVID-19 but it is sufficiently well-introduced that I won’t re-state the current crisis other than to say that I hope you’re safe and taking proper precautions. The Macro Environment “Only when the tide goes out do you discover who’s been swimming naked.” — Warren Buffett I run the NEAR Foundation now but my early career took a somewhat turbulent path. I joined the trading floor of a bank in New York City in mid-2007 and had a front-row seat for the global financial crisis during the following two years before joining BP Energy just in time for the Deepwater Horizon oil spill. While each crisis has its own flavor, echoes of both experiences reverberate in today’s environment. This is where luck, preparation, and strategy combine to forge the next generation of success stories and to expose the cracks in the poorly constructed foundations of others. After spending the last decade enjoying one of the longest and steadiest economic expansions in history, both people and institutions are not well set up right now to handle a deleveraging and slowdown. There has been too much yield chasing, too much operational leveraging and too much picking up speculative nickels before metaphorical bulldozers. The effects of this unwind could be felt in a series of bear waves over the next couple of years before we finally reconfigure our social, operational and financial expectations properly to handle the new macro reality. Even a V-shaped recovery will leave lasting effects because attitudes towards risk don’t shift on a dime. Some effects are obvious but worth restating: Back to “risk-off”: Risk tolerance will be reduced and the funding environment will be lean, not just for protocol projects but for all of the smaller teams that make up these ecosystems. It’s possible that massive government spending and money printing will prop up asset prices and slosh into a new bubble soon but the default reality will still be tighter. You must create tangible value: Everyone’s focus has shifted lower down on Maslow’s Hierarchy and abstract vision-oriented pitches will no longer resonate (though they were getting old in this market already). Creating tangible near-term value will be king, whether for end-users or projects or purchasers. Startups will fail: In the short term, lean companies will have significant pressure to shut down operations as their revenue sources higher up the food chain call-off contracts and stop sending in new business. Every startup that relies on continuous funding to meet its growth trajectory is going to have a lot more difficulty finding that and we will see a lot of empires fall due to that pressure. While the worst outcomes will only affect a minority of projects overall, the perception it creates will make it more challenging for everyone else. Remote first/digital is king: The world just got a sharp wake-up call to move remote-first with everything from enterprise teams to government entitlement programs. It’s a trend that already had product/market fit and now just got a massive influx of new trial users and a reduction in red tape. Risk and opportunity go hand-in-hand in this environment. Some factors will likely work in our favor: Community: It has been a very challenging market for the attention of talented contributors over the last few years and the above factors will certainly loosen this. We expect that our core teams will have an easier time hiring, contracting or otherwise soliciting help from very talented individuals. Openness to change: People typically only change habits, behaviors, and brands during a series of small windows in their lives — graduation, marriage, physical moves, parenthood, etc — and otherwise prefer what’s consistent. This crisis has created the biggest global change event since the world wars and will absolutely create windows for introducing new behaviors and products. While the value proposition has to be much more tangible to succeed, people are in a rare state of collective openness to new ideas. Quality rises: The signal-to-noise ratio will further clarify to support high-quality projects as weaker hands let go and potential competition for airtime and mindshare shut down. It will still be challenging to pitch as an alternative to incumbent projects and behaviors but there will be less foolish salesmanship to compete against. There is always a balance to strike between being bold and foolish but we’re in this space to change the world and that requires the ability to act decisively and take measured risk. We’re going to constantly lookout for opportunities over the coming months and years to “be bold while others are scared” while still protecting the project’s long term ability to survive. The NEAR Project Overall, the NEAR project is in a strong position to thrive in this environment through the fortunate combination of good timing and an effective strategy. Efforts that were already underway when this crisis hit has made it relatively seamless to shift from “peace mode” into “war mode”. I’ll dig into the risks and opportunities for each major area below. Financial Our fundraising activities took place at the right time and we have over 20 months of runway to operate going forward, which supports the efforts of over 40 fulltime contributors and a half dozen organizations plus room to bring in new contributors in key areas. Obviously, as a layer 1 on the final countdown to a decentralized launch, the future funding roadmap and its implications for NEAR are quite a bit different than they are for a typical VC-funded startup. The crypto markets aren’t as exuberant as before but have actually held up better than expected and represent one of the biggest extrinsic risks to the project since they affect long term interest in the space and mid-term fundraising opportunities to support post-launch activities. Operations The teams behind NEAR were about ¾ remote-first when this started and so it was hardly any change when we asked contributors who normally work from an office (eg in SF) to please stay home. That occurred over a month ago and, aside from the challenges some people have working with kids on-premises, the disruption to operations has generally been offset by a greater sense of community among the contributors and the 100% embrace of remote-first communication. The SF-based team decided to hold off on signing a new office space in favor of testing full-remote for a while longer. Launch Roadmap On the technical side, we have been undergoing a “Descopening” effort since the micro-conf in BA two months ago. That means aggressively cutting scope on any features of the core network that aren’t “must-haves” for launch (and can reasonably be added afterward), cutting opportunistic team additions and embracing a Cosmos-style staggered launch strategy. So, rather than representing a hard pivot from the plan, the increased urgency to launch provided by macro events merely requires us to stay the course along that path. We’ll be releasing a public launch roadmap shortly so it is easier for projects, contributors and anyone else to understand what hurdles lie between us and MainNet. It will also help people better understand how the network start-up is likely to look and what we expect to have included in that effort. Here’s a peek: Community On the community side, the shift to remote has helped us focus. We will shortly announce a large-scale effort to build a new kind of remote summit that unites the other layer 1 protocols on the path to expanding the market together. It’s the kind of thing that could only breakthrough in an environment where every live event has been canceled and developers around the world are bored at home. Outro This is a challenging environment but from such times are born stronger projects. The space as a whole still has to overcome the existential challenge of making blockchain-based applications provide tangible value to developers, businesses and consumers in the Real World. And NEAR Protocol is still the technology that gives developers the tools to do this. So please keep referring to us the teams who need a performance edge for their projects, the developers who love hacking at home and the top tier operators who find themselves between gigs. We have bugs to squash, articles to translate, demos to write, teams to lead and components to build as we make our way ever closer to launch. COVID won’t get us down. It may even make us stronger. All the best, Erik
Enter the Black Dragon: NEAR Co-Founder Joins the NEAR Foundation as CEO NEAR FOUNDATION November 7, 2023 The NEAR Foundation announced today that Illia Polosukhin, co-founder of NEAR Protocol, has been appointed NEAR Foundation CEO to lead the NEAR ecosystem into the next phase of building an open web. As the person who has driven the vision for NEAR from the very beginning, there is no one better to oversee the growth of the NEAR Open Web Ecosystem and guide the constellation of teams building on NEAR to work together towards that common vision. From the earliest days of NEAR, Illia’s vision of an open web has guided the development of the ecosystem and served as a north star for the Foundation. In his new role as CEO, he will be able to realize that vision in a more direct and streamlined way. “I’m honored and excited to officially join the NEAR Foundation and continue working together with the ecosystem to build towards our shared vision of an open web,” said Illia Polosukhin about his new role. “Effectively coordinating a decentralized ecosystem involves a lot of iteration and experimentation and I’m proud that NEAR has committed to refining this process since the very beginning. I believe this next step in our shared evolution will help us build our respective verticals faster and work together more efficiently.” With his ability to bring together key nodes and align people across the ecosystem, Illia has always been a powerful guiding force for NEAR, something that his new role will allow him to continue and expand. As NEAR cements its position as the entry point to an open web, Illia’s appointment will help to create common work streams across the organization and broader ecosystem organizations that will help accelerate this journey. Combining a decentralized ecosystem approach with a more streamlined strategic coordination function will accelerate NEAR into its next phase of evolution, the details of which Illia will share at this week’s NEARCON. To help ensure the ecosystem nodes building this open web vision are coordinating effectively, Chris Donovan will be stepping into the position of NEAR Foundation COO to oversee the day-to-day operations of the Foundation, and will also remain as a member of the NEAR Foundation Council. Chris has been essential in this transition to a founder-led organization, and the Foundation and the whole ecosystem extend gratitude and appreciation for his work. With a clear vision, strong leadership, an engaged ecosystem, and a passionate community all building towards a common vision, NEAR is poised to take its next bold step into an open web. All members of the NEAR community are invited to join this week for the biggest, most exciting NEARCON ever in Lisbon, or tune in virtually at nearcon.org starting Wednesday, November 8. You won’t want to miss the chance to hear exciting announcements and strategy updates from Illia, demos from top projects across the ecosystem, and leading perspectives from the Web3 industry during three days of talks, hackathons, and celebration.
--- id: queryapi-websockets title: WebSocket-enabled Components with QueryAPI sidebar_label: WebSockets & QueryAPI --- In this article you'll learn how to create a NEAR component that gathers information from a [QueryAPI indexer](../../2.build/6.data-infrastructure/query-api/intro.md) using WebSockets. In this example, the QueryAPI indexer monitors the widget activity on the blockchain, and the NEAR component gets that information using WebSockets. :::info [QueryAPI](../../2.build/6.data-infrastructure/query-api/intro.md) 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. ::: ## QueryAPI indexer The [Widget Activity indexer](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=roshaan.near/widget-activity-feed) keeps track of any widget activity on the `social.near` smart contract. Whenever a Widget transaction is found, the data is stored in a Postgres database. ### DB schema The schema for the indexer's database is pretty simple: ```sql title=schema.sql CREATE TABLE "widget_activity" ( "id" SERIAL NOT NULL, "account_id" VARCHAR NOT NULL, "widget_name" VARCHAR NOT NULL, "block_height" DECIMAL(58, 0) NOT NULL, "receipt_id" VARCHAR NOT NULL, "block_timestamp" DECIMAL(20, 0) NOT NULL, CONSTRAINT "widgets_pkey" PRIMARY KEY ("id") ); CREATE INDEX idx_widget_activity_block_timestamp ON widget_activity (block_timestamp); ``` ### Indexer logic In the following code snippet, you can find the simple indexer logic that filters widget transactions from the `social.near` smart contract, and if it finds widget development activity, then it adds a record to the `widget_activity` table defined previously. :::tip To learn more, check the complete source code of the [Widget Activity indexer](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=roshaan.near/widget-activity-feed). ::: ```js title=indexerLogic.js // Add your code here const SOCIAL_DB = "social.near"; const nearSocialWidgetTxs = block .actions() .filter((action) => action.receiverId === SOCIAL_DB) .flatMap((action) => action.operations .map((operation) => operation["FunctionCall"]) .filter((operation) => operation?.methodName === "set") .map((functionCallOperation) => ({ ...functionCallOperation, args: base64decode(functionCallOperation.args), receiptId: action.receiptId, // providing receiptId as we need it })) .filter((functionCall) => { const accountId = Object.keys(functionCall.args.data)[0]; return Object.keys(functionCall.args.data[accountId]).includes( "widget" ); }) ); if (nearSocialWidgetTxs.length > 0) { console.log("Found NEAR Widget Development Activity..."); const blockHeight = block.blockHeight; const blockTimestamp = block.header().timestampNanosec; console.log(nearSocialWidgetTxs); await Promise.all( nearSocialWidgetTxs.map(async (widgetEditTx) => { const accountId = Object.keys(widgetEditTx.args.data)[0]; const widgetName = Object.keys( widgetEditTx.args.data[accountId]["widget"] )[0]; console.log(`ACCOUNT_ID: ${accountId}`); console.log(widgetName); await handleWidgetTx( accountId, widgetName, blockHeight, blockTimestamp, widgetEditTx.receiptId ); console.log(widgetEditTx); }) ); } } ``` --- This is the JS function that calls the GraphQL mutation `InsertWidgetActivity` and adds a record to the `widget_activity` table: :::tip Learn more about [QueryAPI indexing functions](../../2.build/6.data-infrastructure/query-api/index-function.md) and how to build your own indexers. ::: ```js title=indexerLogic.js async function handleWidgetTx( accountId, widgetName, blockHeight, blockTimestamp, receiptId ) { console.log(accountId, blockHeight, blockTimestamp, receiptId); try { const mutationData = { activity: { account_id: accountId, widget_name: widgetName, block_height: blockHeight, block_timestamp: blockTimestamp, receipt_id: receiptId, }, }; await context.graphql( `mutation InsertWidgetActivity($activity: roshaan_near_widget_activity_feed_widget_activity_insert_input = {}) { insert_roshaan_near_widget_activity_feed_widget_activity_one(object: $activity) { id } }`, mutationData ); } catch (e) { console.log(`Could not add widget activity to DB, ${e}`); } } ``` ## Using WebSockets Once you have a QueryAPI indexer running, you can use WebSockets to get the data in your NEAR Component. You only need to create a `WebSocket` object pointing to the QueryAPI's GraphQL endpoint. ### Setup Here's a code snippet from the NEAR component that subscribes and processes any activity from the [Widget Activity indexer](#queryapi-indexer): :::tip The code below is only a snippet. If you want the full source code to play around with the component, you can fork the [Widget Activity Feed source code](https://near.org#/near/widget/ComponentDetailsPage?src=roshaan.near/widget/query-api-widget-feed) and build your own NEAR component. ::: ```js const GRAPHQL_ENDPOINT = "near-queryapi.api.pagoda.co"; const LIMIT = 10; const accountId = props.accountId || "roshaan.near" || context.accountId; State.init({ widgetActivities: [], widgetActivityCount: 0, startWebSocketWidgetActivity: null, initialFetch: false, soundEffect: "https://bafybeic7uvzmhuwjficgctpleov5i43rteavwmktyyjrauwi346ntgja4a.ipfs.nftstorage.link/", }); const widgetActivitySubscription = ` subscription IndexerQuery { roshaan_near_widget_activity_feed_widget_activity( order_by: {block_timestamp: desc} limit: ${LIMIT} ) { account_id block_height block_timestamp id receipt_id widget_name } } `; const subscriptionWidgetActivity = { type: "start", id: "widgetActivity", // You can use any unique identifier payload: { operationName: "IndexerQuery", query: widgetActivitySubscription, variables: {}, }, }; function processWidgetActivity(activity) { return { ...activity }; } function startWebSocketWidgetActivity(processWidgetActivities) { let ws = State.get().ws_widgetActivity; if (ws) { ws.close(); return; } ws = new WebSocket(`wss://${GRAPHQL_ENDPOINT}/v1/graphql`, "graphql-ws"); ws.onopen = () => { console.log(`Connection to WS has been established`); ws.send( JSON.stringify({ type: "connection_init", payload: { headers: { "Content-Type": "application/json", "Hasura-Client-Name": "hasura-console", "x-hasura-role": "roshaan_near", }, lazy: true, }, }) ); setTimeout(() => ws.send(JSON.stringify(subscriptionWidgetActivity)), 50); }; ws.onclose = () => { State.update({ ws_widgetActivity: null }); console.log(`WS Connection has been closed`); }; ws.onmessage = (e) => { const data = JSON.parse(e.data); console.log("received data", data); if (data.type === "data" && data.id === "widgetActivity") { processWidgetActivities(data.payload.data); } }; ws.onerror = (err) => { State.update({ ws_widgetActivity: null }); console.log("WebSocket error", err); }; State.update({ ws_widgetActivity: ws }); } ``` :::info Pay attention to the `subscriptionWidgetActivity` JSON payload. ::: --- ### Processing This is the JS function that process the incoming widget activities generated by the QueryAPI indexer, allowing the NEAR component to create a feed based on the blockchain's widget activity: :::tip You can fork the [Widget Activity Feed source code](https://near.org#/near/widget/ComponentDetailsPage?src=roshaan.near/widget/query-api-widget-feed) and build your own NEAR component. ::: ```js function processWidgetActivities(incoming_data) { let incoming_widgetActivities = incoming_data.roshaan_near_widget_activity_feed_widget_activity.flatMap( processWidgetActivity ); const newActivities = [ ...incoming_widgetActivities.filter((activity) => { return ( state.widgetActivities.length == 0 || activity.block_timestamp > state.widgetActivities[0].block_timestamp ); }), ]; const prevActivities = state.prevActivities || []; State.update({ widgetActivities: [...newActivities, ...prevActivities] }); } if (state.ws_widgetActivity === undefined) { State.update({ startWebSocketWidgetActivity: startWebSocketWidgetActivity, }); state.startWebSocketWidgetActivity(processWidgetActivities); } ``` --- ### Rendering Finally, rendering the activity feed on the NEAR component is straight-forward, by iterating through the `state.widgetActivities` map: ```js return ( <div> <Title> Widget Activity Feed{" "} <TextLink href="https://near.org/dataplatform.near/widget/QueryApi.App"> {" "} Powered By QueryAPI{" "} </TextLink> </Title> <RowContainer> {state.widgetActivities.map((activity, i) => ( <Card> <div> <Widget src="mob.near/widget/TimeAgo" props={{ blockHeight: activity.block_height }} />{" "} ago </div> <CardBody> <div key={i}> <Text bold>Widget Name: {activity.widget_name}</Text> <Text bold>Account ID: {activity.account_id}</Text> </div> </CardBody> <CardFooter> <TextLink href={`/#/near/widget/ComponentDetailsPage?src=${activity.account_id}/widget/${activity.widget_name}`} > View </TextLink> </CardFooter> </Card> ))} </RowContainer> </div> ); ``` ---
NEAR Community in Focus: NEAR Regional Hubs COMMUNITY June 20, 2022 Across the NEAR ecosystem and beyond its digital borders, there is frequent talk of NEAR’s infinite scalability. But leveraging scalability, fast transactions, and low costs to reimagine the future ultimately requires a vibrant NEAR community. This is where NEAR Regional Hubs come in. As portals into a multi-faceted, ever-evolving ecosystem, NEAR Regional Hubs are communities where new projects and teams can meet and learn from Web3 natives and early adopters. Led by local entrepreneurs, and operating as independent legal entities, NEAR Regional Hubs are crucial in helping NEAR Foundation reach its missions and objectives around the world. With fully operational outposts in Asia, the Balkans, Ukraine, and Kenya, these hubs are vibrant incubators of Web3 communities, talent, and products. To get a better idea of how they operate and what each is up to, let’s take a deep dive into NEAR Regional Hubs. NEAR Regional Hubs: Mission, structure and operations “Each hub has its own flavor,” says Grace Torrellas, NEAR Foundation’s Head of Regional Hubs. “No hub is expected to be a specific way, or follow the same organization or structure.” Hubs tend to follow one of two primary approaches: local awareness and education or product lab and ecosystem fund. In the first, hubs generate local awareness and onboard new users, as well as support project building on NEAR. There are also activations through press releases, IRL events, and major local blockchain or tech events. Hubs that opt for this approach, like NEAR Kenya, are major drivers of NEAR Education programs, creating opportunities for developers and students to learn Web3 skills. The hub as a product lab or ecosystem fund drives adoption by working closely with projects from idea to execution. They also create partnerships with relevant organizations and government agencies. These hubs function like incubators with fundraising, accelerator, community building, and user acquisition functions. NEAR Asia: The first and largest regional hub Led by Amos Zhang, a Web3 investor and entrepreneur, NEAR Asia has undergone quite an evolution since inception. What began as an organizing force for NEAR’s Chinese community, it’s expanded to now include Korea and Vietnam. Featuring a product lab and ecosystem fund, along with $5M in funding from Metaweb, NEAR Asia is an active incubator of Web3 projects. The hub has also been instrumental in helping the NEAR Foundation secure funding for Web3 talent and project development. NEAR Asia supports users, developers and entrepreneurs in Asia by hosting events, hackathons, translated content, and more. “Half of global internet users are in Asia, home to apps like WeChat, Alipay, and Metituan,” says Zhang. “Mobile payments are also highly common in many Asian countries like China and Korea. This creates a great base and perfect fit for adopting blockchain technology, and NEAR’s mission has always been to make blockchain easy and usable by mainstream users.” The NEAR Chinese community is one of the largest communities in Greater China. Over 50,000 users engage in various community-hosted channels. And many developers and entrepreneurs are actively building on NEAR. In late 2021, NEAR Asia partnered with Alibaba’s Taobao for its Maker Festival. Hosted by China’s leading e-commerce platform, which generated more than $500 billion USD in revenue in 2020, Taobao Maker Festival (TMF) is an annual summit for top creators and innovators from the Taobao community. Taobao debuted “Too Rich City,” the first and only public chain-based NFTs created by artist Huang Heshan. Zhang says that Vietnam is one of NEAR’s biggest communities, with more than 30,000 members. This community is highly active on Telegram, Facebook, and Discord. The Vietnamese community recently partnered with GFS to run online education events to promote the NEAR ecosystem and educate both investors and developers. NEAR Ukraine: A hub within a hub Activated in late 2021, the Ukraine Hub is very much developer-oriented. But Anton Vaisburd, who leads the Ukraine Regional Hub, sees a multi-faceted community. “From one point of view, we’re an independent organization and kind of a for-profit organization,” says Vaisburd. “On the other, we’re a regional hub and community of people building on NEAR. We’re helping everybody out of Ukraine, building the product lab, and deeply connected with the foundation as a whole ecosystem.” NEAR Ukraine’s venture arm includes a product lab, which funds projects building on NEAR. The hub also performs marketing and PR functions, as well as organizing events like hackathons, conferences, and more. Amidst NEAR Ukraine’s hustle and bustle, the war in Ukraine weighs heavily on the community. “There hasn’t been a single hour we haven’t thought about it,” says Vaisburd. “I would love to say that it’s business as usual, but it’s not. You’re thinking about the importance of not only building social initiatives like helping Ukrainian refugees but also supporting the government and army, and trying to fight Russia in every way possible.” “What we realized is that we should do what we can do best, and that’s build products,” Vaisburd adds. “We’re trying to work harder because the better we work, the better we can actually perform, and the more we can pay taxes and support Ukraine.” With its current home in Lisbon, NEAR Ukraine is hub within a hub. The community is keenly aware of this. So NEAR Ukraine is creating an inclusive atmosphere in Lisbon, where local citizens, refugees, and expats from around the world can gather. “We’re trying to build a Web3 community for all in Lisbon,” says Vaisburd. “Soon, we’re going to announce our crypto summer house, where we are going to gather everyone, plan events, and host hackathons.” NEAR Balkans: Seven countries, one Web3 hub NEAR Balkans, which officially launched two months ago, started to coalesce in the summer of 2021. That’s when crypto natives Edi Sinovcic and Luka Sucic—the hub’s co-founders and current advisors—decided to unite Bosnia & Herzegovina, Bulgaria, Croatia, Montenegro, North Macedonia, Serbia and Slovenia into a single Web3 community. Ida Pandur, the General Manager of NEAR Balkans, says the hub has three primary areas of focus: Web3 education and community building, partnerships with traditional businesses, and product development. “Basically, the idea was to bring seven countries into the hub, into a community,” says Pandur. “Educate the community about Web3, about the opportunities, and how NEAR is the main facilitator of these Web3 opportunities within the region.” Community building and Web3 education at NEAR Balkans has already included a number of local meetups across the Balkans. The hub is also sponsoring specific Web3 conferences and building relationships with universities to attract students. “We are also preparing custom-made education for the developers to get certified on NEAR and Web3,” says Pandur. “We believe once you educate the market, then it’s easier to do everything else.” Parallel to education, NEAR Balkans works with both traditional and Web3 companies interested in Web3 integration. To help facilitate this process, the hub distributes grants to projects they see as showing potential. The hub is also available to companies looking to transition to NEAR from other Web3 platforms; and to individuals and teams looking to build projects from scratch. “We have our own research and development lab, and are looking to launch three products in the next few months,” Pandur says. “Two products are going to be in the DeFi space, and the other is going to be an NFT product. So, products are going to be a main focus of our hub.” NEAR Kenya: Spreading word of Web3 NEAR Kenya is taking a different tack by building community from the ground up. “What’s lacking on the ground is predominantly a basic understanding of blockchain and why it’s important,” says Kevin Imani, NEAR Kenya Hub General Manager and Sankore Guild founder. Community members want to learn about Web3. But job prospects are also top of mind. To meet these needs, NEAR Kenya funnels individuals into NEAR Education programs. “We’re promoting NEAR Education different certification programs,” says Imani. “We’re also getting involved with universities. By that I mean having a stand in a college hallway and telling students, hey, we have this thing going on this Saturday. Just come and we’ll break down some of these principles.” “We’re replicating NEAR Education content and breaking it down to the basics,” says Imani. “The end goal is to get them a job. So, hopefully, we’ll have one of the first Africa-based developer shops, where developers can be hired from other parts of the NEAR ecosystem, and jump on really exciting projects.” Imani believes these efforts will bear future fruit—a self-sustaining Web3 community in Kenya and neighboring countries. One built on a playbook based on speed, execution, inclusivity, and scalability. “The playbook will showcase how a Layer 1 protocol can be leveraged to implement blockchain in Eastern Africa, and do it effectively,” says Imani. “A 360-degree experience of someone who’s never been exposed to Web3, making sure there’s a space for them, all the way to bringing apps built by local talent onto NEAR mainnet. And just solving problems from infrastructure to decentralized finance, etc, in our respective region.” “Within a few years we’ll have some components in place, although it won’t be perfect,” Imani says. “Something tangible where we can say, ‘Hey, guys, we actually built something totally new.’” Bringing NEAR hubs to other regions Many other NEAR Regional Hubs are in active development. The LATAM Regional Hub, which would include several Latin American countries, is currently in the works. The hub is spearheaded by Claudio Cossio, founder of Metapool and Hispano Guild, an early NEAR Guild. “The LATAM Hub will focus more on education, and there are two programs that are quite critical in that education pipeline,” says Torrellas. “NEAR-certified developer and NEAR certified entrepreneur. Those two will allow the hub to pair the students with projects.” NEAR Foundation is now focusing on India, home to a large number of developers and strong interest in Web3. The government has even expressed interest in having NEAR be part of university curricula. This hub will feature both education and innovation.” Torrellas says a hub in Dubai, United Arab Emirates (UAE) is another area of interest. Many successful Indian developers have moved to Dubai, making the UAE a natural fit for a NEAR Regional Hub. And, of course, the United States will also feature a number of Hub Nodes forming part of the NEAR Regional Hubs network. Efforts are now underway to begin establishing hubs in Austin, San Francisco, New York City, and Miami. “There are so many places in the world where we know great opportunities seed, we are at the best time to build strong local connections and get people on board,” says Torrellas. “We need to focus on where those opportunities are.”
Use Case Spotlight: Nuclo CASE STUDIES October 19, 2018 We are starting a new blog series that shows use cases that will be enabled via scalable decentralized blockchain very soon. In the first blog in these series, the team at Nuclo provides the overview of their new platform as well as sheds light on one of the first use cases that involve Chilean Government and an entirely new approach to the supply chain for biomass purchasing. The initial deployment will have to support 10,000 active daily users, which requires a scalable, decentralized protocol underlying the Nuclo platform. Intro to what Nuclo offers The Nuclo platform (https://nuclo.io) is the first AMS (Application Management System) for blockchain applications. It requires no coding experience. It allows developers to use drag and drop components to achieve the required functionality. Background into the initial use case and subsequent Nuclo learnings The Nuclo team initially set out to reduce the cost of producing renewable energy by removing middlemen and ended up building the largest sales channel for biomass in Chile in 3-months. The team received an introduction to one of the largest biomass producers in southern Chile and they agreed to sell their entire inventory through Nuclo platform if they could deliver against three core features. It had to reduce the amount carbon emissions related to the burning of wet biomass, it had to reduce the cost of supply chain logistics, and it had to allow end users to purchase biomass directly from producers without middlemen intervention. The Nuclo team spent time on ride-alongs with distributors, walking through processing camps, and talking to different stakeholders throughout Chile. The research resulted in the creation of an application called LeñaHoy. It connected all of the participants of the biomass supply chain together and established the most cost-efficient and reliable way of producing tangible products. The platform reduced the cost of producing and transporting biomass by 31% and allowed consumers to purchase clean-burning dry biomass that was certified as safe. Nuclo team learned two core lessons that drastically influenced their next steps. Lesson one was that even though they drastically disrupted the industry they were not biomass salespeople. Lesson two was that the approach that Nuclo took for connecting supply chain participants including end consumers was industry agnostic. The team realized that they could have an impact on any fragmented supply chain so they decided to build a protocol that would enable others to enhance their own supply chains using the best practices that Nuclo team discovered. As Nuclo conducted more research, supported more businesses, interviewed teams around the world, and documented similar experiences, the team realized that their protocol like many others would be inaccessible to the majority of the world. This led them to develop an application management software that makes Nuclo protocol and others accessible via a graphical plug and play interface. Challenges with the current development on the blockchain In order to build your own blockchain technology, or deploy a product that is based on distributed ledger technology (DLT) your team must have a deep understanding of smart-contracts, core consensus algorithms and launching/maintaining multi-node networks; all of which a very small percentage of the world has an actual understanding of. In addition, when looking to apply this technology to supply-chains, it requires an industry level understanding of the nuances of the said production process. As such, Nuclo team functions as the bridge between this low-level technology and the business/network creators with the real world impact. How will the process be improved in the future Key business leaders at an organization who has no knowledge of smart contracts nor low-level blockchain technology will be able to deploy their own blockchain-based technology. They will be able to spin up their own basic MVP or full end-to-end product. Why blockchain is a key to Nuclo’s use case Nuclo team truly believes this is a question up to their user base. What the team realized is that specifically blockchain technology can revolutionize a number of different industries but it needs to be applied in a way to impact real lives. Initially, Nuclo team used their system as a test case for applying blockchain technology in supply-chains with an emphasis on provenance and traceability of products. This is a very clear and readily valuable application of the blockchain (or DLT) technology give the various amounts of actors in a supply-chain and the lack of uniformity of systems. Now, Nuclo team functions more as a technical partner and continue to actively engage with organizations, institutions, and governments who find novel applications with the blockchain and Nuclo enables them to quickly deploy a prototype around traceability using their platform. How scalability is a key to Nuclo’s use case Given Nuclo team operates in a variety of industries, supply-chains, and end-consumer applications, it is essential to building a system that can scale and always be live for our users. Nuclo protocol has the capacity to be blockchain agnostic which adds to the scalability requirements they face. What other important considerations are key to this use case On top of scalability, security and high transaction throughput are considerations Nuclo team takes into account when building for their user base. To follow our progress you can use: Twitter — https://twitter.com/nearprotocol, Medium — https://medium.com/nearprotocol, Discord — https://discord.gg/kRY6AFp, https://upscri.be/633436/
--- id: tools-infrastructure title: Tools & Infrastructure Resources sidebar_label: Tools & Infrastructure Resources sidebar_position: 6 --- --- There are a multitude of infrastructure tools & services integrated into the NEAR ecosystem to facilitate, and accelerate, your building on NEAR. ## Developer Tools * [NEAR Docs](https://docs.near.org) - your entry point to using NEAR's tech stack * [NEAR CLI](https://docs.near.org/tools/near-cli) - The NEAR Command Line Interface (CLI) is a tool that enables to interact with the NEAR network directly from the shell. * [Pagoda](https://www.pagoda.co/) - The first-ever Web3 startup platform, and main core protocol contributor of NEAR Protocol. * [RPC API](https://docs.near.org/api/rpc/introduction) - The RPC API allows you to communicate directly with the NEAR network. * [Gateway.FM](https://gateway.fm/) - a node infrastructure provider. Their NEAR RPC endpoint is stable, easy-to-use, load tested and QA’d by the experienced Gateway team, being the most stable node in the market * [Onepager](https://drive.google.com/file/d/1EvUJbGEffCW5DqSFbZku_LBMSVhYyV1Q/view?usp=sharing) * [Croncat](https://cron.cat/) - Decentralized Scheduling for Blockchain Transactions. * [Calimero](https://www.calimero.network/) - Allowing deployment of a customisable, easy to use private shard with built-in privacy features and confidential native WASM or EVM smart contracts. * [Torus](https://tor.us/) - The most secure passwordless authentication and private key management platform * [Kurtosis](https://www.kurtosistech.com/) - local development and testing environments for developers in the NEAR ecosystem. * [Overview video](https://www.youtube.com/watch?v=sdb3v9-syI8&t=26s) * [Rustle](https://github.com/blocksecteam/rustle) - Automatic smart contract auditer * [NEAR Playground](https://github.com/CSFM93/NearPlayGround) - Browser-based editor that allows developers to write, compile, test and call Near Rust and AssemblyScript Smart contracts in the browser * [Creator Studio](https://studio-client.pages.dev/auth) - A one-stop shop for minting, distributing, and managing NFT collections from an intuitive app dashboard, without a single line of code. * [Chainstack](https://chainstack.com/build-better-with-near/) - allows anyone to run high-performing NEAR nodes in minutes on a platform built for scale * [Kuutamo](https://kuutamo.cloud/) - Dedicated NEAR staking infrastructure, Next generation cloud services, built for blockchain. * [Kuutamo GitHub](https://github.com/kuutamolabs) ## Rust Stack * [Rust SDK](https://docs.near.org/sdk/rust/introduction) - Documentation around writing smart contracts on NEAR in Rust. * [Rust Library](https://github.com/near/near-sdk-rs) for writing NEAR smart contracts. ## JavaScript Stack * [NEAR JavaScript Docs](https://docs.near.org/tools/near-api-js/quick-reference) * [NEAR JavaScript API](https://github.com/near/near-api-js) - NEAR JavaScript API is a complete library to interact with the NEAR blockchain. * [NEAR JavaScript SDK](https://github.com/near/near-sdk-js) ## Storage * [IPFS](https://ipfs.tech/) - A peer-to-peer hypermedia protocol to make the web faster, safer, and more open. * [OnMachina](https://www.onmachina.io/) (coming soon) - A sharded data storage structure that is designed to provide scalable, cost-efficient, and immediately retrievable information on-chain. * [Arweave](https://www.arweave.org/) - Arweave is a new type of storage that backs data with sustainable and perpetual endowments, allowing users and developers to truly store data forever. * [Ceramic Network](https://ceramic.network/) - Ceramic is a decentralized content computation network for a world of open source information. ## Explorers & Indexers * [NEAR Indexer For Explorer](https://docs.near.org/tools/indexer-for-explorer) - To query usage information while developing a dapp * [Github repo](https://github.com/near/near-indexer-for-explorer) for NEAR Indexer * [The Graph](https://thegraph.com/) - Developer tools to process blockchain events and make the resulting data easily available * [Documentation](https://thegraph.com/docs/en/supported-networks/near/) for building subgraphs on NEAR * [NEAR Lake](https://near-indexers.io/docs/projects/near-lake-framework) is a game changing indexer because for a fraction of the cost of running your own you will have a fast, easy to maintain indexer. * [Byzantion](https://www.byzantion.xyz/) - NFT indexing * [Intake](https://26hh9mc3y0k.typeform.com/to/ExmMSZ58) to reach out about their services & tools * [NearBlocks](https://nearblocks.io/) - user friendly Blockchain Explorer and Analytics Platform for Near Protocol. ## Wallets * [NEAR Wallet Selector](https://github.com/near/wallet-selector) - NEAR Wallet Selector makes it easy for users to interact with your dApp by providing an abstraction over various wallets within the NEAR ecosystem * [Guide](https://github.com/near/wallet-selector/blob/dev/packages/core/docs/guides/custom-wallets.md) for Wallet Selector ## Payments / On Ramps * [MoonPay](https://www.moonpay.io/) - established fiat onramp solution integrated with NEAR * [NearPay](https://nearpay.co/) - fiat onramp & PoS solution built on NEAR * [ZokshPay](https://zoksh.com/) - No-Code, Non-Custodial Payments for Creators. ## Oracles * [Seda Protocol (formerly Flux)](https://www.seda.xyz/) - serving as the trust-less data layer for web3, Seda allows any smart contract to connect with crowdsourced, API-based, and Price-Feed data * [ELI5 thread](https://twitter.com/peterflux/status/1465460419095678980?s=20&t=FrojGyASfcrTqs_hbqew6Q) * [Switchboard](https://switchboard.xyz/) - Permission-less, customizable, multi-chain oracle protocol for general-purpose data feeds & verifiable randomness! ## Security * [NEAR Rust Smart Contract Security](https://www.youtube.com/playlist?list=PL7Gwuo_MOL740lhKTvouCJvk4sAyuqZqT) - 12 in-depth video lectures on NEAR Rust Smart contract security. * [HAPI](https://hapi.one/) - Cross-chain protocol aimed at creating new cybersecurity standards for DeFi market by providing real-time data on stolen funds and compromised wallets. * [BlockSec](https://blocksec.com/) - Building BlockChain Security Infrastructure | Smart Contract Audits. * [Rustle](https://github.com/blocksecteam/rustle) - Automatic smart contract auditer ## Analytics * [NEAR Stats Explorer](https://explorer.near.org/stats) * [GokuStats](https://www.gokustats.xyz/dashboard/near) - Aggregating key metrics for Layer1s. * [Datrics](https://blockchain.datrics.ai): Datrics is a tool for no-code analytics, machine learning, and dashboard creation. We empower blockchain teams with meaningful insights from on-chain and off-chain data. * [Stats Gallery](https://stats.gallery/) - Guides and tutorials from around the network! Quests. Get and complete quests to pump your account up! * [Ref Analytics](https://stats.ref.finance/) - Data & Analytics on Ref Finance. * [NEAR Staking](https://near-staking.com/) - See how decentralization is going and monitor if the pool you've delegated to is increasing or decreasing in stake. * [Flipside](https://docs.flipsidecrypto.com/) - Flipside provides Community Enabled Crypto Analytics, allowing our users to create and share data insights on the crypto projects they care most about. * [About Flipside NEAR integration](https://docs.google.com/document/d/1EHuDoR1VGJvUh47lWMRkAI5PR-_MM-4mlgLcXNC8CQE/edit?usp=sharing) * [Intake](https://vjpyk02mbl8.typeform.com/to/F6ctil9c) to explore their services & tools. * [Wombi](https://wombi.xyz/) - WOMBI helps dapps better understand audience and acquire high-quality users. WOMBI connects web2 and web3 analytics identifying channels and geographies that bring the best users. ## Interoperability * [Aurora EVM](https://aurora.dev/) - Aurora is an EVM solution built on the NEAR Protocol * [Octopus Network](https://oct.network/) - A NEAR-based multichain interoperable crypto-network for launching and running Web3 substrate-based, EVM compatible Appchains. * How to launch an Appchain in Octopus Network: [detailed guide](https://oct.network/appchain) * [Rainbow Bridge](https://rainbowbridge.app/transfer) - Bridge for transferring tokens between Ethereum, NEAR and the Aurora networks. * [Allbridge](https://allbridge.io/) - A fast, affordable and secure way of moving liquidity between EVM, non-EVM, and L2 blockchains. ## Developer Opportunities * [MetaBUIDL](https://near.org/metabuild/) - The NEAR MetaBUIDL hackathons will feature exciting themes focused on solving real-world problems.
--- sidebar_position: 1 --- # Unit Tests Testing contract functionality can be done through the `cargo test` framework. These tests will run with a mocked blockchain and will allow testing function calls directly without having to set up/deploy to a network and sign serialized transactions on this network. A common framework for tests, along with setting up a basic testing environment looks like: ```rust #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use super::*; use near_sdk::test_utils::VMContextBuilder; use near_sdk::{testing_env, VMContext}; fn get_context(is_view: bool) -> VMContext { VMContextBuilder::new() .signer_account_id("bob_near".parse().unwrap()) .is_view(is_view) .build() } #[test] fn my_test() { let context = get_context(false); testing_env!(context); // ... Write test here } } ``` Where `VMContextBuilder` allows for modifying the context of the mocked blockchain to simulate the environment that a transaction would be run. The documentation for what can be modified with this context can be found [here](https://docs.rs/near-sdk/4.1.1/near_sdk/struct.VMContext.html). The `testing_env!` macro will initialize the blockchain interface with the `VMContext` which is either initialized through `VMContextBuilder` or manually through itself. :::info Note This `testing_env!` and `VMContext` is only used for testing outside of `wasm` environments. When running the built contract on a network in a `wasm` environment, the context from the blockchain will be used through host functions on the runtime. ::: To test read-only function calls, set `is_view` to `true` on the `VMContext`. This will test to verify that function calls which just read state do not try to modify state through unit tests. In the above example, `true` should be passed into the `get_context` call, which initializes the context as read-only. You will want to use `testing_env!` each time you need to update this context, such as mocking the `predecessor_accound_id` to simulate the functions being called by or only allowing view operations as mentioned above. Each time this is done, a new mocked blockchain will be initialized while keeping the existing state.
An Update on the NDC Funding and Support for Grassroots Projects COMMUNITY August 18, 2023 Executive Summary The Foundation has set the future of funding for the NDC based on significant milestones post V1 Governance The launch of the Grassroots Support Initiative where projects in need of funding or support can engage directly with the NEAR Foundation to discuss options in the interim of direct support from the NDC If you are looking for support, you can schedule time with the team here One of the central tenets of Web3 is decentralisation. Decentralisation is central to creating an open web because it underpins an ecosystem’s anti-fragility, sustainability, scalability, and censorship resistance (amongst other important characteristics). A core part of a decentralised ecosystem is a robust self-governance infrastructure that empowers users and the community. Decentralisation is something that has guided the Foundation as a northstar, but as in all emerging fields sometimes the path toward that goal can be winding, complicated, and messy. That’s why we thought it would be important to take a moment to discuss the place of the NDC on that journey, the steps ahead, and how we can help the community get the support it needs along the way. Back in August 2022, the Community Working Group was formed by a collection of prominent NEAR community nodes with the purpose of establishing a new framework and implementation plan for ecosystem self-governance infrastructure and an associated treasury that could help ensure the ecosystem would continue on its path to decentralisation while giving everyone the chance to have their voice heard. This is how and why the NEAR Digital Collective (NDC) was formed. As the champion supporting the creation of decentralised governance infrastructure, the NDC plays an important role in the future of the NEAR ecosystem. Decentralised governance infrastructure will enable the community to vote (using an on-chain mechanism) on the allocation of funds, help ensure that decisions are made in a fair and representative manner, and further decentralise the NEAR ecosystem, something that is important both philosophically and practically for the healthy development of any Web3 ecosystem. So far, the NDC has already successfully launched the NDC Community Treasury, the IAMHuman voting initiative and V0 Governance, all major milestones for the ecosystem and vital pieces of governance infrastructure. Funding for the NDC Understanding the important role that the NDC can play in the future of the ecosystem, the NEAR Foundation is fully committed to its long term success. Of the Foundation’s treasury, a substantial portion has been earmarked for community initiatives like the NDC, which the Foundation intends to advance to the NDC Community Treasury over time as the ecosystem’s governance infrastructure matures. In order to further support the mission of the NDC as they continue to make progress, the Foundation is announcing today that it will provide an advance to the NDC Community Treasury in the region of 15M NEAR, subject to the successful completion of the V1 Governance elections. The criteria for this initial treasury advance will include (a) all V1 Governance elected positions being filled; and (b) the implementation by the community of a standardized funding request framework as a benchmark for responsible work moving forward. After this initial advance, the Foundation is also reiterating its commitment to further treasury advances (up to 100M NEAR). These further advances will be based on careful work with the community to set out specific criteria for milestones that will ensure funds are deployed responsibly and in a way that helps achieve the long-term goals of the wider ecosystem. Once V1 Governance is live, the community will be able to create success metrics for the NDC and vote on them as a collective with the support of the Foundation and other ecosystem nodes. The Foundation is also aware that, as a result of various delays with the launch of V1 Governance, the NDC Community Treasury is close to reaching the original USD1.5m V0 Governance budget cap contained in the NDC Community Treasury trust instrument. To ensure the community can continue to move forwards to the critical goal of V1 Governance launch, the Foundation will support the NDC Community Treasury by providing an additional USD400k buffer above that original budget cap. The NDC nominations for all 3 houses in V1 Governance are currently live until September 7th, with elections then kicking off on September 8th and running until September 22nd. We would encourage anyone who is interested in getting involved in this critical ecosystem milestone, and playing a role in steering the ecosystem forwards, to nominate themselves. Support for grassroots projects As part of the Foundation’s commitment to decentralisation and ensuring the voice of the community is heard, the Foundation announced in November 2022 that in most instances it would stop providing capital to the ecosystem through grants and instead have the NDC gradually take over that responsibility. While the Foundation understands that grants are a vital resource for grassroots projects to build and grow, we believed it was important to support moving them to a more decentralised model. However, since the timeline to implement V1 Governance has taken longer than anticipated, we recognise that ecosystem funding has been more limited, which has put significant pressure on builders in the ecosystem. Concerns around funding have been a major topic of discussion in the community over the last few weeks, and the Foundation appreciates that the community has rallied together to surface these issues in an open and constructive way. This feedback has helped the Foundation understand that it should have moved more quickly to provide interim support. To help address this issue, and to better support grassroots projects who are in need of support while the NDC continues to ramp up, the Foundation is launching a grassroots support initiative for any project in the ecosystem that is currently in need of urgent support. The Ecosystem Relations team is leading on the initiative from the Foundation and they have set up an open calendar for community members to connect directly with them to discuss how the Foundation can best support. Projects will be able to ask for emergency support, either financial or otherwise, by booking time with the team. This initiative will remain in place until NDC funding options become more readily available. While the Foundation will not be able to fund every request, we are committed to carefully reviewing every one we receive and prioritizing them based on immediate need and how well they line up with the goals of the broader ecosystem. You can book time with the Ecosystem Relations Team here. Grassroots projects and the community are the lifeblood of the NEAR ecosystem and the Foundation is committed to ensuring projects have the resources they need as we continue to create a thriving, decentralised ecosystem together.
--- id: nft-indexer title: Minted NFTs Indexer sidebar_label: NFTs Indexer --- :::info NEAR QueryAPI is currently under development. Users who want to test-drive this solution need to be added to the allowlist before creating or forking QueryAPI indexers. You can request access through [this link](http://bit.ly/near-queryapi-beta). ::: ## Overview This tutorial creates a working NFT indexer using [NEAR QueryAPI](../../../2.build/6.data-infrastructure/query-api/intro.md), and builds a [NEAR component](../../../2.build/3.near-components/what-is.md) that presents the data. The indexer is watching for `nft_mint` [Events](https://nomicon.io/Standards/EventsFormat) and captures some relevant data: - `receiptId` of the [Receipt](/build/data-infrastructure/lake-data-structures/receipt) where the mint has happened - `receiverId` - Marketplace - Links to the transaction on NEAR Explorer In this tutorial you'll learn how you can listen to [Events](https://nomicon.io/Standards/EventsFormat) generated by smart contracts and how you can index them. :::tip The indexer's source code can be found by [following this link](https://near.org/dataplatform.near/widget/QueryApi.App?selectedIndexerPath=bucanero.near/nft_v4). ::: ### NFT Events NEAR Protocol supports [Events](https://nomicon.io/Standards/EventsFormat). These `Events` allow a contract developer to add standardized logs to the [`ExecutionOutcomes`](/build/data-infrastructure/lake-data-structures/execution-outcome) thus allowing themselves or other developers to read those logs in more convenient manner via API or indexers. Events have a field `standard` which aligns with NEPs. In this tutorial we'll be talking about [NEP-171 Non-Fungible Token standard](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core). The indexer watches all the NFTs minted following the [NEP-171 Events](https://nomicon.io/Standards/Tokens/NonFungibleToken/Event) standard. It should detect every single NFT minted, and store a basic set of data like: in what Receipt it was minted, and which marketplace created it (for example, [Paras](https://paras.id), [ShardDog](https://shard.dog), and [Mintbase](https://mintbase.io)). ## Defining the Database Schema The first step to creating an indexer is to define the database schema. This is done by editing the `schema.sql` file in the code editor. The schema for this indexer looks like this: ```sql CREATE TABLE "nfts" ( "id" SERIAL NOT NULL, "marketplace" TEXT, "block_height" BIGINT, "block_timestamp" BIGINT, "receipt_id" TEXT, "receiver_id" TEXT, "nft_data" TEXT, PRIMARY KEY ("id", "block_height", "block_timestamp") ); ``` This schema defines one table: `nfts`. The table has these columns: - `id`: a unique identifier for each row in the table - `marketplace`: the marketplace where the NFT was created - `block_height`: the height of the block in which the NFT was created - `block_timestamp`: the timestamp of the block in which the NFT was created - `receipt_id`: the receipt ID of the transaction that created the NFT - `receiver_id`: the receiver ID of the transaction that created the NFT - `nft_data`: the content of the minted NFT ## Defining the indexing logic The next step is to define the indexing logic. This is done by editing the `indexingLogic.js` file in the code editor. The logic for this indexer can be divided into two parts: 1. Filtering blockchain transactions for a specific type of transaction 2. Saving the data from the filtered transactions to the database ### Filtering Blockchain transactions The first part of the logic is to filter blockchain transactions for a specific type of transaction, where the `Event` is a [NEP-171](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core) `nft_mint`. This is done by using the `getBlock` function. This function takes in a block and a context and returns a promise. The `block` is a Near Protocol block, and the `context` is a set of helper methods to retrieve and commit state. The `getBlock` function is called for every block on the blockchain. The `getBlock` function for this NFT indexer looks like this: ```js async function getBlock(block: Block) { for (let ev of block.events()) { const r = block.actionByReceiptId(ev.relatedReceiptId); const createdOn = block.streamerMessage.block.header.timestamp; try { let event = ev.rawEvent; if (event.standard === "nep171" && event.event === "nft_mint") { console.log(event); let marketplace = "unknown"; if (r.receiverId.endsWith(".paras.near")) marketplace = "Paras"; else if (r.receiverId.endsWith(".sharddog.near")) marketplace = "ShardDog"; else if (r.receiverId.match(/\.mintbase\d+\.near$/)) marketplace = "Mintbase"; const nftMintData = { marketplace: marketplace, block_height: block.header().height, block_timestamp: createdOn, receipt_id: r.receiptId, receiver_id: r.receiverId, nft_data: JSON.stringify(event.data), }; await context.db.Nfts.insert(nftMintData); console.log(`NFT by ${r.receiptId} has been added to the database`); } } catch (e) { console.log(e); } } } ``` This indexer filters [Blocks](https://near.github.io/near-lake-framework-js/classes/_near_lake_primitives.block.Block.html) that have [Events](https://near.github.io/near-lake-framework-js/classes/_near_lake_primitives.events.Event.html) of type `nft_mint` and standard `nep171`. In addition, it stores the JSON event data and identifies the NFT marketplace. ### Saving the data to the Database The second part of the logic is to save the data from the filtered transactions to the database. This is solved easily by using the [`context.db.Nfts.insert`](../../../2.build/6.data-infrastructure/query-api/context.md#insert) helper method: The logic for this looks like: ```js const nftMintData = { marketplace: marketplace, block_height: h, block_timestamp: createdOn, receipt_id: r.receiptId, receiver_id: r.receiverId, nft_data: JSON.stringify(event.data), }; // store result to the database await context.db.Nfts.insert(nftMintData); ``` ## NEAR Component The final step is querying the indexer using GraphQL from a [NEAR component](../queryapi-ws.md) with WebSockets. Here's a simple GraphQL query that gets the last `${LIMIT}` minted NFTs: ```graphql IndexerQuery { bucanero_near_nft_v4_nfts(order_by: {block_timestamp: desc}, limit: ${LIMIT}) { block_height block_timestamp id marketplace nft_data receipt_id receiver_id } ``` ### Setup Here's a code snippet that subscribes and processes the most recent activity (last 10 NFTs) from the [NFT indexer](#queryapi-indexer): :::tip The code below is only a snippet. If you want the full source code to play around with the component, you can fork the [NFT Activity Feed source code](https://near.org/near/widget/ComponentDetailsPage?src=bucanero.near/widget/query-api-nft-feed) and build your own NEAR component. ::: ```js const GRAPHQL_ENDPOINT = "near-queryapi.api.pagoda.co"; const LIMIT = 10; const accountId = props.accountId || "bucanero.near" || context.accountId; State.init({ widgetActivities: [], widgetActivityCount: 0, startWebSocketWidgetActivity: null, initialFetch: false, }); const widgetActivitySubscription = ` subscription IndexerQuery { bucanero_near_nft_v4_nfts(order_by: {block_timestamp: desc}, limit: ${LIMIT}) { block_height block_timestamp id marketplace nft_data receipt_id receiver_id } } `; const subscriptionWidgetActivity = { type: "start", id: "widgetNftActivity", // You can use any unique identifier payload: { operationName: "IndexerQuery", query: widgetActivitySubscription, variables: {}, }, }; function processWidgetActivity(activity) { return { ...activity }; } function startWebSocketWidgetActivity(processWidgetActivities) { let ws = State.get().ws_widgetActivity; if (ws) { ws.close(); return; } ws = new WebSocket(`wss://${GRAPHQL_ENDPOINT}/v1/graphql`, "graphql-ws"); ws.onopen = () => { console.log(`Connection to WS has been established`); ws.send( JSON.stringify({ type: "connection_init", payload: { headers: { "Content-Type": "application/json", "Hasura-Client-Name": "hasura-console", "x-hasura-role": "bucanero_near", }, lazy: true, }, }) ); setTimeout(() => ws.send(JSON.stringify(subscriptionWidgetActivity)), 50); }; ws.onclose = () => { State.update({ ws_widgetActivity: null }); console.log(`WS Connection has been closed`); }; ws.onmessage = (e) => { const data = JSON.parse(e.data); console.log("received data", data); if (data.type === "data" && data.id === "widgetNftActivity") { processWidgetActivities(data.payload.data); } }; ws.onerror = (err) => { State.update({ ws_widgetActivity: null }); console.log("WebSocket error", err); }; State.update({ ws_widgetActivity: ws }); } ``` :::info Pay attention to the `widgetActivitySubscription` GraphQL query and the `subscriptionWidgetActivity` JSON payload. ::: --- ### Processing This is the JS function that process the incoming widget activities generated by the QueryAPI indexer, allowing the NEAR component to create a feed based on the blockchain's widget activity: :::tip You can fork the [NFT Activity Feed source code](https://near.org/near/widget/ComponentDetailsPage?src=bucanero.near/widget/query-api-nft-feed) and build your own NEAR component. ::: ```js function processWidgetActivities(incoming_data) { let incoming_widgetActivities = incoming_data.bucanero_near_nft_v4_nfts.flatMap(processWidgetActivity); const newActivities = [ ...incoming_widgetActivities.filter((activity) => { return ( state.widgetActivities.length == 0 || activity.block_timestamp > state.widgetActivities[0].block_timestamp ); }), ]; if (newActivities.length > 0 && state.widgetActivities.length > 0) { } const prevActivities = state.prevActivities || []; State.update({ widgetActivities: [...newActivities, ...prevActivities] }); } if (state.ws_widgetActivity === undefined) { State.update({ startWebSocketWidgetActivity: startWebSocketWidgetActivity, }); state.startWebSocketWidgetActivity(processWidgetActivities); } ``` --- ### Rendering Finally, rendering the activity feed on the NEAR component is straight-forward, by iterating through the `state.widgetActivities` map: ```js return ( <div> <Title> NFT Minting Activity Feed{" "} <TextLink href="https://near.org/dataplatform.near/widget/QueryApi.App"> {" "} Powered By QueryAPI{" "} </TextLink> </Title> <RowContainer> {state.widgetActivities.map((activity, i) => ( <Card> <div> <Widget src="mob.near/widget/TimeAgo" props={{ blockHeight: activity.block_height }} />{" "} ago </div> <CardBody> <div key={i}> <Text bold>NFT Marketplace: {activity.marketplace}</Text> <TextLink href={`https://nearblocks.io/address/${activity.receiver_id}`} > {activity.receiver_id} </TextLink> <Text bold>Receipt ID: {activity.receipt_id}</Text> </div> </CardBody> <CardFooter> <TextLink href={`https://legacy.nearblocks.io/?query=${activity.receipt_id}`} > View details on NEAR Explorer </TextLink> </CardFooter> </Card> ))} </RowContainer> </div> ); ```
# Contract preparation This document describes the contract preparation and instrumentation process as well as the limitations this process imposes on the contract authors. In order to provide high performance execution of the [function calls], the near validator utilizes ahead-of-time preparation of the contract WASM code. Today the contract code is prepared during the execution of the [`DeployContractAction`]. The results are then saved and later reported to the user when a [`FunctionCall`] is invoked. Note that only some parts of this document are normative. This document delves into implementation details, which may change in the future as long as the behavior documented by the normative portions of this book is maintained. The non-normative portions of this document will be called out as such. [function calls]: ./FunctionCall.md [`DeployContractAction`]: ./Actions.md#DeployContractAction [`FunctionCallAction`]: ./Actions.md#FunctionCallAction ## High level overview **This section is not normative.** Upon initiation of a contract deployment, broadly the following operations will be executed: validation, instrumentation, conversion to machine code (compilation) and storage of the compiled artifacts in the account’s storage. Functions exported from the contract module may then be invoked through the mechanisms provided by the protocol. Two common ways to call a function is by submitting a function call action onto the chain or via a cross-contract call. Most of the errors that have occurred as part of validation, instrumentation, compilation, etc. are saved and reported when a `FunctionCallAction` is submitted. Deployment itself may only report errors relevant to itself, as described in the specification for [`DeployContractAction`]. ## Validation A number of limits are imposed on the WebAssembly module that is being parsed: * The length of the wasm code must not exceed `max_contract_size` genesis configuration parameter; * The wasm module must be a valid module according to the WebAssembly core 1.0 specification (this means no extensions such as multi value returns or SIMD; this limitation may be relaxed in the future). * The wasm module may contain no more than: * `1_000_000` distinct signatures; * `1_000_000` function imports and local function definitions; * `100_000` imports; * `100_000` exports; * `1_000_000` global imports and module-local global definitions; * `100_000` data segments; * `1` table; * `1` memory; * UTF-8 strings comprising the wasm module definition (e.g. export name) may not exceed `100_000` bytes each; * Function definitions may not specify more than `50_000` locals; * Signatures may not specify more than `1_000` parameters; * Signatures may not specify more than `1_000` results; * Tables may not specify more than `10_000_000` entries; If the contract code is invalid, the first violation in the binary encoding of the WebAssembly module shall be reported. These additional requirements are imposed after the module is parsed: * The wasm module may contain no more function imports and local definitions than specified in the `max_functions_number_per_contract` genesis configuration parameter; and These additional requirements are imposed after the instrumentation, as documented in the later sections: * All imports may only import from the `env` module. ## Memory normalization All near contracts have the same amount of memory made available for execution. The exact amount is specified specified by the `initial_memory_pages` and `max_memory_pages` genesis configuration parameters. In order to ensure a level playing field, any module-local memory definitions are transparently replaced with an import of a standard memory instance from `env.memory`. If the original memory instance definition specified limits different from those specified by the genesis configuration parameters, the limits are reset to the configured parameters. ## Gas instrumentation In order to implement precise and efficient gas accounting, the contract code is analyzed and instrumented with additional operations before the compilation occurs. One such instrumentation implements accounting of the gas fees. Gas fees are accounted for at a granularity of sequences of instructions forming a metered block and are consumed before execution of any instruction part of such a sequence. The accounting mechanism verifies the remaining gas is sufficient, and subtracts the gas fee from the remaining gas budget before continuing execution. In the case where the remaining gas balance is insufficient to continue execution, the `GasExceeded` error is raised and execution of the contract is terminated. The gas instrumentation analysis will segment a wasm function into metered blocks. In the end, every instruction will belong to exactly one metered block. The algorithm uses a stack of metered blocks and instructions are assigned to the metered block on top of the stack. The following terminology will be used throughout this section to refer to metered block operations: * active metered block – the metered block at the top of the stack; * pop – the active metered block is removed from the top of the stack; * push – a new metered block is added to the stack, becoming the new active metered block. A metered block is pushed onto the stack upon a function entry and after every `if` and `loop` instruction. After the `br`, `br_if`, `br_table`, `else` & `return` (pseudo-)instructions the active metered block is popped and a new metered block is pushed onto the stack. The `end` pseudo-instruction associated with the `if` & `loop` instructions, or when it terminates the function body, will cause the top-most metered block to be popped off the stack. As a consequence, the instructions within a metered block need not be consecutive in the original function. If the `if..end`, `loop..end` or `block..end` control block terminated by this `end` pseudo-instruction contained any branching instructions targeting control blocks other than the control block terminated by this `end` pseudo instruction, the currently active metered block is popped and a new metered block is pushed. Note that some of the instructions considered to affect the control flow in the WebAssembly specification such as `call`, `call_indirect` or `unreachable` do not affect metered block construction and are accounted for much like other instructions not mentioned in this section. This also means that calling the `used_gas` host function at different points of the same metered block would return the same value if the `base` cost was `0`. All the instructions covered by a metered block are assigned a fee based on the `regular_op_cost` genesis parameter. Pseudo-instructions do not cause any fee to be charged. A sum of these fees is then charged by instrumentation inserted at the beginning of each metered block. ### Examples **This section is not normative.** In this section some examples of the instrumentation are presented as an understanding aid to the specification above. The examples are annotated with comments describing how much gas is charged at a specific point of the program. The programs presented here are not intended to be executable or to produce meaningful behavior. #### `block` instruction does not terminate a metered block ```wat (func (; charge_gas(6 regular_op_cost) ;) nop block nop unreachable nop end nop) ``` This function has just 1 metered block, covering both the `block..end` block as well as the 2 `nop` instructions outside of it. As a result the gas fee for all 6 instructions will be charged at the beginning of the function (even if we can see `unreachable` would be executed after 4 instructions, terminating the execution). #### Branching instructions pop a metered block Introducing a conditional branch to the example from the previous section would split the metered block and the gas accounting would be introduced in two locations: ```wat (func (; charge_gas([nop block br.0 nop]) ;) nop block br 0 (; charge_gas([nop nop]) ;) nop nop end nop) ``` Note that the first metered block is disjoint and covers the `[nop, block, br 0]` instruction sequence as well as the final `nop`. The analysis is able to deduce that the `br 0` will not be able to jump past the final `nop` instruction, and therefore is able to account for the gas fees incurred by this instruction earlier. Replacing `br 0` with a `return` would enable jumping past this final `nop` instruction, splitting the code into three distinct metered blocks instead: ```wat (func (; charge_gas([nop block return]) ;) nop block return (; charge_gas([nop nop]) ;) nop nop end (; charge_gas([nop]) ;) nop) ``` #### `if` and `loop` push a new metered block ```wat (func (; charge_gas([loop unreachable]) ;) loop (; charge_gas([br 0]) ;) br 0 end unreachable ) ``` In this example the `loop` instruction will always introduce a new nested metered block for its body, for the `end` pseudo-instruction as well as `br 0` cause a backward jump back to the beginning of the loop body. A similar reasoning works for `if .. else .. end` sequence since the body is only executed conditionally: ```wat (func (; charge_gas([i32.const.42 if nop]) ;) i32.const 42 if (; charge_gas([nop nop]) ;) nop nop else (; charge_gas([unreachable]) ;) unreachable end nop) ``` ## Operand stack depth instrumentation The `max_stack_height` genesis parameter imposes a limit on the number of entries the wasm operand stack may contain during the contract execution. The maximum operand stack height required for a function to execute successfully is computed statically by simulating the operand stack operations executed by each instruction. For example, `i32.const 1` pushes 1 entry on the operand stack, whereas `i32.add` pops two entries and pushes 1 entry containing the result value. The maximum operand stack height of the `if..else..end` control block is the larger of the heights for two bodies of the conditional. Stack operations for each instruction are otherwise specified in the section 4 of the WebAssembly core 1.0 specification. Before the `call` or `call_indirect` instructions are executed, the callee's required stack is added to the current stack height counter and is compared with the `max_stack_height` parameter. A trap is raised if the counter exceeds the limit. The instruction is executed, otherwise. Note that the stack depth instrumentation runs after the gas instrumentation. At each point where gas is charged one entry worth of operand stack space is considered to be used. ### Examples **This section is not normative.** Picking the example from the gas instrumentation section, we can tell that this function will use just 1 operand slot. Lets annotate the operand stack operations at each of the instructions: ```wat (func (; charge_gas(...) ;) (; [] => [gas] => [] ;) i32.const 42 (; [] => [i32] ;) if (; [i32] => [] ;) (; charge_gas(...) ;) (; [] => [gas] => [] ;) nop (; [] ;) nop (; [] ;) else (; charge_gas(...) ;) (; [] => [gas] => [] ;) unreachable (; [] ;) end nop (; [] ;) ) ``` We can see that at no point in time the operand stack contained more than 1 entry. As a result, the runtime will check that 1 entry is available in the operand stack before the function is invoked. <!-- TODO: describe the ahead-of-time compilation details and the errors it may cause or limits it may impose -->
Introducing NCON and How to Use It at NEARCON ‘23 NEAR FOUNDATION November 6, 2023 Hello NEARians, By now many of you are in or are en route to the magical city of Lisbon for NEARCON23! The amount of alpha dropping this week will have you weak in your knees. It’s been our mission to bring you an event that puts Web3 experiences at the forefront of NEARCON. Even better when we partner with our Community to bring you a truly social experience elevating your journeys throughout NEARCON. This year NCON makes its big debut! What is NCON? The NEAR Foundation has partnered with Jutsu, Keypom, and Veriken to create an exciting experience for you: the NCON token — an event experience built on B.O.S. NCON embodies the essence of the open web. An open web where we transact with each other on a peer to peer network. Interacting with sponsors, attending content sessions, paying for your lunch, will be part of the NCON experience. As you complete NCON Bounties (see the full list below), you’ll be rewarded NCON which can be redeemed for swag, lunches, and other goodies during NEARCON. When you check in at registration you will automatically receive 100 NCON — enough to buy lunch for 3 days and 1 piece of swag. Complete Bounties to earn more NCON and maximize your NEARCON experience. At the end of NEARCON, the top 3 NCON redeemers will receive a free trip to NEARCON24. Visit the helpdesk to verify your Bounty completions and get dropped NCON. Good luck and “happy bounting”! *NCON exists for the purposes of NEARCON and NCON holds no real financial value beyond the event. Terms and conditions apply. NCON Bounties to complete BOUNTY NCON REWARD Ticket Claim (done at registration) 100.00 We’re dropping various amounts of NCON during sessions, roundtables, firesides, panels and keynotes. The more sessions you join, the higher chance for more NCON! 1.00 – 10.00 Take a picture with the Opening Ceremony special guest and tweet “FOUNDERS, DEVELOPERS, BUILDERS #NEARCON2023” 20.00 Early Bird Drops (arrive to NEARCON or Hacker HQs between 9am and 10:30am) 5.00 Visit all three venues (tweet pictures of each venue and #NEARCON2023) 5.00 Upvote apps in the B.O.S. App Library 5.00 Attend one of the Founders Forum sessions 2.00 Complete the Shard Dog Engage-a-thon 2.00 Submit Pagoda User Research Survey 2.00 Shoutout your favorite thing on NEARCON Twitter #NEARCON2023 2.00 Submit a Hackathon Project 40.00 Visit the B.O.S. Booth 5.00 Visit the hacker help desk and get help on your project (or just get your NCON Drop) 2.00 Sponsor Bounties Varies Glass – Sign up for GLASS at www.glass.fun/signup, and tag us (@glassdotfun) in a tweet about your favorite thing you’ve eaten or drank so far at NEARCON! 5.00 Aurora – Visit Aurora booth, talk to Armand or Slava, tweet “Big Alpha coming soon on @auroraisnear” without a spoiler. 2.00 Proximity – Attend a talk featuring a Proximity team member. Post on X and tag @proximityfi 2.00 Proximity – Try out these B.O.S.-powered gateways for L2s and share your thoughts on X: Polygon zkEVM Interactive App Dashboard, Mantle Ecosystem Gateway, “B.O.S.” Store on the Coin98 Super App. 20.00 Mintbase – Minsta your NEARCON moments and earn NCON 🤳🏻 ▾ Go to https://minsta.mintbase.xyz ▾ Take a photo and mint it as a NFT 8.00 Octopus – Visit us at the Octopus Network booth and tweet a picture at the booth with “Otto” tagging @oct_network and #NEARCON. 2.00 Octopus – Interact with Octopus Network on mainnet.oct.network, in forum at forum.oct.network or at Octopus DAO on AstroDAO for a 5x multiplier bonus! 10.00 Calimero – Log in to Calimero Chat, the official chat of NEARCON, and send an epic meme! The funnier your meme, the more NCON you score! Claim them at the Calimero booth. 2.00 – 5.00 The Littles -1. Visit TheFunPass booth2. Participate in their Stick Catcher experience. 2.00 NEAR Mobile – Publish a tweet describing what you like more about @NEARMobile_app- Download NEAR Mobile (https://nearmobile.app/) and give us a review on Google Play or App Store- Follow us on Twitter (@NEARMobile_app), join our Telegram (https://t.me/NEARMobile) and subscribe to YT (@NEARMobileWallet). 2.00 NEAR Balkans – NEAR Lisbon Adventure: Collect all flags at the NEACON booths! 2.00 NEAR Balkans – POAP: Find the POAP QR code and prove your attendance at NEARCON with the Tekuno PODs! 2.00 SailGP – SailGP’s NEARcon Scavenger Hunt: Download the SailGP app and join our fan loyalty program, The Dock. Then, set off to explore NEARcon’s three venues, hunting down not one, not two, but SEVEN SailGP QR codes. Scan all seven codes using the SailGP app to snag your exclusive SailGP x NEARcon NFT. Once you’ve got your hands on it, head over to the SailGP booth, present your collectible, and get in on the action to win daily prizes on top of NCON! 5.00 How to redeem your NCON Redeemable NCON PRICE LUNCH (NEARCON and HACKER HQs) 15 per visit White t-shirt 20.00 Black t-shirt 20.00 Green t-shirt 20.00 Cream hoodie 50.00 Black hoodie 50.00 Windbreaker 50.00 Cream hat 15.00 Black hat 15.00 Water bottle 10.00 Duffle bag 50.00 Tangem Wallet V1 40 Tangem Wallet V2 40 Bottle Openers 5 Early Closing Party Access 50 Horizon Credits for Founders 30 Top 3 NCON Redeemers will receive a free trip to NEARCNO24! —–
--- sidebar_position: 3 sidebar_label: Get API Keys title: Get Pagoda API Keys --- :::warning Please be advised that these tools and services will be discontinued soon. ::: 1. Register an account on [Pagoda Console](https://console.pagoda.co/): ![](/docs/pagoda/getkey1.png) 2. Create a blank project ![](/docs/pagoda/getkey2.png) 3. Give your project a cool name ![](/docs/pagoda/getkey3.png) 4. Grab your API Key Click the API Tab and you will see your API key already generated for you and ready to use, remember to switch networks for `MainNet` using the button on top, you can also navigate through your different projects there. ![](/docs/pagoda/getkey4.png) 5. Connect to Pagoda RPC Node Follow the instructions on the screen to set up your Pagoda RPC Access, we have created a quick setup guide for all NEAR tools. - `https://near-testnet.api.pagoda.co/rpc/v1/` - `https://near-mainnet.api.pagoda.co/rpc/v1/` ![](/docs/pagoda/getkey5.png) 6. You can use this line of code for a quick test ```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/ ``` ![](/docs/pagoda/getkey6.png) Congrats! You are connected!
Refer-and-Earn Guidelines Update: Q3 2022 NEAR FOUNDATION December 9, 2022 NEAR’s ever-growing and engaged community is one of the ecosystem’s greatest strengths. Remember the NEAR Foundation Grants team’s Refer-and-Earn Program? A number of NEAR community members participated in Refer-and-Earn in early 2022, resulting in grants for dozens of exciting projects currently building on the NEAR ecosystem. The Foundation has had the pleasure of seeing the community being a key contributor in providing ecosystem support and building dapps. The community does this in a number of ways, including running and sponsoring events, educating developers and entrepreneurs on the benefits of NEAR, bringing projects with active user bases from other chains, and so on. NEAR Foundation wants to build on the community’s successes through a new incentive structure that aligns with the Grants Program (more information can be found at the Grants Program Handbook here bit.ly/Grants-Program-Handbook). The payout for each project referred will be awarded a total of 10% of the project awarded grant amount. This amount is awarded in nUSDC (wrapped USDC on NEAR) and is calculated at the end of each quarter. The first half of the 5% will be awarded at the point of the contract signed. The second half of the 5% will be awarded once all project milestones are completed. Refer-and-Earn: Q3 Qualified Projects The NEAR ecosystem receives a number of your recommendations and referrals. A total of 12 quality projects emerged from Refer-and-Earn, each aligning with NEAR Foundation’s Grants program objectives. In no particular order, here are the Q3 2022 qualified projects: Scene Azadi Record Vital Carbon Metavision Games Murder Mystery Collective MetaLordz Klabrate and ClimaFi Meteor wallet Mintmade NEARKai EVIE Marketplace Autify The Grants team has reached out to all Refer-and-Earn referrers. Thanks to your help and support, the Grants team is able to support innovative projects like those listed above.
--- title: DAO Basics description: Your map to navigating the world of DAOs on NEAR slug: /governance sidebar_position: 0 --- # Your Guide to DAOs on NEAR ## What’s a DAO? In short, a DAO is a Decentralised Autonomous Organisation. It’s like a company, coop, club, or task force. The secret that sets DAOs apart from these examples is all in the name. Decentralization is a core concept of blockchains. SputnikDAOs operate on NEAR blockchain, enabling peer to peer transactions without borders or gate keepers. You can collaborate with whoever you want from around the world! Autonomous Organization is a tricker concept tied up in a new work revolution. Companies and platforms typically have someone in the middle to handle logistics (and taking a cut for their effort). SputnikDAOs replace those positions with apps running on the NEAR blockchain to automate things like distributing funds, recording consensus, and managing membership. All of that saved effort and cost is then passed onto the members of the DAOs, paying them more for the value they contribute! To make things tangible let’s look at an example like AirBNB. If people with open space for short term rental coordinate directly with each other through a DAO then they don’t have to give a cut of their profits to AirBNB for providing that organizational service. Record labels, foundations, setting up group buys, crowdfunding, and more are all more efficient as DAOs! In short, DAOs are digital companies living on a blockchain with participants united by a common purpose. SputnikDAO enables individuals to come together to form cooperative, open, accessible, and transparent organisations. ## Why a DAO? DAOs empower communities to govern on-chain activity, make united decisions, and interact with other DAOs.Ultimately, DAOs unlock an unprecedented level of transparent and collaborative coordination with built-in tools to allow for: * Transparency and legitimacy via built-in reporting * Community ownership through stakeholder participation * Responsible fund distribution through openness and transparency which results in meaningful accountability ## DAOs on NEAR In line with the goal of being the most accessible, user-friendly blockchain, DAOs on NEAR are created in a matter of clicks through the [Astro](https://astrodao.com/) dApp. AstroDAO is a hub of DAOs empowering communities in the NEAR ecosystem. [This playbook](how-to-launch-a-dao.md) will guide you through the process of creating and interacting with DAOs in the NEARverse Astro. ## Your Guide to DAOs The following playbook will serve as documentation and a guide to creating DAOs in Astro, the leading DAO Tooling service on NEAR, as well as a key for unlocking the full potential of DAOs within the NEAR Ecosystem.
--- id: contracts title: Accounts / Contracts --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The RPC API enables you to view details about accounts and contracts as well as perform contract calls. --- ## View account {#view-account} > Returns basic account information. - method: `query` - params: - `request_type`: `view_account` - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) - `account_id`: _`"example.testnet"`_ Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "query", "params": { "request_type": "view_account", "finality": "final", "account_id": "nearkat.testnet" } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.query({ request_type: "view_account", finality: "final", account_id: "nearkat.testnet", }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "view_account", "finality": "final", "account_id": "nearkat.testnet" }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "amount": "399992611103597728750000000", "locked": "0", "code_hash": "11111111111111111111111111111111", "storage_usage": 642, "storage_paid_at": 0, "block_height": 17795474, "block_hash": "9MjpcnwW3TSdzGweNfPbkx8M74q1XzUcT1PAN8G5bNDz" }, "id": "dontcare" } ``` </p> </details> #### What Could Go Wrong? {#what-could-go-wrong} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `view_account` request type: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="5">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>INVALID_ACCOUNT</td> <td>The requested <code>account_id</code> is invalid</td> <td> <ul> <li>Provide a valid <code>account_id</code></li> </ul> </td> </tr> <tr> <td>UNKNOWN_ACCOUNT</td> <td>The requested <code>account_id</code> has not been found while viewing since the account has not been created or has been already deleted</td> <td> <ul> <li>Check the <code>account_id</code></li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>UNAVAILABLE_SHARD</td> <td>The node was unable to find the requested data because it does not track the shard where data is present</td> <td> <ul> <li>Send a request to a different node which might track the shard</li> </ul> </td> </tr> <tr> <td>NO_SYNCED_BLOCKS</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## View account changes {#view-account-changes} > Returns account changes from transactions in a given account. - method: `EXPERIMENTAL_changes` - params: - `changes_type`: `account_changes` - `account_ids`: [`"example.testnet"`] - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "EXPERIMENTAL_changes", "params": { "changes_type": "account_changes", "account_ids": ["your_account.testnet"], "block_id": 19703467 } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.experimental_changes({ changes_type: "account_changes", account_ids: ["nearkat.testnet"], block_id: 19703467, }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_changes \ params:='{ "changes_type": "account_changes", "account_ids": ["your_account.testnet"], "block_id": 19703467 }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "block_hash": "6xsfPSG89s6fCMShxxxQTP6D4ZHM9xkGCgubayTDRzAP", "changes": [ { "cause": { "type": "transaction_processing", "tx_hash": "HLvxLKFM7gohFSqXPp5SpyydNEVpAno352qJJbnddsz3" }, "type": "account_update", "change": { "account_id": "your_account.testnet", "amount": "499999959035075000000000000", "locked": "0", "code_hash": "11111111111111111111111111111111", "storage_usage": 182, "storage_paid_at": 0 } }, { "cause": { "type": "receipt_processing", "receipt_hash": "CPenN1dp4DNKnb9LiL5hkPmu1WiKLMuM7msDjEZwDmwa" }, "type": "account_update", "change": { "account_id": "your_account.testnet", "amount": "499999959035075000000000000", "locked": "0", "code_hash": "11111111111111111111111111111111", "storage_usage": 264, "storage_paid_at": 0 } } ] }, "id": "dontcare" } ``` </p> </details> #### What Could Go Wrong? {#what-could-go-wrong-1} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `EXPERIMENTAL_changes` method: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="2">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>NOT_SYNCED_YET</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## View contract code {#view-contract-code} > Returns the contract code (Wasm binary) deployed to the account. Please note that the returned code will be encoded in base64. - method: `query` - params: - `request_type`: `view_code` - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) - `account_id`: `"guest-book.testnet"`, Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "query", "params": { "request_type": "view_code", "finality": "final", "account_id": "guest-book.testnet" } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.query({ request_type: "view_code", finality: "final", account_id: "guest-book.testnet", }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "view_code", "finality": "final", "account_id": "guest-book.testnet" }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "code_base64": "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=", "hash": "7KoFshMQkdyo5iTx8P2LbLu9jQpxRn24d27FrKShNVXs", "block_height": 17814234, "block_hash": "GT1D8nweVQU1zyCUv399x8vDv2ogVq71w17MyR66hXBB" }, "id": "dontcare" } ``` </p> </details> #### What Could Go Wrong? {#what-could-go-wrong-2} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `view_code` request type: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="6">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>INVALID_ACCOUNT</td> <td>The requested <code>account_id</code> is invalid</td> <td> <ul> <li>Provide a valid <code>account_id</code></li> </ul> </td> </tr> <tr> <td>UNKNOWN_ACCOUNT</td> <td>The requested <code>account_id</code> has not been found while viewing since the account has not been created or has been already deleted</td> <td> <ul> <li>Check the <code>account_id</code></li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>NO_CONTRACT_CODE</td> <td>The account does not have any <code>contract</code> deployed on it</td> <td> <ul> <li>Use different account</li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>UNAVAILABLE_SHARD</td> <td>The node was unable to find the requested data because it does not track the shard where data is present</td> <td> <ul> <li>Send a request to a different node which might track the shard</li> </ul> </td> </tr> <tr> <td>NO_SYNCED_BLOCKS</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## View contract state {#view-contract-state} > Returns the state (key value pairs) of a contract based on the key prefix (base64 encoded). Pass an empty string for `prefix_base64` if you would like to return the entire state. Please note that the returned state will be base64 encoded as well. - method: `query` - params: - `request_type`: `view_state` - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) - `account_id`: `"guest-book.testnet"`, - `prefix_base64`: `""` Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "query", "params": { "request_type": "view_state", "finality": "final", "account_id": "guest-book.testnet", "prefix_base64": "" } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.query({ request_type: "view_state", finality: "final", account_id: "guest-book.testnet", prefix_base64: "", }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "view_state", "finality": "final", "account_id": "guest-book.testnet", "prefix_base64": "" }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "values": [ { "key": "bTo6MA==", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJqb3NoZm9yZC50ZXN0bmV0IiwidGV4dCI6ImhlbGxvIn0=", "proof": [] }, { "key": "bTo6MQ==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiY2hhZG9oIiwidGV4dCI6ImhlbGxvIGVyeWJvZHkifQ==", "proof": [] }, { "key": "bTo6MTA=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoic2F0b3NoaWYudGVzdG5ldCIsInRleHQiOiJIaWxsbyEifQ==", "proof": [] }, { "key": "bTo6MTE=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidmFsZW50aW5lc29rb2wudGVzdG5ldCIsInRleHQiOiJIaSEifQ==", "proof": [] }, { "key": "bTo6MTI=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJobngudGVzdG5ldCIsInRleHQiOiJoZWxsbyJ9", "proof": [] }, { "key": "bTo6MTM=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJobngudGVzdG5ldCIsInRleHQiOiJzZCJ9", "proof": [] }, { "key": "bTo6MTQ=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiamdoZy50ZXN0bmV0IiwidGV4dCI6IktoZyJ9", "proof": [] }, { "key": "bTo6MTU=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiYWNjb3VudC50ZXN0bmV0IiwidGV4dCI6IldoZW4gSUNPPyJ9", "proof": [] }, { "key": "bTo6MTY=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiYWNjb3VudC50ZXN0bmV0IiwidGV4dCI6IlRlc3QgMiJ9", "proof": [] }, { "key": "bTo6MTc=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidGVzdC1kcm9wLTEwLnRlc3RuZXQiLCJ0ZXh0IjoiRnJlZSBtZXNzYWdlcyBhcmUgdGhlIGJlc3QifQ==", "proof": [] }, { "key": "bTo6MTg=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidGVzdC1kcm9wLTEwLnRlc3RuZXQiLCJ0ZXh0IjoiV2hlbiBJQ08/In0=", "proof": [] }, { "key": "bTo6MTk=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidGVzdC1kcm9wLTEwLnRlc3RuZXQiLCJ0ZXh0IjoiV2hlbiBJQ08/In0=", "proof": [] }, { "key": "bTo6Mg==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoibnVsbCIsInRleHQiOiJ1bmRlZmluZWQifQ==", "proof": [] }, { "key": "bTo6MjA=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidGVzdC04NDEudGVzdG5ldCIsInRleHQiOiJXaGVuIElDTz8ifQ==", "proof": [] }, { "key": "bTo6MjE=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidGVzdC04NDEudGVzdG5ldCIsInRleHQiOiJoZXkgaGV5IGhleSJ9", "proof": [] }, { "key": "bTo6MjI=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiam9zaGZvcmQudGVzdG5ldCIsInRleHQiOiJoaSJ9", "proof": [] }, { "key": "bTo6MjM=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiam9zaGZvcmQudGVzdG5ldCIsInRleHQiOiJoaSB4MiJ9", "proof": [] }, { "key": "bTo6MjQ=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoibWFzdGVydGh5c2VsZi50ZXN0bmV0IiwidGV4dCI6ImhhbmRzaGFrZS5oYWNrbWVkb21haW4vICJ9", "proof": [] }, { "key": "bTo6MjU=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJtYXN0ZXJ0aHlzZWxmLnRlc3RuZXQiLCJ0ZXh0IjoiSGVsbG8gQ29zbW9zLCBob21lLmNvc21hdHJpeGNvbm5lY3Rpb25zLyJ9", "proof": [] }, { "key": "bTo6MjY=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJtYXN0ZXJ0aHlzZWxmLnRlc3RuZXQiLCJ0ZXh0IjoiYnVpbGQsIGJ1aWxkLCBidWlsZCBpIGNhbWUgdG8gYnVpbGQgYSBicmlkZ2UgaW4gUEVBQ0UsIHNvIGNvbWUgbGV0cyBidWlsZC4uLnNvbmcgYnkgXCJOYWhrbyBCZWFyXCIgIn0=", "proof": [] }, { "key": "bTo6Mjc=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJtYXN0ZXJ0aHlzZWxmLnRlc3RuZXQiLCJ0ZXh0IjoiYnVpbGQgYSBicmlkZ2UgKGh0dHBzOi8vd3d3Lmdvb2dsZS5jb20vdXJsP3NhPXQmcmN0PWomcT0mZXNyYz1zJnNvdXJjZT13ZWImY2Q9JmNhZD1yamEmdWFjdD04JnZlZD0yYWhVS0V3ajA0ZGlnMTlqckFoV05tbGtLSGR5X0FnUVEzeXd3QUhvRUNBVVFBZyZ1cmw9aHR0cHMlM0ElMkYlMkZ3d3cueW91dHViZS5jb20lMkZ3YXRjaCUzRnYlM0Rlb1RYNWZmOVplMCZ1c2c9QU92VmF3MFoxZzFIMkZzeF85d3FJSmg5RTk2UCkifQ==", "proof": [] }, { "key": "bTo6Mjg=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJtYXN0ZXJ0aHlzZWxmLnRlc3RuZXQiLCJ0ZXh0IjoiaHR0cDovL3RyaXBweS7wn42EbWFnaWMvIn0=", "proof": [] }, { "key": "bTo6Mjk=", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJtYXN0ZXJ0aHlzZWxmLnRlc3RuZXQiLCJ0ZXh0IjoiaHR0cDovL3VuaXRlLnJhaW5ib3d0cmliZXMvIn0=", "proof": [] }, { "key": "bTo6Mw==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiam9zaGZvcmQudGVzdG5ldCIsInRleHQiOiJobW1tbW1tIn0=", "proof": [] }, { "key": "bTo6MzA=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiZXhlbXBsYXJ5LnRlc3RuZXQiLCJ0ZXh0IjoiaGVsbG8ifQ==", "proof": [] }, { "key": "bTo6MzE=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiYWRpMjMudGVzdG5ldCIsInRleHQiOiJobW0ifQ==", "proof": [] }, { "key": "bTo6MzI=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiYWRpMjMudGVzdG5ldCIsInRleHQiOiJ3aGF0In0=", "proof": [] }, { "key": "bTo6MzM=", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoidmxhZGJhc2gudGVzdG5ldCIsInRleHQiOiJIaSJ9", "proof": [] }, { "key": "bTo6NA==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoibnVsbCIsInRleHQiOiIgIn0=", "proof": [] }, { "key": "bTo6NQ==", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJ0ZXN0YWNjb3VudDEudGVzdG5ldCIsInRleHQiOiJ0ZXN0In0=", "proof": [] }, { "key": "bTo6Ng==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiZXVnZW5ldGhlZHJlYW0iLCJ0ZXh0IjoibnVsbCJ9", "proof": [] }, { "key": "bTo6Nw==", "value": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiZGVtby50ZXN0bmV0IiwidGV4dCI6Ikkgb25seSB3cml0ZSBmcmVlIG1lc3NhZ2VzLiJ9", "proof": [] }, { "key": "bTo6OA==", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJqb3NoZm9yZC50ZXN0bmV0IiwidGV4dCI6IkkgcHJlZmVyIHByZW1pdW0gbWVzc2FnZXMifQ==", "proof": [] }, { "key": "bTo6OQ==", "value": "eyJwcmVtaXVtIjp0cnVlLCJzZW5kZXIiOiJuZXdsZWRnZXIzLnRlc3RuZXQiLCJ0ZXh0IjoiTGVkZ2VyIn0=", "proof": [] }, { "key": "bTpsZW4=", "value": "MzQ=", "proof": [] } ], "proof": [], "block_height": 17814234, "block_hash": "GT1D8nweVQU1zyCUv399x8vDv2ogVq71w17MyR66hXBB" }, "id": "dontcare" } ``` </p> **Note**: Currently, the response includes a `proof` field directly in the `result`, and a `proof` fields on each element of the `values` list. In the future, the `result.proof` will be included only if the result is **not empty**, and the `proof` field will be removed from all `values`. When parsing the result, you should accept objects with or without these fields set. </details> > **Heads up** > > There is a limitation on default RPC nodes. You won't be able to get the contract state if it is too big. The default limit of for contract state is 50kb of state size. You're able to change the limits if you [run your own RPC node](https://near-nodes.io/validator/compile-and-run-a-node) with adjusted `trie_viewer_state_size_limit` value in `config.json` #### What Could Go Wrong? {#what-could-go-wrong-3} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `view_state` request type: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="7">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>INVALID_ACCOUNT</td> <td>The requested <code>account_id</code> is invalid</td> <td> <ul> <li>Provide a valid <code>account_id</code></li> </ul> </td> </tr> <tr> <td>UNKNOWN_ACCOUNT</td> <td>The requested <code>account_id</code> has not been found while viewing since the account has not been created or has been already deleted</td> <td> <ul> <li>Check the <code>account_id</code></li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>NO_CONTRACT_CODE</td> <td>The account does not have any <code>contract</code> deployed on it</td> <td> <ul> <li>Query and account with contract deployed</li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>TOO_LARGE_CONTRACT_STATE</td> <td>The requested contract state is too large to be returned from this node (the default limit is 50kb of state size)</td> <td> <ul> <li>Send the request to a node with larger limits in order to view the requested state</li> <li>Spin up your own node where you can increase the limits to view state</li> </ul> </td> </tr> <tr> <td>UNAVAILABLE_SHARD</td> <td>The node was unable to find the requested data because it does not track the shard where data is present</td> <td> <ul> <li>Send a request to a different node which might track the shard</li> </ul> </td> </tr> <tr> <td>NO_SYNCED_BLOCKS</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## View contract state changes {#view-contract-state-changes} > Returns the state change details of a contract based on the key prefix (encoded to base64). Pass an empty string for this param if you would like to return all state changes. - method: `EXPERIMENTAL_changes` - params: - `changes_type`: `data_changes` - `account_ids`: `["example.testnet"]`, - `key_prefix_base64`: `"base64 encoded key value"`, - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "EXPERIMENTAL_changes", "params": { "changes_type": "data_changes", "account_ids": ["guest-book.testnet"], "key_prefix_base64": "", "block_id": 19450732 } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.experimental_changes({ changes_type: "data_changes", account_ids: ["guest-book.testnet"], key_prefix_base64: "", block_id: 19450732, }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_changes \ params:='{ "changes_type": "data_changes", "account_ids": ["guest-book.testnet"], "key_prefix_base64": "", "block_id": 19450732 }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "block_hash": "6U8Yd4JFZwJUNfqkD4KaKgTKmpNSmVRTSggpjmsRWdKY", "changes": [ { "cause": { "type": "receipt_processing", "receipt_hash": "9ewznXgs2t7vRCssxW4thgaiwggnMagKybZ7ryLNTT2z" }, "type": "data_update", "change": { "account_id": "guest-book.testnet", "key_base64": "bTo6Mzk=", "value_base64": "eyJwcmVtaXVtIjpmYWxzZSwic2VuZGVyIjoiZmhyLnRlc3RuZXQiLCJ0ZXh0IjoiSGkifQ==" } }, { "cause": { "type": "receipt_processing", "receipt_hash": "9ewznXgs2t7vRCssxW4thgaiwggnMagKybZ7ryLNTT2z" }, "type": "data_update", "change": { "account_id": "guest-book.testnet", "key_base64": "bTpsZW4=", "value_base64": "NDA=" } } ] }, "id": "dontcare" } ``` </p> </details> #### What Could Go Wrong? {#what-could-go-wrong-4} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `EXPERIMENTAL_changes` method: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="2">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>NOT_SYNCED_YET</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## View contract code changes {#view-contract-code-changes} > Returns code changes made when deploying a contract. Change is returned is a base64 encoded WASM file. - method: `EXPERIMENTAL_changes` - params: - `changes_type`: `contract_code_changes` - `account_ids`: `["example.testnet"]`, - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) Example: <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "EXPERIMENTAL_changes", "params": { "changes_type": "contract_code_changes", "account_ids": ["dev-1602714453032-7566969"], "block_id": 20046655 } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.experimental_changes({ changes_type: "contract_code_changes", account_ids: ["dev-1602714453032-7566969"], block_id: 20046655, }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=EXPERIMENTAL_changes \ params:='{ "changes_type": "contract_code_changes", "account_ids": ["dev-1602714453032-7566969"], "block_id": 20046655 }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "block_hash": "3yLNV5zdpzRJ8HP5xTXcF7jdFxuHnmKNUwWcok4616WZ", "changes": [ { "cause": { "type": "receipt_processing", "receipt_hash": "CEm3NNaNdu9cijh9NvZMM1srbtEYSsBVwGbZxFQYKt5B" }, "type": "contract_code_update", "change": { "account_id": "dev-1602714453032-7566969", "code_base64": "AGFzbQEAAAABpAM3YAF/AGAAAX9gAn9+AGADf35+AGAEf35+fgF+YAZ/fn5+fn4BfmADf35+AX5gAn9+AX5gAn9/AX9gAn9/AGADf39/AX9gAX8BfmACfn4AYAF+AX5gAX4AYAABfmADfn5+AGAAAGAIfn5+fn5+fn4BfmAJfn5+fn5+fn5+AX5gAn5+AX5gA35+fgF+YAd+fn5+fn5+AGAEfn5+fgBgCX5+fn5+fn5+fgBgBX5+fn5+AX5gA39/fwBgAX8Bf2ACf3wAYAR/f39+AGAFf39/fn8AYAV/f39/fwBgBH9/f38AYAN/f38BfmADf39+AGACf38BfmAFf39/f38Bf2AEf39/fwF/YAZ/f39/f38AYAV/f35/fwBgBH9+f38Bf2ACf34Bf2AHf35+f39+fwBgBX9/f39+AGAEf35+fgBgCX9+fn5+fn5+fgF+YAp/fn5+fn5+fn5+AX5gCH9+fn5+fn5+AGAFf35+fn4AYAp/fn5+fn5+fn5+AGAHf39/f39/fwBgBH98f38Bf2AGf39/f39..." } } ] }, "id": "dontcare" } ``` </p> </details> #### What Could Go Wrong? {#what-could-go-wrong-5} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `EXPERIMENTAL_changes` method: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="2">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>NOT_SYNCED_YET</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> --- ## Call a contract function {#call-a-contract-function} > Allows you to call a contract method as a [view function](../../4.tools/cli.md#near-view-near-view). - method: `query` - params: - `request_type`: `call_function` - [`finality`](/api/rpc/setup#using-finality-param) _OR_ [`block_id`](/api/rpc/setup#using-block_id-param) - `account_id`: _`"example.testnet"`_ - `method_name`: `name_of_a_example.testnet_method` (example [`view` methods](https://github.com/near/core-contracts/blob/master/staking-pool/src/lib.rs#L317) - `args_base64`: `method_arguments_base_64_encoded` Example (`get_num`): <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "query", "params": { "request_type": "call_function", "finality": "final", "account_id": "dev-1588039999690", "method_name": "get_num", "args_base64": "e30=" } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.query({ request_type: "call_function", finality: "final", account_id: "dev-1588039999690", method_name: "get_num", args_base64: "e30=", }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "call_function", "finality": "final", "account_id": "dev-1588039999690", "method_name": "get_num", "args_base64": "e30=" }' ``` </TabItem> </Tabs> Example (`get_account_staked_balance`): The `args_base64` in this example is decoded as `{"account_id":"dev-1588039999690"}`. The `account_id` would likely be the validator and not the same account for this particular view function. <Tabs> <TabItem value="json" label="JSON" default> ```json { "jsonrpc": "2.0", "id": "dontcare", "method": "query", "params": { "request_type": "call_function", "finality": "final", "account_id": "dev-1588039999690", "method_name": "get_account_staked_balance", "args_base64": "eyJhY2NvdW50X2lkIjoiZGV2LTE1ODgwMzk5OTk2OTAifQ==" } } ``` </TabItem> <TabItem value="js" label="🌐 JavaScript" label="JavaScript"> ```js const response = await near.connection.provider.query({ request_type: "call_function", finality: "final", account_id: "dev-1588039999690", method_name: "get_account_staked_balance", args_base64: "eyJhY2NvdW50X2lkIjoiZGV2LTE1ODgwMzk5OTk2OTAifQ==", }); ``` </TabItem> <TabItem value="http" label="HTTPie"> ```bash http post https://rpc.testnet.near.org jsonrpc=2.0 id=dontcare method=query \ params:='{ "request_type": "call_function", "finality": "final", "account_id": "dev-1588039999690", "method_name": "get_account_staked_balance", "args_base64": "eyJhY2NvdW50X2lkIjoiZGV2LTE1ODgwMzk5OTk2OTAifQ==" }' ``` </TabItem> </Tabs> <details> <summary>Example response: </summary> <p> ```json { "jsonrpc": "2.0", "result": { "result": [48], "logs": [], "block_height": 17817336, "block_hash": "4qkA4sUUG8opjH5Q9bL5mWJTnfR4ech879Db1BZXbx6P" }, "id": "dontcare" } ``` **Note**: `[48]` is an array of bytes, to be specific it is an ASCII code of `0`.`near-sdk-rs` and `near-sdk-js` return JSON-serialized results. </p> </details> #### What Could Go Wrong? {#what-could-go-wrong-6} When API request fails, RPC server returns a structured error response with a limited number of well-defined error variants, so client code can exhaustively handle all the possible error cases. Our JSON-RPC errors follow [verror](https://github.com/joyent/node-verror) convention for structuring the error response: ```json { "error": { "name": <ERROR_TYPE>, "cause": { "info": {..}, "name": <ERROR_CAUSE> }, "code": -32000, "data": String, "message": "Server error", }, "id": "dontcare", "jsonrpc": "2.0" } ``` > **Heads up** > > The fields `code`, `data`, and `message` in the structure above are considered legacy ones and might be deprecated in the future. Please, don't rely on them. Here is the exhaustive list of the error variants that can be returned by `call_function` request type: <table className="custom-stripe"> <thead> <tr> <th> ERROR_TYPE<br /> <code>error.name</code> </th> <th>ERROR_CAUSE<br /><code>error.cause.name</code></th> <th>Reason</th> <th>Solution</th> </tr> </thead> <tbody> <tr> <td rowspan="7">HANDLER_ERROR</td> <td>UNKNOWN_BLOCK</td> <td>The requested block has not been produced yet or it has been garbage-collected (cleaned up to save space on the RPC node)</td> <td> <ul> <li>Check that the requested block is legit</li> <li>If the block had been produced more than 5 epochs ago, try to send your request to <a href="https://near-nodes.io/intro/node-types#archival-node">an archival node</a></li> </ul> </td> </tr> <tr> <td>INVALID_ACCOUNT</td> <td>The requested <code>account_id</code> is invalid</td> <td> <ul> <li>Provide a valid <code>account_id</code></li> </ul> </td> </tr> <tr> <td>UNKNOWN_ACCOUNT</td> <td>The requested <code>account_id</code> has not been found while viewing since the account has not been created or has been already deleted</td> <td> <ul> <li>Check the <code>account_id</code></li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>NO_CONTRACT_CODE</td> <td>The requested <code>contract_code</code> has not been found while viewing</td> <td> <ul> <li>Check the <code>public_key</code></li> <li>Specify a different block or retry if you request the latest state</li> </ul> </td> </tr> <tr> <td>CONTRACT_EXECUTION_ERROR</td> <td>The execution of the view function call failed (crashed, run out of the default 200 TGas limit, etc)</td> <td> <ul> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>UNAVAILABLE_SHARD</td> <td>The node was unable to find the requested data because it does not track the shard where data is present</td> <td> <ul> <li>Send a request to a different node which might track the shard</li> </ul> </td> </tr> <tr> <td>NO_SYNCED_BLOCKS</td> <td>The node is still syncing and the requested block is not in the database yet</td> <td> <ul> <li>Wait until the node finish syncing</li> <li>Send a request to a different node which is synced</li> </ul> </td> </tr> <tr className="stripe"> <td>REQUEST_VALIDATION_ERROR</td> <td>PARSE_ERROR</td> <td>Passed arguments can't be parsed by JSON RPC server (missing arguments, wrong format, etc.)</td> <td> <ul> <li>Check the arguments passed and pass the correct ones</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> <tr> <td>INTERNAL_ERROR</td> <td>INTERNAL_ERROR</td> <td>Something went wrong with the node itself or overloaded</td> <td> <ul> <li>Try again later</li> <li>Send a request to a different node</li> <li>Check <code>error.cause.info</code> for more details</li> </ul> </td> </tr> </tbody> </table> ---
--- id: what-is title: What is Data Infrastructure? --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import {CodeTabs, Language, Github} from "@site/src/components/codetabs" NEAR offers ready-to-use solutions to access and monitor on-chain data easily. This is very useful to automate actions based on specific **events**, cache data to **reduce latency**, gather **usage data** of the blockchain, and even **study user preferences**. ![img](/docs/assets/welcome-pages/data-lake.png) NEAR offers three main solutions to access and monitor on-chain data: [**BigQuery Public Dataset**](#bigquery-public-dataset), [**QueryAPI**](#queryapi-indexers-made-simple), and [**NEAR Lake**](#near-lake). Each of these solutions is designed to fit different needs and use cases, and can be used in combination to create a complete data infrastructure for your application. --- ## [BigQuery: Public Dataset](./big-query.md) A large dataset with on-chain data publicly available on Google Cloud Platform. Obtain near real-time blockchain data using simple SQL queries. **All the data, zero setup**. - Instant insights: Historic on-chain data queried at scale. No need to run your own infrastructure. - Cost-effective: Eliminate the need to store and process bulk NEAR Protocol data. Query as little or as much data as you like. - As easy as SQL: No prior experience with blockchain technology is required. Just bring a general knowledge of SQL to unlock insights. <hr subclass="subsection" /> ## [QueryAPI: Indexers Made Simple](./query-api/intro.md) A fully managed solution to build indexer functions, extract on-chain data, and easily query it using GraphQL endpoints and subscriptions. - Your data, your way: Decide how you want to store data. Design the tables and databases that better suit your needs. - Indexers made simple: Create the logic of your indexer and we will execute it for you. Forget about infrastructure—focus on solutions. - Plug & play to your app: Fetch your data from any application through our API. Leverage GraphQL to query exactly what you need. <hr subclass="subsection" /> ## [NEAR Lake](./lake-framework/near-lake.md) A solution that watches over the NEAR network and stores all the events for your easy access. - Cost-efficient solution: Cost-efficient solution for building self-hosted indexers in Rust, JavaScript, Python, Go and other languages - Streamlined data management: Use NEAR Lake Framework to stream blocks to your server directly from NEAR Lake
Berklee College of Music Partners with NEAR Foundation to Build Music Licensing Platform NEAR FOUNDATION November 2, 2023 Berklee College of Music, the largest independent college of contemporary music and performing arts in the world, announced today a partnership with the NEAR Foundation to help build a music licensing platform. The agreement, which will harness NEAR Protocol’s easy-to-use tech stack, will lead to the creation of a marketplace where musicians can upload their music, and creators can license music from the students of this world-class music institution. The project will be released under an app called RAIDAR, which stands for Rights and Asset Information in Decentralized, Authoritative Repositories. Thanks to NEAR’s Web3 technology, all transactions will be recorded on the NEAR blockchain, ensuring a creators’ rights and representation are recorded on-chain. Behind Berklee’s music licensing app, built on NEAR RAIDAR will use smart contracts to disintermediate the licensing process and ensure that musicians receive the full economic value and credit for their works. “This is a first of its kind product that will help to democratize the world of music by putting creators first and ensuring they are always rewarded and protected from exploitation for their original work,” says George Howard, Distinguished Professor of Music Business at Berklee. “Those who are seeking to license music for their projects now have a chance to access and support new creators by tapping into an exciting marketplace through the RAIDAR app, which is easy to navigate and offers a safe and reliable way to pay for music.” RAIDAR — simple to use, accessible to all The product is designed to be simple to use, which is a cornerstone of building on the NEAR Protocol. Musicians simply upload their music files and relevant metadata through a mobile- and desktop-friendly web app. Their song is then represented by a unique, secure smart contract and assigned to the creator’s wallet as an asset or NFT, empowering the creator to view and showcase the song, wherever they go. On the customer side, users can browse, search, and preview songs uploaded to the RAIDAR app and purchase single-use licenses for songs via the app. The song’s smart contract distributes funds received from the payment to the song’s creator. After the purchase transaction completes, the buyer receives an email with the corresponding song download link and a copy of the license agreement. “We are extremely excited to be working with Berklee to support a new and unique use case that has real world value for those that use it,” says Chris Donovan, CEO of the NEAR Foundation. “The RAIDAR app is a disruptive technology built on NEAR that will help students to explore the power of smart contracts to ensure they are being paid fairly for their work, and that the world of music becomes more inclusive, safe and exciting for everyone.”
```js import { Wallet } from './near-wallet'; const KEYPOM_CONTRACT_ADDRESS = "v2.keypom.near"; const NFT_CONTRACT_ADDRESS = "nft.primitives.near"; const NFT_TOKEN_ID = "1"; const DROP_AMOUNT = "10000000000000000000000"; const nftConnectedWallet = new Wallet({ createAccessKeyFor: NFT_CONTRACT_ADDRESS }); await wallet.callMethod({ method: "nft_transfer_call", contractId: NFT_CONTRACT_ADDRESS, args: { receiver_id: keypomContract, token_id: nftTokenId, msg: dropId.toString() }, deposit: 1, gas: "100000000000000", }); ``` _The `Wallet` object comes from our [quickstart template](https://github.com/near-examples/hello-near-examples/blob/main/frontend/near-wallet.js)_
--- id: get-started --- # Getting Started ## Install Rust and Wasm toolchain Follow [these instructions](https://doc.rust-lang.org/book/ch01-01-installation.html) for setting up Rust. To install Rust on Linux or MacOS, use the following command: ```bash curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh source $HOME/.cargo/env ``` Then, add the `wasm32-unknown-unknown` toolchain. This toolchain is required because the contracts that we will build will be compiled to [Wasm](https://webassembly.org/) to run on the NEAR blockchain. ```bash rustup target add wasm32-unknown-unknown ``` ## Create a new project The best way to create a new NEAR app connected with a frontend is through [create-near-app](https://github.com/near/create-near-app). When initializing the project, your option are `npx create-near-app <projectName> [--frontend next|vanilla|none] [--contract rs|ts|none --tests rs|ts|none]`. ```bash npx create-near-app my-project --contract rs --frontend none --tests rs ``` If you only wish to develop and deploy a Rust contract, the [status message example](https://github.com/near-examples/rust-status-message) is great to use as a template or through [cargo-generate](https://github.com/cargo-generate/cargo-generate). To initialize a new project with `cargo-generate`, run the following commands: ```bash cargo install cargo-generate --features vendored-openssl cargo generate --git https://github.com/near-examples/rust-status-message --name my-project cd my-project ``` If you would like to generate a new crate manually with `cargo new --lib <crate-name>`, make sure you include the following configuration in the generated `Cargo.toml`: ```toml [dependencies] near-sdk = "4.0.0" [lib] crate-type = ["cdylib"] [profile.release] codegen-units = 1 # Tell `rustc` to optimize for small code size. opt-level = "z" lto = true debug = false panic = "abort" # Opt into extra safety checks on arithmetic operations https://stackoverflow.com/a/64136471/249801 overflow-checks = true ```
--- id: intro title: Moving from Web 2 to Web 3 sidebar_label: Introduction --- by Sigma Software >DISCLAIMER. All references to particular products, frameworks, solutions, libraries and other software of NEAR ecosystem are provided for educational purposes only. All product names, logos, brands, trademarks and registered trademarks are property of their respective owners. Use of these names, trademarks and brands throughout the document does not imply endorsement. ## Introduction In this guideline we’ll see how to bring a traditional Web 2 application into a Web 3 world using NEAR Protocol. It’s written for developers who are just starting their journey into the world of Web 3 and Blockchain, so we’ll start by explaining what Web 3 and blockchain are. Then, we’ll explore how to build decentralized applications (dApps) using NEAR Protocol. And after we’ve learned the basics, we’ll guide you through the intricacies of fusing client applications, traditional web servers and the NEAR blockchain. During our journey we’ll focus on high-level decisions, architecture, and explore not just HOW to do something, but also WHY it’s done this way. And as with anything, there’s no single right way, so we’ll explore different alternatives and help you to choose the right one. Of course, real world applications aren’t built with words, but with code, so links to numerous code examples will be provided. But to make it as useful as possible, this guideline itself will be kept implementation and technology agnostic whenever possible. If you are already familiar with Web 3 and blockchains, feel free to skip to the [NEAR Protocol section](near.md). And if you are already quite comfortable with NEAR, you can jump straight ahead into the [NFTs for Web 2 Applications](nfts.md) chapter, where we’ll guide you on how to connect Web 2 and the NEAR blockchain together to bring the full power of NFTs into your app. Without further ado, let’s begin our journey!
Women in Web3 Changemakers: Emily Rose Dallara NEAR FOUNDATION September 26, 2023 “A lot of the clients I work with don’t feel that they’re ever on top of anything,” says Emily Rose Dallara, an award winning leadership coach and founder of the Web 3 and Thrive Podcast. Dallara is one of the 10 finalists of the 2023 Women in Web3 Changemakers List, an annual competition designed to champion women pushing boundaries in the space. Dallara, along with nine other outstanding candidates, is showing the industry the change women are bringing about during the advent of the Open Web. Dallara was selected because of her work helping ambitious leaders confidently succeed without constant self-doubt or working 24/7. “There’s always been this golden thread throughout my whole experience, which is helping other people thrive, elevating people, especially women, because we didn’t have much of a voice back then, when I first started out.” But Dallara’s expertise in helping others came at a personal cost. Dallara had to learn through challenging personal experiences what happens when the fast-paced world of Web3 creeps ever further into your personal life and what can happen when boundaries are not in place. Watch an extended NEAR Foundation video interview with Emily Rose Dallara below. Burning out “I’ve had two burnouts and two layoffs, both related,” says Dallara, from her home in France. “I just wanted to succeed. I wanted to make all the money that was promised. I wanted to learn as much as I could. And I just didn’t see another way of working. It was a 24/7 grind.” Dallara began her Web3 journey while living in and working in Bali. “I was very much on the humanitarian side. I did a lot of work in Southeast Asia and Japan, helping with merchant onboarding, and had my own e-commerce platform for women.” She found a niche helping young female entrepreneurs accept crypto from international clients, creating payment rails for merchants, before joining Bitcoin.com as a marketing manager. A flurry of advisory roles followed, and her CV quickly became a Who’s Who of the crypto community. “I just didn’t have the boundaries in place. I didn’t have a support network in place, I didn’t have the experience to prevent that from happening. So I burnt out. And then a bit later when I was a marketing director.” Finding a new path After a period of recovery and reflection, Dallara began to ask herself if she wanted to stay in the industry, and if she did, what would a different path look like. And it was during this period she found that a lot of the clients and colleagues she had worked with had experienced similar issues. “Because it’s such a rapidly changing space that’s constantly innovating, they feel that if they don’t stay on top, or they don’t have all the information they need, or they don’t reply to Slack messages all the time, that they’re not going to succeed. That’s what they’re scared of. And so this was a fear that I carried as well. And it took me a long time to unravel that and understand that it wasn’t a valid fear.” But Dallara used that fear to help her understand what she should do next. After qualifying as an accredited coach, she decided she wanted to help other women learn the lessons she had without having to burn out first. “We’re trying to create a bit of a movement. We can’t just go say to the VCs, ‘you need to train the people that you’re invested in as better leaders’. It’s not as simple as that. We have to make people aware first, we can’t make any changes without that.” Given her experience working at the breakneck speeds of the Web3 world, would she recommend the industry to other women? “It’s a huge opportunity. I would never have been in the roles I’ve been in in web two, it would have been a much, much slower process. It gave me the space to understand what I was really good at, in a really short time because people kept throwing opportunities at me because it was rare to have a woman who was a marketing leader in the space.” Dallara advises any women looking at this space to be, above all, curious. “Know that you can make this whatever you want to make it. There’s no rules. You can build whatever you want to build, you can create the role, whatever you want to create. And it’s up to you to determine how you do that. And when.
--- id: introduction sidebar_label: Home title: NEAR RPC API --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The RPC API allows you to communicate directly with the NEAR network. For example, tools such as [near-api-js](/tools/near-api-js/quick-reference) are just abstractions making RPC calls. <hr className="subsection" /> ## RPC Providers There are multiple [RPC providers which you can choose from](./providers.md). These providers will work as intermediaries to help you interact with the NEAR network. <hr className="subsection" /> ## NEAR RPC - Quick Links | API | Description | |-----------------------------------------------------|------------------------------------------------------------------------------| | [Access Keys](/api/rpc/access-keys) | Retrieve information about an account's access keys. | | [Accounts / Contracts](/api/rpc/contracts) | View details about accounts and contracts as well as perform contract calls. | | [Block / Chunk](/api/rpc/block-chunk) | Query the network and get details about specific blocks or chunks. | | [Gas](/api/rpc/gas) | Get gas price for a specific block or hash. | | [Protocol](/api/rpc/protocol) | Retrieve current genesis and protocol configuration. | | [Network](/api/rpc/network) | Return status information for nodes and validators. | | [Transactions](/api/rpc/transactions) | Send transactions and query their status. | | [Maintenance Windows](/api/rpc/maintenance-windows) | Query the maintenance windows in current epoch for a validator. | :::tip You can access the JSON RPC 2.0 endpoints using [Postman](/api/rpc/setup#postman-setup), [JavaScript](/api/rpc/setup#javascript-setup), and [HTTPie](/api/rpc/setup#httpie-setup). :::
--- 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 build artifact can be affected by the locale, timezone, build path, and billion other factors in your build environment. Rust community has a long story of fighting this issue but still, [it is not achieved yet](https://github.com/rust-lang/rust/labels/A-reproducibility). ## CI solution We recommend you to build your contracts with the use of our [Contract Builder](https://github.com/near/near-sdk-rs/tree/master/contract-builder). It's is using Docker, controlled and sharable environment that can be used by both you and your users. Docker image is available [here](https://hub.docker.com/r/nearprotocol/contract-builder). The contract built in it will result in a binary that is the same if built on other machines.
--- title: Trust and Safety description: Overview of Moderation Framework on NEAR BOS sidebar_position: 7 --- # T&S Content Moderation ### Highlights: * 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. ### What it is: The moderation framework is an open-source, decentralized content moderation system built on the Blockchain Operating System (BOS) and specifically designed for Web3 platforms. It leverages the power of the BOS to tackle the challenges of managing User Generated Content (UGC) through community engagement and automation, providing a scalable, transparent solution to content review that is easy to use and legally compliant. ### Why it matters: The ever-increasing volume of online content and communities necessitates a robust, scalable and transparent moderation system to manage potentially offensive, risky or illegal content. Traditional content moderation processes, which are centralized and often lack transparency, are ill-equipped to meet these demands. With the growing influence of Web3 platforms the need for an innovative solution that addresses these challenges is more critical than ever. Moderation, built on the BOS offers a decentralized approach that empowers users and ensures that content moderation remains scalable and adaptable to the evolving digital landscape. By leveraging the BOS, the moderation framework not only mitigates the risks of overregulation, consumer backlash and reputational damage but also ensures compliance with regional legal requirements, something that is crucial in a world where content moderation legislation varies significantly across countries and regions. Through the use of AI, the moderation system also addresses the often overlooked mental health concerns of content moderators themselves, creating a more positive, healthier experience. With its decentralized approach and community-driven governance and moderation, the moderation framework is poised to redefine content moderation for Web3 platforms and contribute significantly to a healthier online environment for all stakeholders. ### Who it’s for: * Developers - Developers can implement the moderation framework into their Web3 projects to manage UGC and create a safe environment allowing them to focus on core features. * Users - Users interact with the moderation framework through an efficient reporting system, and they also have access to a wide range of tools enabling them to manage their feed content and experience. * Decentralized moderators - A user-friendly dashboard makes it easy for decentralized moderators to participate in content moderation and receive token rewards, fostering high quality moderation and mental well-being. * Internal and third party teams - Internal moderator teams or NGO that require a content moderation tool for their needs. * Social Media or other platforms - By adopting the moderation framework, social media, e-commerce and any other platform with UGC content can gain an open-course decentralized moderation system that promotes scalability, trust, and user satisfaction. ### How it works: * Reporting flow * Users can report any type of content (e.g. post, comment, Communities, account, etc.). * The content goes through automations, and different sets of actions are applied (e.g. violative content, auto-approve, suspicious content). * Suspicious content is assessed by the decentralized community, internal teams, or NGOs depending on the issue type and risk. * The content is reviewed and the reporter is informed of the decision. * Detection and automation * A different set of automations including CV, NLP, and ASR model will run at different times (e.g. content creation, content update, content being queued for review, content being reviewed) when users and moderators are interacting with content. * Moderator verification * Any user who would like to sign up to be a community moderator would need to go through a light KYC process and training. They will have access to support to do their job on a regular basis, and will be rewarded through tokens. ![](@site/static/img/t-and-s.png) ### What’s coming next: * Collaboration with legal teams to ensure compliance with regional legal requirements using the BOS and development of policies. * Ongoing analysis of competitors and alternative solutions to remain ahead of industry developments. * Improving UI and content reporting flow for users. * Further development and integration of machine learning technologies for more accurate automations.
--- id: deploy-on-mainnet title: Deploy Mainnet Staking Pool sidebar_label: Deploy Mainnet Staking Pool sidebar_position: 5 --- Deploying a node on `mainnet` is similar to deploying one on `testnet` and requires the following steps: 1. Create `mainnet` wallet. 2. Build `mainnet` validator node daemon. 3. Initialize the node. 4. Deploy `mainnet` staking pool. 5. Run the validator node. ### 1. Create `mainnet` wallet {#create-wallet} If you don’t have a NEAR account, first go to [NEAR Wallet](https://wallet.near.org/) and create one. ### 2. Build `mainnet` validator node daemon {#build-node} To build the validator first clone the [`nearcore` repository](https://github.com/near/nearcore): ```bash git clone https://github.com/near/nearcore.git ``` Once that’s done, figure out [the most recent stable release](https://github.com/near/nearcore/releases). Stable releases are ones without `-rc.<number>` suffix (‘rc’ stands for ‘release candidate’). This can be done automatically as follows: ```bash NEAR_RELEASE_VERSION=$(curl -s https://github.com/near/nearcore/releases/latest | tr '/" ' '\n' | grep "[0-9]\.[0-9]*\.[0-9]" | head -n 1) ``` Now, go to the cloned repository’s root directory and checkout the code corresponding to the latest stable release: ```bash cd nearcore git checkout "refs/heads/${NEAR_RELEASE_VERSION:?}" ``` Finally, build the executable using `make`. Note that building with `cargo build --release` command *is not* sufficient to create fully optimized executable: ```bash make neard ``` ### 3. Initialize the node {#init-node} Once the daemon executable is built it’s time to initialize the node. ```bash ./target/release/neard init --chain-id=mainnet \ --account-id="<POOL_ID>.poolv1.near" ``` `<POOL_ID>` is the name you want to use for your staking pool. Note that at this point the `<POOL_ID>.poolv1.near` account doesn’t yet exist. We’re going to create it in the next step. This command will create a `~/.near/validator_key.json` file which will contain validator’s private key. It’s a good idea to back this file up in a secure location. For now, read the validator’s public key from this file: ```bash grep public_key ~/.near/validator_key.json ``` ### 4. Deploy `mainnet` Staking Pool {#deploy-staking-pool} You can deploy the staking pool with [near-cli](https://github.com/near/near-cli), using the `near call` command: ```bash near call poolv1.near create_staking_pool '{ "staking_pool_id": "<POOL_ID>", "owner_id": "<OWNER_ID>", "stake_public_key": "<VALIDATOR_KEY>", "reward_fee_fraction": {"numerator": <X>, "denominator": <Y>} }' --account_id <OWNER_ID> --amount 30 --gas 300000000000000 ``` It will invoke the `staking-pool-factory` method from [NEAR Core Contracts](https://github.com/near/core-contracts), passing the following parameters: - `poolv1.near` is the staking pool factory, - `<POOL_ID>` is the name of your validator (and the staking pool associated with it), - `<OWNER_ID>` is the wallet that controls the pool (see [owner-only methods](https://github.com/near/core-contracts/tree/master/staking-pool#owner-only-methods) for more information), - `<VALIDATOR_KEY>` is the validator node public key read in the previous step from the `~/.near/validator_key.json` file, - `{"numerator": <X>, "denominator": <Y>}` sets the validator fees (for example`X=10` and `Y=100` means 10%), - `--amount 30` attaches 30 $NEAR to the transaction to pay the contract storage, - `--gas 300000000000000` specifies the amount of gas for the transaction (optional). Note that if your `<POOL_ID>` is ‘buildlinks’, the staking pool factory will deploy a contract called ‘buildlinks.poolv1.near’, and your node will appear in the Explorer as ‘buildlinks.poolv1.near’. This corresponds to the account identifier used in the previous step. ### 5. Run the validator node {#run-the-node} Once the daemon is built, node is initialized and staking pool created, the validator can be started. To make sure the node has been set up correctly, check that the configuration file located at `~/.near/config.json` is the same as [this mainnet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/mainnet/config.json): ```bash sha1sum <~/.near/config.json curl -s https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/mainnet/config.json | sha1sum ``` If everything is in order, start your node with the following command: ``` ./target/release/neard run ``` You can start your node without the JSON RPC endpoint by running the above command with an additional `--disable-rpc` flag. This reduces resource use and attack vector by closing a listening port. >Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a>
Welcome to NEARCON ‘23: Step Into the Open Web NEAR FOUNDATION November 7, 2023 Hello NEARians! Welcome to the 3rd annual NEARCON in the always lovely and scenic Lisbon, Portugal. The NEAR Community is out in force for NEARCON ‘23, with around 3,000 delegates here to explore the power and possibilities of an open web. A number of exciting protocol and ecosystem announcements are planned over from November 7-10th. We’re thrilled to have you all here to get inspired by talks from renowned authors, economists, artists, politicians, developers, entrepreneurs, and many others helping to build an open web. NEARCON ‘23 is the perfect opportunity to meet and network with a wide variety of projects, speakers, community members, builders, and multi-chain enthusiasts from across the globe. And if you’re here to build, then we look forward to seeing what you put together for the NEAR IRL Hackathon, for which $140K+ in prizes are up for grabs! Finding the NEARCON 23 venues NEARCON ‘23 will unfold across three different venues. NEAR Foundation designed and optimized each space for talks, demonstrations, hackathons, and more. You can find the three NEARCON venues here: NEARCON HQ Convento Do Beato Alameda do Beato 40, 1950-042 Lisboa, Portugal Hacker HQ Armazem 16 R. Pereira Henriques nº1, 1950-242 Lisboa, Portugal Community HQ Rua Pereira Henriques 31950-242 Lisboa, Portugal NCON: What it is and how to use it For NEARCON ‘23, NEAR Foundation partnered with Jutsu, Keypom, and Veriken to create a novel conference experience — the NCON token, an event experience built on the Blockchain Operating System (B.O.S). In many ways, NCON is the embodiment of the open web, where users seamlessly transact with each other on a peer-to-peer network. With NCON, you can attend content sessions, interact with sponsors, pay for your lunch, and more. You can even complete NCON Bounties, for which you’ll be rewarded NCON that can be redeemed for swag, lunches, and other goodies during NEARCON ‘23. More NCON details. Tracks for Developers, Entrepreneurs, Creatives, and Regulators To make this year’s NEARCON even more iconic than last year, we’ve created a diverse set of tracks for attendees. There is something for every type of open web enthusiast. Developers — Devs should drop in on a number of hands-on workshops and coding sessions. These are the best sessions for getting first-hand looks at NEAR’s latest open web innovations. Entrepreneurs — A track designed for the open web entrepreneur. Web3 industry leaders will be on-site to share the best insights, strategies, and advice on turning an idea into the next best open web startup. Creatives — Artists, musicians, marketers, and more are a major part of the NEAR community. The Creatives track is designed to deliver the latest insights into the creative process for NEARCON attendees. Regulators — Top legal and regulatory talent will help open web developers and founders get the latest information on best practices, legal frameworks, and future regulatory development. AI is NEAR: The Future of AI on the Open Web We’re all excited about AI and blockchain, and this is reflected in a special track for NEARCON ’23 — “AI is NEAR”. NEAR co-founder Illia Polosukhin, a pioneer in the world of AI, will be leading the charge. Check out the “AI is NEAR” track over at nearcon.org. Get your badge, beat the lines, and register for the hackathon November 7th is the perfect day to drop by to get your badge and register for the hackathon. Beat the lines and get settled in! You can also drop by the Registration Party sponsored by Octopus Network, G20, and Glass at the Layer 1 Stage (Convento Do Beato). From 5-7pm, join the hackathon orientation and NDC’s Proof of Pizza at Hacker HQ from 5-7pm, then don your party hat for NEARWEEK’s evening party from 7-11pm! A look ahead to NEARCON Day 1 — November 8th Doors open at 9:00am. Join us bright and early for breakfast before a number of welcome sessions from various NEARCON stages, and earn some NCON for being an early riser! NEARCON Day 1 will feature a variety of talks and panels, from NEAR UX and DeFi, to decentralized storage, Web3 community building, and much more. Check out the full Day 1 schedule now to plan for the day’s events!